SemaType.cpp revision 208600
1193326Sed//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements type-related semantic analysis.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "Sema.h"
15193326Sed#include "clang/AST/ASTContext.h"
16198092Srdivacky#include "clang/AST/CXXInheritance.h"
17193326Sed#include "clang/AST/DeclObjC.h"
18193326Sed#include "clang/AST/DeclTemplate.h"
19198092Srdivacky#include "clang/AST/TypeLoc.h"
20198398Srdivacky#include "clang/AST/TypeLocVisitor.h"
21193326Sed#include "clang/AST/Expr.h"
22198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
23193326Sed#include "clang/Parse/DeclSpec.h"
24195341Sed#include "llvm/ADT/SmallPtrSet.h"
25198954Srdivacky#include "llvm/Support/ErrorHandling.h"
26193326Sedusing namespace clang;
27193326Sed
28208600Srdivacky#include <iostream>
29208600Srdivacky
30193326Sed/// \brief Perform adjustment on the parameter type of a function.
31193326Sed///
32193326Sed/// This routine adjusts the given parameter type @p T to the actual
33198092Srdivacky/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
34198092Srdivacky/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
35193326SedQualType Sema::adjustParameterType(QualType T) {
36193326Sed  // C99 6.7.5.3p7:
37198893Srdivacky  //   A declaration of a parameter as "array of type" shall be
38198893Srdivacky  //   adjusted to "qualified pointer to type", where the type
39198893Srdivacky  //   qualifiers (if any) are those specified within the [ and ] of
40198893Srdivacky  //   the array type derivation.
41198893Srdivacky  if (T->isArrayType())
42193326Sed    return Context.getArrayDecayedType(T);
43198893Srdivacky
44198893Srdivacky  // C99 6.7.5.3p8:
45198893Srdivacky  //   A declaration of a parameter as "function returning type"
46198893Srdivacky  //   shall be adjusted to "pointer to function returning type", as
47198893Srdivacky  //   in 6.3.2.1.
48198893Srdivacky  if (T->isFunctionType())
49193326Sed    return Context.getPointerType(T);
50193326Sed
51193326Sed  return T;
52193326Sed}
53193326Sed
54198893Srdivacky
55198893Srdivacky
56198893Srdivacky/// isOmittedBlockReturnType - Return true if this declarator is missing a
57198893Srdivacky/// return type because this is a omitted return type on a block literal.
58198893Srdivackystatic bool isOmittedBlockReturnType(const Declarator &D) {
59198893Srdivacky  if (D.getContext() != Declarator::BlockLiteralContext ||
60198893Srdivacky      D.getDeclSpec().hasTypeSpecifier())
61198893Srdivacky    return false;
62198893Srdivacky
63198893Srdivacky  if (D.getNumTypeObjects() == 0)
64198893Srdivacky    return true;   // ^{ ... }
65198893Srdivacky
66198893Srdivacky  if (D.getNumTypeObjects() == 1 &&
67198893Srdivacky      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
68198893Srdivacky    return true;   // ^(int X, float Y) { ... }
69198893Srdivacky
70198893Srdivacky  return false;
71198893Srdivacky}
72198893Srdivacky
73203955Srdivackytypedef std::pair<const AttributeList*,QualType> DelayedAttribute;
74203955Srdivackytypedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet;
75203955Srdivacky
76203955Srdivackystatic void ProcessTypeAttributeList(Sema &S, QualType &Type,
77204643Srdivacky                                     bool IsDeclSpec,
78203955Srdivacky                                     const AttributeList *Attrs,
79203955Srdivacky                                     DelayedAttributeSet &DelayedFnAttrs);
80203955Srdivackystatic bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr);
81203955Srdivacky
82203955Srdivackystatic void ProcessDelayedFnAttrs(Sema &S, QualType &Type,
83203955Srdivacky                                  DelayedAttributeSet &Attrs) {
84203955Srdivacky  for (DelayedAttributeSet::iterator I = Attrs.begin(),
85203955Srdivacky         E = Attrs.end(); I != E; ++I)
86207619Srdivacky    if (ProcessFnAttr(S, Type, *I->first)) {
87203955Srdivacky      S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
88203955Srdivacky        << I->first->getName() << I->second;
89207619Srdivacky      // Avoid any further processing of this attribute.
90207619Srdivacky      I->first->setInvalid();
91207619Srdivacky    }
92203955Srdivacky  Attrs.clear();
93203955Srdivacky}
94203955Srdivacky
95203955Srdivackystatic void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) {
96203955Srdivacky  for (DelayedAttributeSet::iterator I = Attrs.begin(),
97203955Srdivacky         E = Attrs.end(); I != E; ++I) {
98203955Srdivacky    S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
99203955Srdivacky      << I->first->getName() << I->second;
100207619Srdivacky    // Avoid any further processing of this attribute.
101207619Srdivacky    I->first->setInvalid();
102203955Srdivacky  }
103203955Srdivacky  Attrs.clear();
104203955Srdivacky}
105203955Srdivacky
106193326Sed/// \brief Convert the specified declspec to the appropriate type
107193326Sed/// object.
108198893Srdivacky/// \param D  the declarator containing the declaration specifier.
109193326Sed/// \returns The type described by the declaration specifiers.  This function
110193326Sed/// never returns null.
111203955Srdivackystatic QualType ConvertDeclSpecToType(Sema &TheSema,
112203955Srdivacky                                      Declarator &TheDeclarator,
113203955Srdivacky                                      DelayedAttributeSet &Delayed) {
114193326Sed  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
115193326Sed  // checking.
116198893Srdivacky  const DeclSpec &DS = TheDeclarator.getDeclSpec();
117198893Srdivacky  SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
118198893Srdivacky  if (DeclLoc.isInvalid())
119198893Srdivacky    DeclLoc = DS.getSourceRange().getBegin();
120198893Srdivacky
121198893Srdivacky  ASTContext &Context = TheSema.Context;
122198893Srdivacky
123193326Sed  QualType Result;
124193326Sed  switch (DS.getTypeSpecType()) {
125193326Sed  case DeclSpec::TST_void:
126193326Sed    Result = Context.VoidTy;
127193326Sed    break;
128193326Sed  case DeclSpec::TST_char:
129193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
130193326Sed      Result = Context.CharTy;
131193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
132193326Sed      Result = Context.SignedCharTy;
133193326Sed    else {
134193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
135193326Sed             "Unknown TSS value");
136193326Sed      Result = Context.UnsignedCharTy;
137193326Sed    }
138193326Sed    break;
139193326Sed  case DeclSpec::TST_wchar:
140193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
141193326Sed      Result = Context.WCharTy;
142193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
143198893Srdivacky      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
144193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
145193326Sed      Result = Context.getSignedWCharType();
146193326Sed    } else {
147193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
148193326Sed        "Unknown TSS value");
149198893Srdivacky      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
150193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
151193326Sed      Result = Context.getUnsignedWCharType();
152193326Sed    }
153193326Sed    break;
154198092Srdivacky  case DeclSpec::TST_char16:
155198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
156198092Srdivacky        "Unknown TSS value");
157198092Srdivacky      Result = Context.Char16Ty;
158198092Srdivacky    break;
159198092Srdivacky  case DeclSpec::TST_char32:
160198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
161198092Srdivacky        "Unknown TSS value");
162198092Srdivacky      Result = Context.Char32Ty;
163198092Srdivacky    break;
164193326Sed  case DeclSpec::TST_unspecified:
165193326Sed    // "<proto1,proto2>" is an objc qualified ID with a missing id.
166193326Sed    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
167208600Srdivacky      Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
168208600Srdivacky                                         (ObjCProtocolDecl**)PQ,
169208600Srdivacky                                         DS.getNumProtocolQualifiers());
170208600Srdivacky      Result = Context.getObjCObjectPointerType(Result);
171193326Sed      break;
172193326Sed    }
173198893Srdivacky
174198893Srdivacky    // If this is a missing declspec in a block literal return context, then it
175198893Srdivacky    // is inferred from the return statements inside the block.
176198893Srdivacky    if (isOmittedBlockReturnType(TheDeclarator)) {
177198893Srdivacky      Result = Context.DependentTy;
178198893Srdivacky      break;
179198893Srdivacky    }
180198092Srdivacky
181193326Sed    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
182193326Sed    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
183193326Sed    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
184193326Sed    // Note that the one exception to this is function definitions, which are
185193326Sed    // allowed to be completely missing a declspec.  This is handled in the
186193326Sed    // parser already though by it pretending to have seen an 'int' in this
187193326Sed    // case.
188198893Srdivacky    if (TheSema.getLangOptions().ImplicitInt) {
189193326Sed      // In C89 mode, we only warn if there is a completely missing declspec
190193326Sed      // when one is not allowed.
191193326Sed      if (DS.isEmpty()) {
192198893Srdivacky        TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
193193326Sed          << DS.getSourceRange()
194206084Srdivacky        << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
195193326Sed      }
196193326Sed    } else if (!DS.hasTypeSpecifier()) {
197193326Sed      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
198193326Sed      // "At least one type specifier shall be given in the declaration
199193326Sed      // specifiers in each declaration, and in the specifier-qualifier list in
200193326Sed      // each struct declaration and type name."
201193326Sed      // FIXME: Does Microsoft really have the implicit int extension in C++?
202198893Srdivacky      if (TheSema.getLangOptions().CPlusPlus &&
203198893Srdivacky          !TheSema.getLangOptions().Microsoft) {
204198893Srdivacky        TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
205193326Sed          << DS.getSourceRange();
206198092Srdivacky
207195099Sed        // When this occurs in C++ code, often something is very broken with the
208195099Sed        // value being declared, poison it as invalid so we don't get chains of
209195099Sed        // errors.
210198893Srdivacky        TheDeclarator.setInvalidType(true);
211195099Sed      } else {
212198893Srdivacky        TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
213193326Sed          << DS.getSourceRange();
214195099Sed      }
215193326Sed    }
216198092Srdivacky
217198092Srdivacky    // FALL THROUGH.
218193326Sed  case DeclSpec::TST_int: {
219193326Sed    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
220193326Sed      switch (DS.getTypeSpecWidth()) {
221193326Sed      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
222193326Sed      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
223193326Sed      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
224198893Srdivacky      case DeclSpec::TSW_longlong:
225198893Srdivacky        Result = Context.LongLongTy;
226198893Srdivacky
227198893Srdivacky        // long long is a C99 feature.
228198893Srdivacky        if (!TheSema.getLangOptions().C99 &&
229198893Srdivacky            !TheSema.getLangOptions().CPlusPlus0x)
230198893Srdivacky          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
231198893Srdivacky        break;
232193326Sed      }
233193326Sed    } else {
234193326Sed      switch (DS.getTypeSpecWidth()) {
235193326Sed      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
236193326Sed      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
237193326Sed      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
238198893Srdivacky      case DeclSpec::TSW_longlong:
239198893Srdivacky        Result = Context.UnsignedLongLongTy;
240198893Srdivacky
241198893Srdivacky        // long long is a C99 feature.
242198893Srdivacky        if (!TheSema.getLangOptions().C99 &&
243198893Srdivacky            !TheSema.getLangOptions().CPlusPlus0x)
244198893Srdivacky          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
245198893Srdivacky        break;
246193326Sed      }
247193326Sed    }
248193326Sed    break;
249193326Sed  }
250193326Sed  case DeclSpec::TST_float: Result = Context.FloatTy; break;
251193326Sed  case DeclSpec::TST_double:
252193326Sed    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
253193326Sed      Result = Context.LongDoubleTy;
254193326Sed    else
255193326Sed      Result = Context.DoubleTy;
256193326Sed    break;
257193326Sed  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
258193326Sed  case DeclSpec::TST_decimal32:    // _Decimal32
259193326Sed  case DeclSpec::TST_decimal64:    // _Decimal64
260193326Sed  case DeclSpec::TST_decimal128:   // _Decimal128
261198893Srdivacky    TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
262193326Sed    Result = Context.IntTy;
263198893Srdivacky    TheDeclarator.setInvalidType(true);
264193326Sed    break;
265193326Sed  case DeclSpec::TST_class:
266193326Sed  case DeclSpec::TST_enum:
267193326Sed  case DeclSpec::TST_union:
268193326Sed  case DeclSpec::TST_struct: {
269199482Srdivacky    TypeDecl *D
270199482Srdivacky      = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
271198092Srdivacky    if (!D) {
272198092Srdivacky      // This can happen in C++ with ambiguous lookups.
273198092Srdivacky      Result = Context.IntTy;
274198893Srdivacky      TheDeclarator.setInvalidType(true);
275198092Srdivacky      break;
276198092Srdivacky    }
277198092Srdivacky
278198893Srdivacky    // If the type is deprecated or unavailable, diagnose it.
279198893Srdivacky    TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
280198893Srdivacky
281193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
282198893Srdivacky           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
283198893Srdivacky
284193326Sed    // TypeQuals handled by caller.
285198893Srdivacky    Result = Context.getTypeDeclType(D);
286198092Srdivacky
287198092Srdivacky    // In C++, make an ElaboratedType.
288198893Srdivacky    if (TheSema.getLangOptions().CPlusPlus) {
289208600Srdivacky      ElaboratedTypeKeyword Keyword
290208600Srdivacky        = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
291208600Srdivacky      Result = TheSema.getElaboratedType(Keyword, DS.getTypeSpecScope(),
292208600Srdivacky                                         Result);
293198092Srdivacky    }
294193326Sed    if (D->isInvalidDecl())
295198893Srdivacky      TheDeclarator.setInvalidType(true);
296193326Sed    break;
297198092Srdivacky  }
298193326Sed  case DeclSpec::TST_typename: {
299193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
300193326Sed           DS.getTypeSpecSign() == 0 &&
301193326Sed           "Can't handle qualifiers on typedef names yet!");
302198893Srdivacky    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
303193326Sed
304193326Sed    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
305208600Srdivacky      if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
306208600Srdivacky        // Silently drop any existing protocol qualifiers.
307208600Srdivacky        // TODO: determine whether that's the right thing to do.
308208600Srdivacky        if (ObjT->getNumProtocols())
309208600Srdivacky          Result = ObjT->getBaseType();
310208600Srdivacky
311208600Srdivacky        if (DS.getNumProtocolQualifiers())
312208600Srdivacky          Result = Context.getObjCObjectType(Result,
313208600Srdivacky                                             (ObjCProtocolDecl**) PQ,
314208600Srdivacky                                             DS.getNumProtocolQualifiers());
315208600Srdivacky      } else if (Result->isObjCIdType()) {
316193326Sed        // id<protocol-list>
317208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
318208600Srdivacky                                           (ObjCProtocolDecl**) PQ,
319208600Srdivacky                                           DS.getNumProtocolQualifiers());
320208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
321208600Srdivacky      } else if (Result->isObjCClassType()) {
322193326Sed        // Class<protocol-list>
323208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
324208600Srdivacky                                           (ObjCProtocolDecl**) PQ,
325208600Srdivacky                                           DS.getNumProtocolQualifiers());
326208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
327193326Sed      } else {
328198893Srdivacky        TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
329193326Sed          << DS.getSourceRange();
330198893Srdivacky        TheDeclarator.setInvalidType(true);
331193326Sed      }
332193326Sed    }
333198092Srdivacky
334193326Sed    // TypeQuals handled by caller.
335193326Sed    break;
336193326Sed  }
337193326Sed  case DeclSpec::TST_typeofType:
338198092Srdivacky    // FIXME: Preserve type source info.
339198893Srdivacky    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
340193326Sed    assert(!Result.isNull() && "Didn't get a type for typeof?");
341193326Sed    // TypeQuals handled by caller.
342193326Sed    Result = Context.getTypeOfType(Result);
343193326Sed    break;
344193326Sed  case DeclSpec::TST_typeofExpr: {
345193326Sed    Expr *E = static_cast<Expr *>(DS.getTypeRep());
346193326Sed    assert(E && "Didn't get an expression for typeof?");
347193326Sed    // TypeQuals handled by caller.
348201361Srdivacky    Result = TheSema.BuildTypeofExprType(E);
349201361Srdivacky    if (Result.isNull()) {
350201361Srdivacky      Result = Context.IntTy;
351201361Srdivacky      TheDeclarator.setInvalidType(true);
352201361Srdivacky    }
353193326Sed    break;
354193326Sed  }
355195099Sed  case DeclSpec::TST_decltype: {
356195099Sed    Expr *E = static_cast<Expr *>(DS.getTypeRep());
357195099Sed    assert(E && "Didn't get an expression for decltype?");
358195099Sed    // TypeQuals handled by caller.
359198893Srdivacky    Result = TheSema.BuildDecltypeType(E);
360195341Sed    if (Result.isNull()) {
361195341Sed      Result = Context.IntTy;
362198893Srdivacky      TheDeclarator.setInvalidType(true);
363195341Sed    }
364195099Sed    break;
365195099Sed  }
366195099Sed  case DeclSpec::TST_auto: {
367195099Sed    // TypeQuals handled by caller.
368195099Sed    Result = Context.UndeducedAutoTy;
369195099Sed    break;
370195099Sed  }
371198092Srdivacky
372193326Sed  case DeclSpec::TST_error:
373193326Sed    Result = Context.IntTy;
374198893Srdivacky    TheDeclarator.setInvalidType(true);
375193326Sed    break;
376193326Sed  }
377198092Srdivacky
378193326Sed  // Handle complex types.
379193326Sed  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
380198893Srdivacky    if (TheSema.getLangOptions().Freestanding)
381198893Srdivacky      TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
382193326Sed    Result = Context.getComplexType(Result);
383203955Srdivacky  } else if (DS.isTypeAltiVecVector()) {
384203955Srdivacky    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
385203955Srdivacky    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
386203955Srdivacky    Result = Context.getVectorType(Result, 128/typeSize, true,
387203955Srdivacky      DS.isTypeAltiVecPixel());
388193326Sed  }
389198092Srdivacky
390193326Sed  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
391193326Sed         "FIXME: imaginary types not supported yet!");
392198092Srdivacky
393193326Sed  // See if there are any attributes on the declspec that apply to the type (as
394193326Sed  // opposed to the decl).
395193326Sed  if (const AttributeList *AL = DS.getAttributes())
396204643Srdivacky    ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed);
397198092Srdivacky
398193326Sed  // Apply const/volatile/restrict qualifiers to T.
399193326Sed  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
400193326Sed
401193326Sed    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
402193326Sed    // or incomplete types shall not be restrict-qualified."  C++ also allows
403193326Sed    // restrict-qualified references.
404198092Srdivacky    if (TypeQuals & DeclSpec::TQ_restrict) {
405200583Srdivacky      if (Result->isAnyPointerType() || Result->isReferenceType()) {
406200583Srdivacky        QualType EltTy;
407200583Srdivacky        if (Result->isObjCObjectPointerType())
408200583Srdivacky          EltTy = Result;
409200583Srdivacky        else
410200583Srdivacky          EltTy = Result->isPointerType() ?
411200583Srdivacky                    Result->getAs<PointerType>()->getPointeeType() :
412200583Srdivacky                    Result->getAs<ReferenceType>()->getPointeeType();
413198092Srdivacky
414193326Sed        // If we have a pointer or reference, the pointee must have an object
415193326Sed        // incomplete type.
416193326Sed        if (!EltTy->isIncompleteOrObjectType()) {
417198893Srdivacky          TheSema.Diag(DS.getRestrictSpecLoc(),
418193326Sed               diag::err_typecheck_invalid_restrict_invalid_pointee)
419193326Sed            << EltTy << DS.getSourceRange();
420198092Srdivacky          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
421193326Sed        }
422193326Sed      } else {
423198893Srdivacky        TheSema.Diag(DS.getRestrictSpecLoc(),
424193326Sed             diag::err_typecheck_invalid_restrict_not_pointer)
425193326Sed          << Result << DS.getSourceRange();
426198092Srdivacky        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
427193326Sed      }
428193326Sed    }
429198092Srdivacky
430193326Sed    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
431193326Sed    // of a function type includes any type qualifiers, the behavior is
432193326Sed    // undefined."
433193326Sed    if (Result->isFunctionType() && TypeQuals) {
434193326Sed      // Get some location to point at, either the C or V location.
435193326Sed      SourceLocation Loc;
436198092Srdivacky      if (TypeQuals & DeclSpec::TQ_const)
437193326Sed        Loc = DS.getConstSpecLoc();
438198092Srdivacky      else if (TypeQuals & DeclSpec::TQ_volatile)
439198092Srdivacky        Loc = DS.getVolatileSpecLoc();
440193326Sed      else {
441198092Srdivacky        assert((TypeQuals & DeclSpec::TQ_restrict) &&
442198092Srdivacky               "Has CVR quals but not C, V, or R?");
443198092Srdivacky        Loc = DS.getRestrictSpecLoc();
444193326Sed      }
445198893Srdivacky      TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
446193326Sed        << Result << DS.getSourceRange();
447193326Sed    }
448198092Srdivacky
449193326Sed    // C++ [dcl.ref]p1:
450193326Sed    //   Cv-qualified references are ill-formed except when the
451193326Sed    //   cv-qualifiers are introduced through the use of a typedef
452193326Sed    //   (7.1.3) or of a template type argument (14.3), in which
453193326Sed    //   case the cv-qualifiers are ignored.
454193326Sed    // FIXME: Shouldn't we be checking SCS_typedef here?
455193326Sed    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
456193326Sed        TypeQuals && Result->isReferenceType()) {
457198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_const;
458198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_volatile;
459198092Srdivacky    }
460198092Srdivacky
461198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
462198092Srdivacky    Result = Context.getQualifiedType(Result, Quals);
463193326Sed  }
464198092Srdivacky
465193326Sed  return Result;
466193326Sed}
467193326Sed
468193326Sedstatic std::string getPrintableNameForEntity(DeclarationName Entity) {
469193326Sed  if (Entity)
470193326Sed    return Entity.getAsString();
471198092Srdivacky
472193326Sed  return "type name";
473193326Sed}
474193326Sed
475193326Sed/// \brief Build a pointer type.
476193326Sed///
477193326Sed/// \param T The type to which we'll be building a pointer.
478193326Sed///
479193326Sed/// \param Quals The cvr-qualifiers to be applied to the pointer type.
480193326Sed///
481193326Sed/// \param Loc The location of the entity whose type involves this
482193326Sed/// pointer type or, if there is no such entity, the location of the
483193326Sed/// type that will have pointer type.
484193326Sed///
485193326Sed/// \param Entity The name of the entity that involves the pointer
486193326Sed/// type, if known.
487193326Sed///
488193326Sed/// \returns A suitable pointer type, if there are no
489193326Sed/// errors. Otherwise, returns a NULL type.
490198092SrdivackyQualType Sema::BuildPointerType(QualType T, unsigned Quals,
491193326Sed                                SourceLocation Loc, DeclarationName Entity) {
492193326Sed  if (T->isReferenceType()) {
493193326Sed    // C++ 8.3.2p4: There shall be no ... pointers to references ...
494193326Sed    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
495198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
496193326Sed    return QualType();
497193326Sed  }
498193326Sed
499198092Srdivacky  Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
500198092Srdivacky
501193326Sed  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
502193326Sed  // object or incomplete types shall not be restrict-qualified."
503198092Srdivacky  if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
504193326Sed    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
505193326Sed      << T;
506198092Srdivacky    Qs.removeRestrict();
507193326Sed  }
508193326Sed
509208600Srdivacky  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
510207619Srdivacky
511193326Sed  // Build the pointer type.
512198092Srdivacky  return Context.getQualifiedType(Context.getPointerType(T), Qs);
513193326Sed}
514193326Sed
515193326Sed/// \brief Build a reference type.
516193326Sed///
517193326Sed/// \param T The type to which we'll be building a reference.
518193326Sed///
519198092Srdivacky/// \param CVR The cvr-qualifiers to be applied to the reference type.
520193326Sed///
521193326Sed/// \param Loc The location of the entity whose type involves this
522193326Sed/// reference type or, if there is no such entity, the location of the
523193326Sed/// type that will have reference type.
524193326Sed///
525193326Sed/// \param Entity The name of the entity that involves the reference
526193326Sed/// type, if known.
527193326Sed///
528193326Sed/// \returns A suitable reference type, if there are no
529193326Sed/// errors. Otherwise, returns a NULL type.
530198398SrdivackyQualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
531198398Srdivacky                                  unsigned CVR, SourceLocation Loc,
532198398Srdivacky                                  DeclarationName Entity) {
533198092Srdivacky  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
534193326Sed
535198398Srdivacky  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
536198398Srdivacky
537198398Srdivacky  // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
538198398Srdivacky  //   reference to a type T, and attempt to create the type "lvalue
539198398Srdivacky  //   reference to cv TD" creates the type "lvalue reference to T".
540198398Srdivacky  // We use the qualifiers (restrict or none) of the original reference,
541198398Srdivacky  // not the new ones. This is consistent with GCC.
542198398Srdivacky
543198398Srdivacky  // C++ [dcl.ref]p4: There shall be no references to references.
544198398Srdivacky  //
545198398Srdivacky  // According to C++ DR 106, references to references are only
546198398Srdivacky  // diagnosed when they are written directly (e.g., "int & &"),
547198398Srdivacky  // but not when they happen via a typedef:
548198398Srdivacky  //
549198398Srdivacky  //   typedef int& intref;
550198398Srdivacky  //   typedef intref& intref2;
551198398Srdivacky  //
552198398Srdivacky  // Parser::ParseDeclaratorInternal diagnoses the case where
553198398Srdivacky  // references are written directly; here, we handle the
554198398Srdivacky  // collapsing of references-to-references as described in C++
555198398Srdivacky  // DR 106 and amended by C++ DR 540.
556198398Srdivacky
557193326Sed  // C++ [dcl.ref]p1:
558198092Srdivacky  //   A declarator that specifies the type "reference to cv void"
559193326Sed  //   is ill-formed.
560193326Sed  if (T->isVoidType()) {
561193326Sed    Diag(Loc, diag::err_reference_to_void);
562193326Sed    return QualType();
563193326Sed  }
564193326Sed
565193326Sed  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
566193326Sed  // object or incomplete types shall not be restrict-qualified."
567198092Srdivacky  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
568193326Sed    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
569193326Sed      << T;
570198092Srdivacky    Quals.removeRestrict();
571193326Sed  }
572193326Sed
573193326Sed  // C++ [dcl.ref]p1:
574193326Sed  //   [...] Cv-qualified references are ill-formed except when the
575193326Sed  //   cv-qualifiers are introduced through the use of a typedef
576193326Sed  //   (7.1.3) or of a template type argument (14.3), in which case
577193326Sed  //   the cv-qualifiers are ignored.
578193326Sed  //
579193326Sed  // We diagnose extraneous cv-qualifiers for the non-typedef,
580193326Sed  // non-template type argument case within the parser. Here, we just
581193326Sed  // ignore any extraneous cv-qualifiers.
582198092Srdivacky  Quals.removeConst();
583198092Srdivacky  Quals.removeVolatile();
584193326Sed
585193326Sed  // Handle restrict on references.
586193326Sed  if (LValueRef)
587198398Srdivacky    return Context.getQualifiedType(
588198398Srdivacky               Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
589198092Srdivacky  return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
590193326Sed}
591193326Sed
592193326Sed/// \brief Build an array type.
593193326Sed///
594193326Sed/// \param T The type of each element in the array.
595193326Sed///
596193326Sed/// \param ASM C99 array size modifier (e.g., '*', 'static').
597193326Sed///
598198092Srdivacky/// \param ArraySize Expression describing the size of the array.
599198092Srdivacky///
600193326Sed/// \param Quals The cvr-qualifiers to be applied to the array's
601193326Sed/// element type.
602193326Sed///
603193326Sed/// \param Loc The location of the entity whose type involves this
604193326Sed/// array type or, if there is no such entity, the location of the
605193326Sed/// type that will have array type.
606193326Sed///
607193326Sed/// \param Entity The name of the entity that involves the array
608193326Sed/// type, if known.
609193326Sed///
610193326Sed/// \returns A suitable array type, if there are no errors. Otherwise,
611193326Sed/// returns a NULL type.
612193326SedQualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
613193326Sed                              Expr *ArraySize, unsigned Quals,
614198092Srdivacky                              SourceRange Brackets, DeclarationName Entity) {
615198092Srdivacky
616198092Srdivacky  SourceLocation Loc = Brackets.getBegin();
617198954Srdivacky  if (getLangOptions().CPlusPlus) {
618207619Srdivacky    // C++ [dcl.array]p1:
619207619Srdivacky    //   T is called the array element type; this type shall not be a reference
620207619Srdivacky    //   type, the (possibly cv-qualified) type void, a function type or an
621207619Srdivacky    //   abstract class type.
622207619Srdivacky    //
623207619Srdivacky    // Note: function types are handled in the common path with C.
624207619Srdivacky    if (T->isReferenceType()) {
625207619Srdivacky      Diag(Loc, diag::err_illegal_decl_array_of_references)
626207619Srdivacky      << getPrintableNameForEntity(Entity) << T;
627207619Srdivacky      return QualType();
628207619Srdivacky    }
629207619Srdivacky
630198954Srdivacky    if (T->isVoidType()) {
631198954Srdivacky      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
632198954Srdivacky      return QualType();
633198954Srdivacky    }
634207619Srdivacky
635207619Srdivacky    if (RequireNonAbstractType(Brackets.getBegin(), T,
636207619Srdivacky                               diag::err_array_of_abstract_type))
637207619Srdivacky      return QualType();
638207619Srdivacky
639198954Srdivacky  } else {
640207619Srdivacky    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
641207619Srdivacky    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
642198954Srdivacky    if (RequireCompleteType(Loc, T,
643198954Srdivacky                            diag::err_illegal_decl_array_incomplete_type))
644198954Srdivacky      return QualType();
645198954Srdivacky  }
646193326Sed
647193326Sed  if (T->isFunctionType()) {
648193326Sed    Diag(Loc, diag::err_illegal_decl_array_of_functions)
649198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
650193326Sed    return QualType();
651193326Sed  }
652198092Srdivacky
653195099Sed  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
654198092Srdivacky    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
655195099Sed      << getPrintableNameForEntity(Entity);
656195099Sed    return QualType();
657195099Sed  }
658198092Srdivacky
659198092Srdivacky  if (const RecordType *EltTy = T->getAs<RecordType>()) {
660193326Sed    // If the element type is a struct or union that contains a variadic
661193326Sed    // array, accept it as a GNU extension: C99 6.7.2.1p2.
662193326Sed    if (EltTy->getDecl()->hasFlexibleArrayMember())
663193326Sed      Diag(Loc, diag::ext_flexible_array_in_array) << T;
664208600Srdivacky  } else if (T->isObjCObjectType()) {
665193326Sed    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
666193326Sed    return QualType();
667193326Sed  }
668198092Srdivacky
669193326Sed  // C99 6.7.5.2p1: The size expression shall have integer type.
670193326Sed  if (ArraySize && !ArraySize->isTypeDependent() &&
671193326Sed      !ArraySize->getType()->isIntegerType()) {
672193326Sed    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
673193326Sed      << ArraySize->getType() << ArraySize->getSourceRange();
674193326Sed    ArraySize->Destroy(Context);
675193326Sed    return QualType();
676193326Sed  }
677193326Sed  llvm::APSInt ConstVal(32);
678193326Sed  if (!ArraySize) {
679193326Sed    if (ASM == ArrayType::Star)
680198092Srdivacky      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
681193326Sed    else
682193326Sed      T = Context.getIncompleteArrayType(T, ASM, Quals);
683208600Srdivacky  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
684198092Srdivacky    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
685193326Sed  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
686198954Srdivacky             (!T->isDependentType() && !T->isIncompleteType() &&
687198954Srdivacky              !T->isConstantSizeType())) {
688193326Sed    // Per C99, a variable array is an array with either a non-constant
689193326Sed    // size or an element type that has a non-constant-size
690198092Srdivacky    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
691193326Sed  } else {
692193326Sed    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
693193326Sed    // have a value greater than zero.
694198954Srdivacky    if (ConstVal.isSigned() && ConstVal.isNegative()) {
695198954Srdivacky      Diag(ArraySize->getLocStart(),
696198954Srdivacky           diag::err_typecheck_negative_array_size)
697198954Srdivacky        << ArraySize->getSourceRange();
698198954Srdivacky      return QualType();
699198092Srdivacky    }
700198954Srdivacky    if (ConstVal == 0) {
701206084Srdivacky      // GCC accepts zero sized static arrays. We allow them when
702206084Srdivacky      // we're not in a SFINAE context.
703206084Srdivacky      Diag(ArraySize->getLocStart(),
704206084Srdivacky           isSFINAEContext()? diag::err_typecheck_zero_array_size
705206084Srdivacky                            : diag::ext_typecheck_zero_array_size)
706198954Srdivacky        << ArraySize->getSourceRange();
707198954Srdivacky    }
708198398Srdivacky    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
709193326Sed  }
710193326Sed  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
711193326Sed  if (!getLangOptions().C99) {
712208600Srdivacky    if (T->isVariableArrayType()) {
713208600Srdivacky      // Prohibit the use of non-POD types in VLAs.
714208600Srdivacky      if (!T->isDependentType() &&
715208600Srdivacky          !Context.getBaseElementType(T)->isPODType()) {
716208600Srdivacky        Diag(Loc, diag::err_vla_non_pod)
717208600Srdivacky          << Context.getBaseElementType(T);
718208600Srdivacky        return QualType();
719208600Srdivacky      }
720208600Srdivacky      // Prohibit the use of VLAs during template argument deduction.
721208600Srdivacky      else if (isSFINAEContext()) {
722208600Srdivacky        Diag(Loc, diag::err_vla_in_sfinae);
723208600Srdivacky        return QualType();
724208600Srdivacky      }
725208600Srdivacky      // Just extwarn about VLAs.
726208600Srdivacky      else
727208600Srdivacky        Diag(Loc, diag::ext_vla);
728208600Srdivacky    } else if (ASM != ArrayType::Normal || Quals != 0)
729198092Srdivacky      Diag(Loc,
730198092Srdivacky           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
731198092Srdivacky                                     : diag::ext_c99_array_usage);
732193326Sed  }
733193326Sed
734193326Sed  return T;
735193326Sed}
736194613Sed
737194613Sed/// \brief Build an ext-vector type.
738194613Sed///
739194613Sed/// Run the required checks for the extended vector type.
740198092SrdivackyQualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
741194613Sed                                  SourceLocation AttrLoc) {
742194613Sed
743194613Sed  Expr *Arg = (Expr *)ArraySize.get();
744194613Sed
745194613Sed  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
746194613Sed  // in conjunction with complex types (pointers, arrays, functions, etc.).
747198092Srdivacky  if (!T->isDependentType() &&
748194613Sed      !T->isIntegerType() && !T->isRealFloatingType()) {
749194613Sed    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
750194613Sed    return QualType();
751194613Sed  }
752194613Sed
753194613Sed  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
754194613Sed    llvm::APSInt vecSize(32);
755194613Sed    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
756194613Sed      Diag(AttrLoc, diag::err_attribute_argument_not_int)
757194613Sed      << "ext_vector_type" << Arg->getSourceRange();
758194613Sed      return QualType();
759194613Sed    }
760198092Srdivacky
761198092Srdivacky    // unlike gcc's vector_size attribute, the size is specified as the
762194613Sed    // number of elements, not the number of bytes.
763198092Srdivacky    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
764198092Srdivacky
765194613Sed    if (vectorSize == 0) {
766194613Sed      Diag(AttrLoc, diag::err_attribute_zero_size)
767194613Sed      << Arg->getSourceRange();
768194613Sed      return QualType();
769194613Sed    }
770198092Srdivacky
771194613Sed    if (!T->isDependentType())
772194613Sed      return Context.getExtVectorType(T, vectorSize);
773198092Srdivacky  }
774198092Srdivacky
775198092Srdivacky  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
776194613Sed                                                AttrLoc);
777194613Sed}
778198092Srdivacky
779193326Sed/// \brief Build a function type.
780193326Sed///
781193326Sed/// This routine checks the function type according to C++ rules and
782193326Sed/// under the assumption that the result type and parameter types have
783193326Sed/// just been instantiated from a template. It therefore duplicates
784193326Sed/// some of the behavior of GetTypeForDeclarator, but in a much
785193326Sed/// simpler form that is only suitable for this narrow use case.
786193326Sed///
787193326Sed/// \param T The return type of the function.
788193326Sed///
789193326Sed/// \param ParamTypes The parameter types of the function. This array
790193326Sed/// will be modified to account for adjustments to the types of the
791193326Sed/// function parameters.
792193326Sed///
793193326Sed/// \param NumParamTypes The number of parameter types in ParamTypes.
794193326Sed///
795193326Sed/// \param Variadic Whether this is a variadic function type.
796193326Sed///
797193326Sed/// \param Quals The cvr-qualifiers to be applied to the function type.
798193326Sed///
799193326Sed/// \param Loc The location of the entity whose type involves this
800193326Sed/// function type or, if there is no such entity, the location of the
801193326Sed/// type that will have function type.
802193326Sed///
803193326Sed/// \param Entity The name of the entity that involves the function
804193326Sed/// type, if known.
805193326Sed///
806193326Sed/// \returns A suitable function type, if there are no
807193326Sed/// errors. Otherwise, returns a NULL type.
808193326SedQualType Sema::BuildFunctionType(QualType T,
809198092Srdivacky                                 QualType *ParamTypes,
810193326Sed                                 unsigned NumParamTypes,
811193326Sed                                 bool Variadic, unsigned Quals,
812193326Sed                                 SourceLocation Loc, DeclarationName Entity) {
813193326Sed  if (T->isArrayType() || T->isFunctionType()) {
814202379Srdivacky    Diag(Loc, diag::err_func_returning_array_function)
815202379Srdivacky      << T->isFunctionType() << T;
816193326Sed    return QualType();
817193326Sed  }
818198092Srdivacky
819193326Sed  bool Invalid = false;
820193326Sed  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
821193326Sed    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
822193326Sed    if (ParamType->isVoidType()) {
823193326Sed      Diag(Loc, diag::err_param_with_void_type);
824193326Sed      Invalid = true;
825193326Sed    }
826193326Sed
827198398Srdivacky    ParamTypes[Idx] = ParamType;
828193326Sed  }
829193326Sed
830193326Sed  if (Invalid)
831193326Sed    return QualType();
832193326Sed
833198092Srdivacky  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
834206084Srdivacky                                 Quals, false, false, 0, 0,
835206084Srdivacky                                 FunctionType::ExtInfo());
836193326Sed}
837198092Srdivacky
838194179Sed/// \brief Build a member pointer type \c T Class::*.
839194179Sed///
840194179Sed/// \param T the type to which the member pointer refers.
841194179Sed/// \param Class the class type into which the member pointer points.
842198092Srdivacky/// \param CVR Qualifiers applied to the member pointer type
843194179Sed/// \param Loc the location where this type begins
844194179Sed/// \param Entity the name of the entity that will have this member pointer type
845194179Sed///
846194179Sed/// \returns a member pointer type, if successful, or a NULL type if there was
847194179Sed/// an error.
848198092SrdivackyQualType Sema::BuildMemberPointerType(QualType T, QualType Class,
849198092Srdivacky                                      unsigned CVR, SourceLocation Loc,
850194179Sed                                      DeclarationName Entity) {
851198092Srdivacky  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
852198092Srdivacky
853194179Sed  // Verify that we're not building a pointer to pointer to function with
854194179Sed  // exception specification.
855194179Sed  if (CheckDistantExceptionSpec(T)) {
856194179Sed    Diag(Loc, diag::err_distant_exception_spec);
857194179Sed
858194179Sed    // FIXME: If we're doing this as part of template instantiation,
859194179Sed    // we should return immediately.
860194179Sed
861194179Sed    // Build the type anyway, but use the canonical type so that the
862194179Sed    // exception specifiers are stripped off.
863194179Sed    T = Context.getCanonicalType(T);
864194179Sed  }
865194179Sed
866194179Sed  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
867194179Sed  //   with reference type, or "cv void."
868194179Sed  if (T->isReferenceType()) {
869195341Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
870198893Srdivacky      << (Entity? Entity.getAsString() : "type name") << T;
871194179Sed    return QualType();
872194179Sed  }
873194179Sed
874194179Sed  if (T->isVoidType()) {
875194179Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
876194179Sed      << (Entity? Entity.getAsString() : "type name");
877194179Sed    return QualType();
878194179Sed  }
879194179Sed
880194179Sed  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
881194179Sed  // object or incomplete types shall not be restrict-qualified."
882198092Srdivacky  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
883194179Sed    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
884194179Sed      << T;
885194179Sed
886194179Sed    // FIXME: If we're doing this as part of template instantiation,
887194179Sed    // we should return immediately.
888198092Srdivacky    Quals.removeRestrict();
889194179Sed  }
890194179Sed
891194179Sed  if (!Class->isDependentType() && !Class->isRecordType()) {
892194179Sed    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
893194179Sed    return QualType();
894194179Sed  }
895194179Sed
896198092Srdivacky  return Context.getQualifiedType(
897198092Srdivacky           Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
898194179Sed}
899198092Srdivacky
900194179Sed/// \brief Build a block pointer type.
901194179Sed///
902194179Sed/// \param T The type to which we'll be building a block pointer.
903194179Sed///
904198092Srdivacky/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
905194179Sed///
906194179Sed/// \param Loc The location of the entity whose type involves this
907194179Sed/// block pointer type or, if there is no such entity, the location of the
908194179Sed/// type that will have block pointer type.
909194179Sed///
910194179Sed/// \param Entity The name of the entity that involves the block pointer
911194179Sed/// type, if known.
912194179Sed///
913194179Sed/// \returns A suitable block pointer type, if there are no
914194179Sed/// errors. Otherwise, returns a NULL type.
915198092SrdivackyQualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
916198092Srdivacky                                     SourceLocation Loc,
917194179Sed                                     DeclarationName Entity) {
918198092Srdivacky  if (!T->isFunctionType()) {
919194179Sed    Diag(Loc, diag::err_nonfunction_block_type);
920194179Sed    return QualType();
921194179Sed  }
922198092Srdivacky
923198092Srdivacky  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
924198092Srdivacky  return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
925194179Sed}
926194179Sed
927200583SrdivackyQualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) {
928198092Srdivacky  QualType QT = QualType::getFromOpaquePtr(Ty);
929198893Srdivacky  if (QT.isNull()) {
930200583Srdivacky    if (TInfo) *TInfo = 0;
931198893Srdivacky    return QualType();
932198893Srdivacky  }
933198893Srdivacky
934200583Srdivacky  TypeSourceInfo *DI = 0;
935198092Srdivacky  if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
936198092Srdivacky    QT = LIT->getType();
937200583Srdivacky    DI = LIT->getTypeSourceInfo();
938198092Srdivacky  }
939198092Srdivacky
940200583Srdivacky  if (TInfo) *TInfo = DI;
941198092Srdivacky  return QT;
942198092Srdivacky}
943198092Srdivacky
944193326Sed/// GetTypeForDeclarator - Convert the type for the specified
945198893Srdivacky/// declarator to Type instances.
946193326Sed///
947193326Sed/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
948193326Sed/// owns the declaration of a type (e.g., the definition of a struct
949193326Sed/// type), then *OwnedDecl will receive the owned declaration.
950198092SrdivackyQualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
951200583Srdivacky                                    TypeSourceInfo **TInfo,
952193326Sed                                    TagDecl **OwnedDecl) {
953193326Sed  // Determine the type of the declarator. Not all forms of declarator
954193326Sed  // have a type.
955193326Sed  QualType T;
956207619Srdivacky  TypeSourceInfo *ReturnTypeInfo = 0;
957207619Srdivacky
958203955Srdivacky  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec;
959203955Srdivacky
960198893Srdivacky  switch (D.getName().getKind()) {
961198893Srdivacky  case UnqualifiedId::IK_Identifier:
962198893Srdivacky  case UnqualifiedId::IK_OperatorFunctionId:
963199990Srdivacky  case UnqualifiedId::IK_LiteralOperatorId:
964198893Srdivacky  case UnqualifiedId::IK_TemplateId:
965203955Srdivacky    T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec);
966198893Srdivacky
967203955Srdivacky    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
968203955Srdivacky      TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
969203955Srdivacky      // Owned is embedded if it was defined here, or if it is the
970203955Srdivacky      // very first (i.e., canonical) declaration of this tag type.
971203955Srdivacky      Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
972203955Srdivacky                                     Owned->isCanonicalDecl());
973203955Srdivacky      if (OwnedDecl) *OwnedDecl = Owned;
974203955Srdivacky    }
975193326Sed    break;
976193326Sed
977198893Srdivacky  case UnqualifiedId::IK_ConstructorName:
978202379Srdivacky  case UnqualifiedId::IK_ConstructorTemplateId:
979198893Srdivacky  case UnqualifiedId::IK_DestructorName:
980193326Sed    // Constructors and destructors don't have return types. Use
981202379Srdivacky    // "void" instead.
982193326Sed    T = Context.VoidTy;
983207619Srdivacky
984207619Srdivacky    if (TInfo)
985207619Srdivacky      ReturnTypeInfo = Context.getTrivialTypeSourceInfo(T,
986207619Srdivacky                                                    D.getName().StartLocation);
987193326Sed    break;
988202379Srdivacky
989202379Srdivacky  case UnqualifiedId::IK_ConversionFunctionId:
990202379Srdivacky    // The result type of a conversion function is the type that it
991202379Srdivacky    // converts to.
992207619Srdivacky    T = GetTypeFromParser(D.getName().ConversionFunctionId,
993207619Srdivacky                          TInfo? &ReturnTypeInfo : 0);
994202379Srdivacky    break;
995193326Sed  }
996198092Srdivacky
997200583Srdivacky  if (T.isNull())
998200583Srdivacky    return T;
999200583Srdivacky
1000195099Sed  if (T == Context.UndeducedAutoTy) {
1001195099Sed    int Error = -1;
1002198092Srdivacky
1003195099Sed    switch (D.getContext()) {
1004195099Sed    case Declarator::KNRTypeListContext:
1005195099Sed      assert(0 && "K&R type lists aren't allowed in C++");
1006195099Sed      break;
1007195099Sed    case Declarator::PrototypeContext:
1008195099Sed      Error = 0; // Function prototype
1009195099Sed      break;
1010195099Sed    case Declarator::MemberContext:
1011195099Sed      switch (cast<TagDecl>(CurContext)->getTagKind()) {
1012208600Srdivacky      case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1013208600Srdivacky      case TTK_Struct: Error = 1; /* Struct member */ break;
1014208600Srdivacky      case TTK_Union:  Error = 2; /* Union member */ break;
1015208600Srdivacky      case TTK_Class:  Error = 3; /* Class member */ break;
1016198092Srdivacky      }
1017195099Sed      break;
1018195099Sed    case Declarator::CXXCatchContext:
1019195099Sed      Error = 4; // Exception declaration
1020195099Sed      break;
1021195099Sed    case Declarator::TemplateParamContext:
1022195099Sed      Error = 5; // Template parameter
1023195099Sed      break;
1024195099Sed    case Declarator::BlockLiteralContext:
1025195099Sed      Error = 6;  // Block literal
1026195099Sed      break;
1027195099Sed    case Declarator::FileContext:
1028195099Sed    case Declarator::BlockContext:
1029195099Sed    case Declarator::ForContext:
1030195099Sed    case Declarator::ConditionContext:
1031195099Sed    case Declarator::TypeNameContext:
1032195099Sed      break;
1033195099Sed    }
1034195099Sed
1035195099Sed    if (Error != -1) {
1036195099Sed      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1037195099Sed        << Error;
1038195099Sed      T = Context.IntTy;
1039195099Sed      D.setInvalidType(true);
1040195099Sed    }
1041195099Sed  }
1042198092Srdivacky
1043193326Sed  // The name we're declaring, if any.
1044193326Sed  DeclarationName Name;
1045193326Sed  if (D.getIdentifier())
1046193326Sed    Name = D.getIdentifier();
1047193326Sed
1048203955Srdivacky  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk;
1049203955Srdivacky
1050193326Sed  // Walk the DeclTypeInfo, building the recursive type as we go.
1051193326Sed  // DeclTypeInfos are ordered from the identifier out, which is
1052193326Sed  // opposite of what we want :).
1053198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1054198893Srdivacky    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
1055193326Sed    switch (DeclType.Kind) {
1056193326Sed    default: assert(0 && "Unknown decltype!");
1057193326Sed    case DeclaratorChunk::BlockPointer:
1058193326Sed      // If blocks are disabled, emit an error.
1059193326Sed      if (!LangOpts.Blocks)
1060193326Sed        Diag(DeclType.Loc, diag::err_blocks_disable);
1061198092Srdivacky
1062198092Srdivacky      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
1063194179Sed                                Name);
1064193326Sed      break;
1065193326Sed    case DeclaratorChunk::Pointer:
1066193326Sed      // Verify that we're not building a pointer to pointer to function with
1067193326Sed      // exception specification.
1068193326Sed      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1069193326Sed        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1070193326Sed        D.setInvalidType(true);
1071193326Sed        // Build the type anyway.
1072193326Sed      }
1073208600Srdivacky      if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1074208600Srdivacky        T = Context.getObjCObjectPointerType(T);
1075208600Srdivacky        T = Context.getCVRQualifiedType(T, DeclType.Ptr.TypeQuals);
1076198092Srdivacky        break;
1077198092Srdivacky      }
1078193326Sed      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
1079193326Sed      break;
1080198092Srdivacky    case DeclaratorChunk::Reference: {
1081198092Srdivacky      Qualifiers Quals;
1082198092Srdivacky      if (DeclType.Ref.HasRestrict) Quals.addRestrict();
1083198092Srdivacky
1084193326Sed      // Verify that we're not building a reference to pointer to function with
1085193326Sed      // exception specification.
1086193326Sed      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1087193326Sed        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1088193326Sed        D.setInvalidType(true);
1089193326Sed        // Build the type anyway.
1090193326Sed      }
1091198092Srdivacky      T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
1092193326Sed                             DeclType.Loc, Name);
1093193326Sed      break;
1094198092Srdivacky    }
1095193326Sed    case DeclaratorChunk::Array: {
1096193326Sed      // Verify that we're not building an array of pointers to function with
1097193326Sed      // exception specification.
1098193326Sed      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1099193326Sed        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1100193326Sed        D.setInvalidType(true);
1101193326Sed        // Build the type anyway.
1102193326Sed      }
1103193326Sed      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1104193326Sed      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1105193326Sed      ArrayType::ArraySizeModifier ASM;
1106193326Sed      if (ATI.isStar)
1107193326Sed        ASM = ArrayType::Star;
1108193326Sed      else if (ATI.hasStatic)
1109193326Sed        ASM = ArrayType::Static;
1110193326Sed      else
1111193326Sed        ASM = ArrayType::Normal;
1112193326Sed      if (ASM == ArrayType::Star &&
1113193326Sed          D.getContext() != Declarator::PrototypeContext) {
1114193326Sed        // FIXME: This check isn't quite right: it allows star in prototypes
1115193326Sed        // for function definitions, and disallows some edge cases detailed
1116193326Sed        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1117193326Sed        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1118193326Sed        ASM = ArrayType::Normal;
1119193326Sed        D.setInvalidType(true);
1120193326Sed      }
1121198092Srdivacky      T = BuildArrayType(T, ASM, ArraySize,
1122198092Srdivacky                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1123198092Srdivacky                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1124193326Sed      break;
1125193326Sed    }
1126193326Sed    case DeclaratorChunk::Function: {
1127193326Sed      // If the function declarator has a prototype (i.e. it is not () and
1128193326Sed      // does not have a K&R-style identifier list), then the arguments are part
1129193326Sed      // of the type, otherwise the argument list is ().
1130193326Sed      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1131193326Sed
1132193326Sed      // C99 6.7.5.3p1: The return type may not be a function or array type.
1133202379Srdivacky      // For conversion functions, we'll diagnose this particular error later.
1134202379Srdivacky      if ((T->isArrayType() || T->isFunctionType()) &&
1135202379Srdivacky          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1136202379Srdivacky        Diag(DeclType.Loc, diag::err_func_returning_array_function)
1137202379Srdivacky          << T->isFunctionType() << T;
1138193326Sed        T = Context.IntTy;
1139193326Sed        D.setInvalidType(true);
1140193326Sed      }
1141193326Sed
1142193326Sed      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1143193326Sed        // C++ [dcl.fct]p6:
1144193326Sed        //   Types shall not be defined in return or parameter types.
1145193326Sed        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1146193326Sed        if (Tag->isDefinition())
1147193326Sed          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1148193326Sed            << Context.getTypeDeclType(Tag);
1149193326Sed      }
1150193326Sed
1151193326Sed      // Exception specs are not allowed in typedefs. Complain, but add it
1152193326Sed      // anyway.
1153193326Sed      if (FTI.hasExceptionSpec &&
1154193326Sed          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1155193326Sed        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1156193326Sed
1157193326Sed      if (FTI.NumArgs == 0) {
1158193326Sed        if (getLangOptions().CPlusPlus) {
1159193326Sed          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1160193326Sed          // function takes no arguments.
1161193326Sed          llvm::SmallVector<QualType, 4> Exceptions;
1162193326Sed          Exceptions.reserve(FTI.NumExceptions);
1163198092Srdivacky          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1164198092Srdivacky            // FIXME: Preserve type source info.
1165198092Srdivacky            QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1166193326Sed            // Check that the type is valid for an exception spec, and drop it
1167193326Sed            // if not.
1168193326Sed            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1169193326Sed              Exceptions.push_back(ET);
1170193326Sed          }
1171193326Sed          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1172193326Sed                                      FTI.hasExceptionSpec,
1173193326Sed                                      FTI.hasAnyExceptionSpec,
1174204643Srdivacky                                      Exceptions.size(), Exceptions.data(),
1175206084Srdivacky                                      FunctionType::ExtInfo());
1176193326Sed        } else if (FTI.isVariadic) {
1177193326Sed          // We allow a zero-parameter variadic function in C if the
1178193326Sed          // function is marked with the "overloadable"
1179193326Sed          // attribute. Scan for this attribute now.
1180193326Sed          bool Overloadable = false;
1181193326Sed          for (const AttributeList *Attrs = D.getAttributes();
1182193326Sed               Attrs; Attrs = Attrs->getNext()) {
1183193326Sed            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1184193326Sed              Overloadable = true;
1185193326Sed              break;
1186193326Sed            }
1187193326Sed          }
1188193326Sed
1189193326Sed          if (!Overloadable)
1190193326Sed            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1191204643Srdivacky          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0,
1192206084Srdivacky                                      false, false, 0, 0,
1193206084Srdivacky                                      FunctionType::ExtInfo());
1194193326Sed        } else {
1195193326Sed          // Simple void foo(), where the incoming T is the result type.
1196193326Sed          T = Context.getFunctionNoProtoType(T);
1197193326Sed        }
1198193326Sed      } else if (FTI.ArgInfo[0].Param == 0) {
1199193326Sed        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1200198092Srdivacky        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1201198398Srdivacky        D.setInvalidType(true);
1202193326Sed      } else {
1203193326Sed        // Otherwise, we have a function with an argument list that is
1204193326Sed        // potentially variadic.
1205193326Sed        llvm::SmallVector<QualType, 16> ArgTys;
1206198092Srdivacky
1207193326Sed        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1208193326Sed          ParmVarDecl *Param =
1209193326Sed            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1210193326Sed          QualType ArgTy = Param->getType();
1211193326Sed          assert(!ArgTy.isNull() && "Couldn't parse type?");
1212193326Sed
1213193326Sed          // Adjust the parameter type.
1214193326Sed          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1215193326Sed
1216193326Sed          // Look for 'void'.  void is allowed only as a single argument to a
1217193326Sed          // function with no other parameters (C99 6.7.5.3p10).  We record
1218193326Sed          // int(void) as a FunctionProtoType with an empty argument list.
1219193326Sed          if (ArgTy->isVoidType()) {
1220193326Sed            // If this is something like 'float(int, void)', reject it.  'void'
1221193326Sed            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1222193326Sed            // have arguments of incomplete type.
1223193326Sed            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1224193326Sed              Diag(DeclType.Loc, diag::err_void_only_param);
1225193326Sed              ArgTy = Context.IntTy;
1226193326Sed              Param->setType(ArgTy);
1227193326Sed            } else if (FTI.ArgInfo[i].Ident) {
1228193326Sed              // Reject, but continue to parse 'int(void abc)'.
1229193326Sed              Diag(FTI.ArgInfo[i].IdentLoc,
1230193326Sed                   diag::err_param_with_void_type);
1231193326Sed              ArgTy = Context.IntTy;
1232193326Sed              Param->setType(ArgTy);
1233193326Sed            } else {
1234193326Sed              // Reject, but continue to parse 'float(const void)'.
1235198092Srdivacky              if (ArgTy.hasQualifiers())
1236193326Sed                Diag(DeclType.Loc, diag::err_void_param_qualified);
1237198092Srdivacky
1238193326Sed              // Do not add 'void' to the ArgTys list.
1239193326Sed              break;
1240193326Sed            }
1241193326Sed          } else if (!FTI.hasPrototype) {
1242193326Sed            if (ArgTy->isPromotableIntegerType()) {
1243198092Srdivacky              ArgTy = Context.getPromotedIntegerType(ArgTy);
1244198092Srdivacky            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1245193326Sed              if (BTy->getKind() == BuiltinType::Float)
1246193326Sed                ArgTy = Context.DoubleTy;
1247193326Sed            }
1248193326Sed          }
1249198092Srdivacky
1250198398Srdivacky          ArgTys.push_back(ArgTy);
1251193326Sed        }
1252193326Sed
1253193326Sed        llvm::SmallVector<QualType, 4> Exceptions;
1254193326Sed        Exceptions.reserve(FTI.NumExceptions);
1255198092Srdivacky        for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1256198092Srdivacky          // FIXME: Preserve type source info.
1257198092Srdivacky          QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1258193326Sed          // Check that the type is valid for an exception spec, and drop it if
1259193326Sed          // not.
1260193326Sed          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1261193326Sed            Exceptions.push_back(ET);
1262193326Sed        }
1263193326Sed
1264193326Sed        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1265193326Sed                                    FTI.isVariadic, FTI.TypeQuals,
1266193326Sed                                    FTI.hasExceptionSpec,
1267193326Sed                                    FTI.hasAnyExceptionSpec,
1268204643Srdivacky                                    Exceptions.size(), Exceptions.data(),
1269206084Srdivacky                                    FunctionType::ExtInfo());
1270193326Sed      }
1271203955Srdivacky
1272203955Srdivacky      // For GCC compatibility, we allow attributes that apply only to
1273203955Srdivacky      // function types to be placed on a function's return type
1274203955Srdivacky      // instead (as long as that type doesn't happen to be function
1275203955Srdivacky      // or function-pointer itself).
1276203955Srdivacky      ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk);
1277203955Srdivacky
1278193326Sed      break;
1279193326Sed    }
1280193326Sed    case DeclaratorChunk::MemberPointer:
1281195341Sed      // Verify that we're not building a pointer to pointer to function with
1282195341Sed      // exception specification.
1283195341Sed      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1284195341Sed        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1285195341Sed        D.setInvalidType(true);
1286195341Sed        // Build the type anyway.
1287195341Sed      }
1288193326Sed      // The scope spec must refer to a class, or be dependent.
1289193326Sed      QualType ClsType;
1290207619Srdivacky      if (DeclType.Mem.Scope().isInvalid()) {
1291207619Srdivacky        // Avoid emitting extra errors if we already errored on the scope.
1292207619Srdivacky        D.setInvalidType(true);
1293207619Srdivacky      } else if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1294207619Srdivacky                 || dyn_cast_or_null<CXXRecordDecl>(
1295198954Srdivacky                                   computeDeclContext(DeclType.Mem.Scope()))) {
1296198092Srdivacky        NestedNameSpecifier *NNS
1297194179Sed          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1298198954Srdivacky        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1299198954Srdivacky        switch (NNS->getKind()) {
1300198954Srdivacky        case NestedNameSpecifier::Identifier:
1301206084Srdivacky          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1302206084Srdivacky                                                 NNS->getAsIdentifier());
1303198954Srdivacky          break;
1304198954Srdivacky
1305198954Srdivacky        case NestedNameSpecifier::Namespace:
1306198954Srdivacky        case NestedNameSpecifier::Global:
1307200583Srdivacky          llvm_unreachable("Nested-name-specifier must name a type");
1308198954Srdivacky          break;
1309198954Srdivacky
1310198954Srdivacky        case NestedNameSpecifier::TypeSpec:
1311198954Srdivacky        case NestedNameSpecifier::TypeSpecWithTemplate:
1312198954Srdivacky          ClsType = QualType(NNS->getAsType(), 0);
1313198954Srdivacky          if (NNSPrefix)
1314208600Srdivacky            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
1315198954Srdivacky          break;
1316198954Srdivacky        }
1317193326Sed      } else {
1318194179Sed        Diag(DeclType.Mem.Scope().getBeginLoc(),
1319194179Sed             diag::err_illegal_decl_mempointer_in_nonclass)
1320194179Sed          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1321194179Sed          << DeclType.Mem.Scope().getRange();
1322193326Sed        D.setInvalidType(true);
1323193326Sed      }
1324193326Sed
1325194179Sed      if (!ClsType.isNull())
1326194179Sed        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1327194179Sed                                   DeclType.Loc, D.getIdentifier());
1328194179Sed      if (T.isNull()) {
1329194179Sed        T = Context.IntTy;
1330193326Sed        D.setInvalidType(true);
1331193326Sed      }
1332193326Sed      break;
1333193326Sed    }
1334193326Sed
1335193326Sed    if (T.isNull()) {
1336193326Sed      D.setInvalidType(true);
1337193326Sed      T = Context.IntTy;
1338193326Sed    }
1339193326Sed
1340203955Srdivacky    DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1341203955Srdivacky
1342193326Sed    // See if there are any attributes on this declarator chunk.
1343193326Sed    if (const AttributeList *AL = DeclType.getAttrs())
1344204643Srdivacky      ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk);
1345193326Sed  }
1346193326Sed
1347193326Sed  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1348198092Srdivacky    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1349198893Srdivacky    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1350193326Sed
1351193326Sed    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1352193326Sed    // for a nonstatic member function, the function type to which a pointer
1353193326Sed    // to member refers, or the top-level function type of a function typedef
1354193326Sed    // declaration.
1355193326Sed    if (FnTy->getTypeQuals() != 0 &&
1356193326Sed        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1357193326Sed        ((D.getContext() != Declarator::MemberContext &&
1358193326Sed          (!D.getCXXScopeSpec().isSet() ||
1359198092Srdivacky           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1360198092Srdivacky              ->isRecord())) ||
1361193326Sed         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1362193326Sed      if (D.isFunctionDeclarator())
1363193326Sed        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1364193326Sed      else
1365193326Sed        Diag(D.getIdentifierLoc(),
1366193326Sed             diag::err_invalid_qualified_typedef_function_type_use);
1367193326Sed
1368193326Sed      // Strip the cv-quals from the type.
1369193326Sed      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1370204643Srdivacky                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0,
1371206084Srdivacky                                  false, false, 0, 0, FunctionType::ExtInfo());
1372193326Sed    }
1373193326Sed  }
1374198092Srdivacky
1375203955Srdivacky  // Process any function attributes we might have delayed from the
1376203955Srdivacky  // declaration-specifiers.
1377203955Srdivacky  ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec);
1378198092Srdivacky
1379203955Srdivacky  // If there were any type attributes applied to the decl itself, not
1380203955Srdivacky  // the type, apply them to the result type.  But don't do this for
1381203955Srdivacky  // block-literal expressions, which are parsed wierdly.
1382203955Srdivacky  if (D.getContext() != Declarator::BlockLiteralContext)
1383203955Srdivacky    if (const AttributeList *Attrs = D.getAttributes())
1384204643Srdivacky      ProcessTypeAttributeList(*this, T, false, Attrs,
1385204643Srdivacky                               FnAttrsFromPreviousChunk);
1386203955Srdivacky
1387203955Srdivacky  DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1388203955Srdivacky
1389200583Srdivacky  if (TInfo) {
1390198398Srdivacky    if (D.isInvalidType())
1391200583Srdivacky      *TInfo = 0;
1392198398Srdivacky    else
1393207619Srdivacky      *TInfo = GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
1394198398Srdivacky  }
1395198092Srdivacky
1396193326Sed  return T;
1397193326Sed}
1398193326Sed
1399198398Srdivackynamespace {
1400198398Srdivacky  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1401198398Srdivacky    const DeclSpec &DS;
1402193326Sed
1403198398Srdivacky  public:
1404198398Srdivacky    TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1405193326Sed
1406198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1407198398Srdivacky      Visit(TL.getUnqualifiedLoc());
1408198398Srdivacky    }
1409198398Srdivacky    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1410198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1411198398Srdivacky    }
1412198398Srdivacky    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1413198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1414208600Srdivacky    }
1415208600Srdivacky    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1416208600Srdivacky      // Handle the base type, which might not have been written explicitly.
1417208600Srdivacky      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1418208600Srdivacky        TL.setHasBaseTypeAsWritten(false);
1419208600Srdivacky        TL.getBaseLoc().initialize(SourceLocation());
1420208600Srdivacky      } else {
1421208600Srdivacky        TL.setHasBaseTypeAsWritten(true);
1422208600Srdivacky        Visit(TL.getBaseLoc());
1423208600Srdivacky      }
1424193326Sed
1425208600Srdivacky      // Protocol qualifiers.
1426198398Srdivacky      if (DS.getProtocolQualifiers()) {
1427198398Srdivacky        assert(TL.getNumProtocols() > 0);
1428198398Srdivacky        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1429198398Srdivacky        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1430198398Srdivacky        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1431198398Srdivacky        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1432198398Srdivacky          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1433198398Srdivacky      } else {
1434198398Srdivacky        assert(TL.getNumProtocols() == 0);
1435198398Srdivacky        TL.setLAngleLoc(SourceLocation());
1436198398Srdivacky        TL.setRAngleLoc(SourceLocation());
1437198398Srdivacky      }
1438198398Srdivacky    }
1439198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1440198398Srdivacky      TL.setStarLoc(SourceLocation());
1441208600Srdivacky      Visit(TL.getPointeeLoc());
1442198092Srdivacky    }
1443198893Srdivacky    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1444200583Srdivacky      TypeSourceInfo *TInfo = 0;
1445200583Srdivacky      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1446198893Srdivacky
1447198893Srdivacky      // If we got no declarator info from previous Sema routines,
1448198893Srdivacky      // just fill with the typespec loc.
1449200583Srdivacky      if (!TInfo) {
1450198893Srdivacky        TL.initialize(DS.getTypeSpecTypeLoc());
1451198893Srdivacky        return;
1452198893Srdivacky      }
1453198893Srdivacky
1454208600Srdivacky      TypeLoc OldTL = TInfo->getTypeLoc();
1455208600Srdivacky      if (TInfo->getType()->getAs<ElaboratedType>()) {
1456208600Srdivacky        ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
1457208600Srdivacky        TemplateSpecializationTypeLoc NamedTL =
1458208600Srdivacky          cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
1459208600Srdivacky        TL.copy(NamedTL);
1460208600Srdivacky      }
1461208600Srdivacky      else
1462208600Srdivacky        TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
1463198893Srdivacky    }
1464202379Srdivacky    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1465202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
1466202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1467202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
1468202379Srdivacky    }
1469202379Srdivacky    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1470202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
1471202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1472202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
1473202379Srdivacky      assert(DS.getTypeRep());
1474202379Srdivacky      TypeSourceInfo *TInfo = 0;
1475202379Srdivacky      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1476202379Srdivacky      TL.setUnderlyingTInfo(TInfo);
1477202379Srdivacky    }
1478202879Srdivacky    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1479202879Srdivacky      // By default, use the source location of the type specifier.
1480202879Srdivacky      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
1481202879Srdivacky      if (TL.needsExtraLocalData()) {
1482202879Srdivacky        // Set info for the written builtin specifiers.
1483202879Srdivacky        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
1484202879Srdivacky        // Try to have a meaningful source location.
1485202879Srdivacky        if (TL.getWrittenSignSpec() != TSS_unspecified)
1486202879Srdivacky          // Sign spec loc overrides the others (e.g., 'unsigned long').
1487202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
1488202879Srdivacky        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
1489202879Srdivacky          // Width spec loc overrides type spec loc (e.g., 'short int').
1490202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
1491202879Srdivacky      }
1492202879Srdivacky    }
1493208600Srdivacky    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1494208600Srdivacky      ElaboratedTypeKeyword Keyword
1495208600Srdivacky        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1496208600Srdivacky      if (Keyword == ETK_Typename) {
1497208600Srdivacky        TypeSourceInfo *TInfo = 0;
1498208600Srdivacky        Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1499208600Srdivacky        if (TInfo) {
1500208600Srdivacky          TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
1501208600Srdivacky          return;
1502208600Srdivacky        }
1503208600Srdivacky      }
1504208600Srdivacky      TL.setKeywordLoc(Keyword != ETK_None
1505208600Srdivacky                       ? DS.getTypeSpecTypeLoc()
1506208600Srdivacky                       : SourceLocation());
1507208600Srdivacky      const CXXScopeSpec& SS = DS.getTypeSpecScope();
1508208600Srdivacky      TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange());
1509208600Srdivacky      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
1510208600Srdivacky    }
1511208600Srdivacky    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1512208600Srdivacky      ElaboratedTypeKeyword Keyword
1513208600Srdivacky        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1514208600Srdivacky      if (Keyword == ETK_Typename) {
1515208600Srdivacky        TypeSourceInfo *TInfo = 0;
1516208600Srdivacky        Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1517208600Srdivacky        if (TInfo) {
1518208600Srdivacky          TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
1519208600Srdivacky          return;
1520208600Srdivacky        }
1521208600Srdivacky      }
1522208600Srdivacky      TL.setKeywordLoc(Keyword != ETK_None
1523208600Srdivacky                       ? DS.getTypeSpecTypeLoc()
1524208600Srdivacky                       : SourceLocation());
1525208600Srdivacky      const CXXScopeSpec& SS = DS.getTypeSpecScope();
1526208600Srdivacky      TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange());
1527208600Srdivacky      // FIXME: load appropriate source location.
1528208600Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1529208600Srdivacky    }
1530208600Srdivacky
1531198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
1532198398Srdivacky      // FIXME: add other typespec types and change this to an assert.
1533198398Srdivacky      TL.initialize(DS.getTypeSpecTypeLoc());
1534198092Srdivacky    }
1535198398Srdivacky  };
1536198398Srdivacky
1537198398Srdivacky  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1538198398Srdivacky    const DeclaratorChunk &Chunk;
1539198398Srdivacky
1540198398Srdivacky  public:
1541198398Srdivacky    DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1542198398Srdivacky
1543198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1544200583Srdivacky      llvm_unreachable("qualified type locs not expected here!");
1545198092Srdivacky    }
1546198398Srdivacky
1547198398Srdivacky    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1548198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1549198398Srdivacky      TL.setCaretLoc(Chunk.Loc);
1550198092Srdivacky    }
1551198398Srdivacky    void VisitPointerTypeLoc(PointerTypeLoc TL) {
1552198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1553198398Srdivacky      TL.setStarLoc(Chunk.Loc);
1554198398Srdivacky    }
1555198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1556198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1557198398Srdivacky      TL.setStarLoc(Chunk.Loc);
1558198398Srdivacky    }
1559198398Srdivacky    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1560198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1561198398Srdivacky      TL.setStarLoc(Chunk.Loc);
1562198398Srdivacky      // FIXME: nested name specifier
1563198398Srdivacky    }
1564198398Srdivacky    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1565198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
1566198398Srdivacky      // 'Amp' is misleading: this might have been originally
1567198398Srdivacky      /// spelled with AmpAmp.
1568198398Srdivacky      TL.setAmpLoc(Chunk.Loc);
1569198398Srdivacky    }
1570198398Srdivacky    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1571198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
1572198398Srdivacky      assert(!Chunk.Ref.LValueRef);
1573198398Srdivacky      TL.setAmpAmpLoc(Chunk.Loc);
1574198398Srdivacky    }
1575198398Srdivacky    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1576198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Array);
1577198398Srdivacky      TL.setLBracketLoc(Chunk.Loc);
1578198398Srdivacky      TL.setRBracketLoc(Chunk.EndLoc);
1579198398Srdivacky      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1580198398Srdivacky    }
1581198398Srdivacky    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1582198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Function);
1583198398Srdivacky      TL.setLParenLoc(Chunk.Loc);
1584198398Srdivacky      TL.setRParenLoc(Chunk.EndLoc);
1585198398Srdivacky
1586198398Srdivacky      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1587198398Srdivacky      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1588198092Srdivacky        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1589198398Srdivacky        TL.setArg(tpi++, Param);
1590198092Srdivacky      }
1591198398Srdivacky      // FIXME: exception specs
1592198092Srdivacky    }
1593193326Sed
1594198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
1595200583Srdivacky      llvm_unreachable("unsupported TypeLoc kind in declarator!");
1596198092Srdivacky    }
1597198398Srdivacky  };
1598198398Srdivacky}
1599198092Srdivacky
1600200583Srdivacky/// \brief Create and instantiate a TypeSourceInfo with type source information.
1601198398Srdivacky///
1602198398Srdivacky/// \param T QualType referring to the type as written in source code.
1603207619Srdivacky///
1604207619Srdivacky/// \param ReturnTypeInfo For declarators whose return type does not show
1605207619Srdivacky/// up in the normal place in the declaration specifiers (such as a C++
1606207619Srdivacky/// conversion function), this pointer will refer to a type source information
1607207619Srdivacky/// for that return type.
1608200583SrdivackyTypeSourceInfo *
1609207619SrdivackySema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1610207619Srdivacky                                     TypeSourceInfo *ReturnTypeInfo) {
1611200583Srdivacky  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
1612200583Srdivacky  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
1613198398Srdivacky
1614198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1615198398Srdivacky    DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1616198398Srdivacky    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1617195341Sed  }
1618198092Srdivacky
1619198398Srdivacky  TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1620207619Srdivacky
1621207619Srdivacky  // We have source information for the return type that was not in the
1622207619Srdivacky  // declaration specifiers; copy that information into the current type
1623207619Srdivacky  // location so that it will be retained. This occurs, for example, with
1624207619Srdivacky  // a C++ conversion function, where the return type occurs within the
1625207619Srdivacky  // declarator-id rather than in the declaration specifiers.
1626207619Srdivacky  if (ReturnTypeInfo && D.getDeclSpec().getTypeSpecType() == TST_unspecified) {
1627207619Srdivacky    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
1628207619Srdivacky    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
1629207619Srdivacky    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
1630207619Srdivacky  }
1631207619Srdivacky
1632200583Srdivacky  return TInfo;
1633198092Srdivacky}
1634195341Sed
1635200583Srdivacky/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
1636200583SrdivackyQualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) {
1637198092Srdivacky  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1638198092Srdivacky  // and Sema during declaration parsing. Try deallocating/caching them when
1639198092Srdivacky  // it's appropriate, instead of allocating them and keeping them around.
1640198092Srdivacky  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1641200583Srdivacky  new (LocT) LocInfoType(T, TInfo);
1642198092Srdivacky  assert(LocT->getTypeClass() != T->getTypeClass() &&
1643198092Srdivacky         "LocInfoType's TypeClass conflicts with an existing Type class");
1644198092Srdivacky  return QualType(LocT, 0);
1645198092Srdivacky}
1646195341Sed
1647198092Srdivackyvoid LocInfoType::getAsStringInternal(std::string &Str,
1648198092Srdivacky                                      const PrintingPolicy &Policy) const {
1649198092Srdivacky  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1650198092Srdivacky         " was used directly instead of getting the QualType through"
1651198092Srdivacky         " GetTypeFromParser");
1652195341Sed}
1653195341Sed
1654193326Sed/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1655193326Sed/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1656193326Sed/// they point to and return true. If T1 and T2 aren't pointer types
1657193326Sed/// or pointer-to-member types, or if they are not similar at this
1658193326Sed/// level, returns false and leaves T1 and T2 unchanged. Top-level
1659193326Sed/// qualifiers on T1 and T2 are ignored. This function will typically
1660193326Sed/// be called in a loop that successively "unwraps" pointer and
1661193326Sed/// pointer-to-member types to compare them at each level.
1662193326Sedbool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1663198092Srdivacky  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1664198092Srdivacky                    *T2PtrType = T2->getAs<PointerType>();
1665193326Sed  if (T1PtrType && T2PtrType) {
1666193326Sed    T1 = T1PtrType->getPointeeType();
1667193326Sed    T2 = T2PtrType->getPointeeType();
1668193326Sed    return true;
1669193326Sed  }
1670193326Sed
1671198092Srdivacky  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1672198092Srdivacky                          *T2MPType = T2->getAs<MemberPointerType>();
1673193326Sed  if (T1MPType && T2MPType &&
1674193326Sed      Context.getCanonicalType(T1MPType->getClass()) ==
1675193326Sed      Context.getCanonicalType(T2MPType->getClass())) {
1676193326Sed    T1 = T1MPType->getPointeeType();
1677193326Sed    T2 = T2MPType->getPointeeType();
1678193326Sed    return true;
1679193326Sed  }
1680208600Srdivacky
1681208600Srdivacky  if (getLangOptions().ObjC1) {
1682208600Srdivacky    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
1683208600Srdivacky                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
1684208600Srdivacky    if (T1OPType && T2OPType) {
1685208600Srdivacky      T1 = T1OPType->getPointeeType();
1686208600Srdivacky      T2 = T2OPType->getPointeeType();
1687208600Srdivacky      return true;
1688208600Srdivacky    }
1689208600Srdivacky  }
1690193326Sed  return false;
1691193326Sed}
1692193326Sed
1693193326SedSema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1694193326Sed  // C99 6.7.6: Type names have no identifier.  This is already validated by
1695193326Sed  // the parser.
1696193326Sed  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1697198092Srdivacky
1698200583Srdivacky  TypeSourceInfo *TInfo = 0;
1699193326Sed  TagDecl *OwnedTag = 0;
1700200583Srdivacky  QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
1701193326Sed  if (D.isInvalidType())
1702193326Sed    return true;
1703193326Sed
1704193326Sed  if (getLangOptions().CPlusPlus) {
1705193326Sed    // Check that there are no default arguments (C++ only).
1706193326Sed    CheckExtraCXXDefaultArguments(D);
1707193326Sed
1708193326Sed    // C++0x [dcl.type]p3:
1709193326Sed    //   A type-specifier-seq shall not define a class or enumeration
1710193326Sed    //   unless it appears in the type-id of an alias-declaration
1711193326Sed    //   (7.1.3).
1712193326Sed    if (OwnedTag && OwnedTag->isDefinition())
1713193326Sed      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1714193326Sed        << Context.getTypeDeclType(OwnedTag);
1715193326Sed  }
1716193326Sed
1717200583Srdivacky  if (TInfo)
1718200583Srdivacky    T = CreateLocInfoType(T, TInfo);
1719198092Srdivacky
1720193326Sed  return T.getAsOpaquePtr();
1721193326Sed}
1722193326Sed
1723193326Sed
1724193326Sed
1725193326Sed//===----------------------------------------------------------------------===//
1726193326Sed// Type Attribute Processing
1727193326Sed//===----------------------------------------------------------------------===//
1728193326Sed
1729193326Sed/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1730193326Sed/// specified type.  The attribute contains 1 argument, the id of the address
1731193326Sed/// space for the type.
1732198092Srdivackystatic void HandleAddressSpaceTypeAttribute(QualType &Type,
1733193326Sed                                            const AttributeList &Attr, Sema &S){
1734198092Srdivacky
1735193326Sed  // If this type is already address space qualified, reject it.
1736193326Sed  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1737193326Sed  // for two or more different address spaces."
1738193326Sed  if (Type.getAddressSpace()) {
1739193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1740207619Srdivacky    Attr.setInvalid();
1741193326Sed    return;
1742193326Sed  }
1743198092Srdivacky
1744193326Sed  // Check the attribute arguments.
1745193326Sed  if (Attr.getNumArgs() != 1) {
1746193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1747207619Srdivacky    Attr.setInvalid();
1748193326Sed    return;
1749193326Sed  }
1750193326Sed  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1751193326Sed  llvm::APSInt addrSpace(32);
1752208600Srdivacky  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
1753208600Srdivacky      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1754193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1755193326Sed      << ASArgExpr->getSourceRange();
1756207619Srdivacky    Attr.setInvalid();
1757193326Sed    return;
1758193326Sed  }
1759193326Sed
1760198092Srdivacky  // Bounds checking.
1761198092Srdivacky  if (addrSpace.isSigned()) {
1762198092Srdivacky    if (addrSpace.isNegative()) {
1763198092Srdivacky      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1764198092Srdivacky        << ASArgExpr->getSourceRange();
1765207619Srdivacky      Attr.setInvalid();
1766198092Srdivacky      return;
1767198092Srdivacky    }
1768198092Srdivacky    addrSpace.setIsSigned(false);
1769198092Srdivacky  }
1770198092Srdivacky  llvm::APSInt max(addrSpace.getBitWidth());
1771198092Srdivacky  max = Qualifiers::MaxAddressSpace;
1772198092Srdivacky  if (addrSpace > max) {
1773198092Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1774198092Srdivacky      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1775207619Srdivacky    Attr.setInvalid();
1776198092Srdivacky    return;
1777198092Srdivacky  }
1778198092Srdivacky
1779198092Srdivacky  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1780193326Sed  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1781193326Sed}
1782193326Sed
1783193326Sed/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1784193326Sed/// specified type.  The attribute contains 1 argument, weak or strong.
1785198092Srdivackystatic void HandleObjCGCTypeAttribute(QualType &Type,
1786193326Sed                                      const AttributeList &Attr, Sema &S) {
1787198092Srdivacky  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1788193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1789207619Srdivacky    Attr.setInvalid();
1790193326Sed    return;
1791193326Sed  }
1792198092Srdivacky
1793193326Sed  // Check the attribute arguments.
1794198092Srdivacky  if (!Attr.getParameterName()) {
1795193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1796193326Sed      << "objc_gc" << 1;
1797207619Srdivacky    Attr.setInvalid();
1798193326Sed    return;
1799193326Sed  }
1800198092Srdivacky  Qualifiers::GC GCAttr;
1801193326Sed  if (Attr.getNumArgs() != 0) {
1802193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1803207619Srdivacky    Attr.setInvalid();
1804193326Sed    return;
1805193326Sed  }
1806198092Srdivacky  if (Attr.getParameterName()->isStr("weak"))
1807198092Srdivacky    GCAttr = Qualifiers::Weak;
1808193326Sed  else if (Attr.getParameterName()->isStr("strong"))
1809198092Srdivacky    GCAttr = Qualifiers::Strong;
1810193326Sed  else {
1811193326Sed    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1812193326Sed      << "objc_gc" << Attr.getParameterName();
1813207619Srdivacky    Attr.setInvalid();
1814193326Sed    return;
1815193326Sed  }
1816198092Srdivacky
1817193326Sed  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1818193326Sed}
1819193326Sed
1820203955Srdivacky/// Process an individual function attribute.  Returns true if the
1821203955Srdivacky/// attribute does not make sense to apply to this type.
1822203955Srdivackybool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) {
1823203955Srdivacky  if (Attr.getKind() == AttributeList::AT_noreturn) {
1824203955Srdivacky    // Complain immediately if the arg count is wrong.
1825203955Srdivacky    if (Attr.getNumArgs() != 0) {
1826203955Srdivacky      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1827207619Srdivacky      Attr.setInvalid();
1828203955Srdivacky      return false;
1829203955Srdivacky    }
1830198092Srdivacky
1831203955Srdivacky    // Delay if this is not a function or pointer to block.
1832203955Srdivacky    if (!Type->isFunctionPointerType()
1833203955Srdivacky        && !Type->isBlockPointerType()
1834203955Srdivacky        && !Type->isFunctionType())
1835203955Srdivacky      return true;
1836198092Srdivacky
1837203955Srdivacky    // Otherwise we can process right away.
1838203955Srdivacky    Type = S.Context.getNoReturnType(Type);
1839203955Srdivacky    return false;
1840203955Srdivacky  }
1841203955Srdivacky
1842206084Srdivacky  if (Attr.getKind() == AttributeList::AT_regparm) {
1843206084Srdivacky    // The warning is emitted elsewhere
1844206084Srdivacky    if (Attr.getNumArgs() != 1) {
1845206084Srdivacky      return false;
1846206084Srdivacky    }
1847206084Srdivacky
1848206084Srdivacky    // Delay if this is not a function or pointer to block.
1849206084Srdivacky    if (!Type->isFunctionPointerType()
1850206084Srdivacky        && !Type->isBlockPointerType()
1851206084Srdivacky        && !Type->isFunctionType())
1852206084Srdivacky      return true;
1853206084Srdivacky
1854206084Srdivacky    // Otherwise we can process right away.
1855206084Srdivacky    Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1856206084Srdivacky    llvm::APSInt NumParams(32);
1857206084Srdivacky
1858206084Srdivacky    // The warning is emitted elsewhere
1859208600Srdivacky    if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
1860208600Srdivacky        !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context))
1861206084Srdivacky      return false;
1862206084Srdivacky
1863206084Srdivacky    Type = S.Context.getRegParmType(Type, NumParams.getZExtValue());
1864206084Srdivacky    return false;
1865206084Srdivacky  }
1866206084Srdivacky
1867203955Srdivacky  // Otherwise, a calling convention.
1868203955Srdivacky  if (Attr.getNumArgs() != 0) {
1869203955Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1870207619Srdivacky    Attr.setInvalid();
1871203955Srdivacky    return false;
1872203955Srdivacky  }
1873203955Srdivacky
1874203955Srdivacky  QualType T = Type;
1875203955Srdivacky  if (const PointerType *PT = Type->getAs<PointerType>())
1876203955Srdivacky    T = PT->getPointeeType();
1877203955Srdivacky  const FunctionType *Fn = T->getAs<FunctionType>();
1878203955Srdivacky
1879203955Srdivacky  // Delay if the type didn't work out to a function.
1880203955Srdivacky  if (!Fn) return true;
1881203955Srdivacky
1882203955Srdivacky  // TODO: diagnose uses of these conventions on the wrong target.
1883203955Srdivacky  CallingConv CC;
1884203955Srdivacky  switch (Attr.getKind()) {
1885203955Srdivacky  case AttributeList::AT_cdecl: CC = CC_C; break;
1886203955Srdivacky  case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
1887203955Srdivacky  case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
1888208600Srdivacky  case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break;
1889203955Srdivacky  default: llvm_unreachable("unexpected attribute kind"); return false;
1890203955Srdivacky  }
1891203955Srdivacky
1892203955Srdivacky  CallingConv CCOld = Fn->getCallConv();
1893204643Srdivacky  if (S.Context.getCanonicalCallConv(CC) ==
1894207619Srdivacky      S.Context.getCanonicalCallConv(CCOld)) {
1895207619Srdivacky    Attr.setInvalid();
1896207619Srdivacky    return false;
1897207619Srdivacky  }
1898203955Srdivacky
1899203955Srdivacky  if (CCOld != CC_Default) {
1900203955Srdivacky    // Should we diagnose reapplications of the same convention?
1901203955Srdivacky    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1902203955Srdivacky      << FunctionType::getNameForCallConv(CC)
1903203955Srdivacky      << FunctionType::getNameForCallConv(CCOld);
1904207619Srdivacky    Attr.setInvalid();
1905203955Srdivacky    return false;
1906203955Srdivacky  }
1907203955Srdivacky
1908203955Srdivacky  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
1909203955Srdivacky  if (CC == CC_X86FastCall) {
1910203955Srdivacky    if (isa<FunctionNoProtoType>(Fn)) {
1911203955Srdivacky      S.Diag(Attr.getLoc(), diag::err_cconv_knr)
1912203955Srdivacky        << FunctionType::getNameForCallConv(CC);
1913207619Srdivacky      Attr.setInvalid();
1914203955Srdivacky      return false;
1915203955Srdivacky    }
1916203955Srdivacky
1917203955Srdivacky    const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn);
1918203955Srdivacky    if (FnP->isVariadic()) {
1919203955Srdivacky      S.Diag(Attr.getLoc(), diag::err_cconv_varargs)
1920203955Srdivacky        << FunctionType::getNameForCallConv(CC);
1921207619Srdivacky      Attr.setInvalid();
1922203955Srdivacky      return false;
1923203955Srdivacky    }
1924203955Srdivacky  }
1925203955Srdivacky
1926203955Srdivacky  Type = S.Context.getCallConvType(Type, CC);
1927203955Srdivacky  return false;
1928198092Srdivacky}
1929198092Srdivacky
1930200583Srdivacky/// HandleVectorSizeAttribute - this attribute is only applicable to integral
1931200583Srdivacky/// and float scalars, although arrays, pointers, and function return values are
1932200583Srdivacky/// allowed in conjunction with this construct. Aggregates with this attribute
1933200583Srdivacky/// are invalid, even if they are of the same size as a corresponding scalar.
1934200583Srdivacky/// The raw attribute should contain precisely 1 argument, the vector size for
1935200583Srdivacky/// the variable, measured in bytes. If curType and rawAttr are well formed,
1936200583Srdivacky/// this routine will return a new vector type.
1937200583Srdivackystatic void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1938200583Srdivacky  // Check the attribute arugments.
1939200583Srdivacky  if (Attr.getNumArgs() != 1) {
1940200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1941207619Srdivacky    Attr.setInvalid();
1942200583Srdivacky    return;
1943200583Srdivacky  }
1944200583Srdivacky  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1945200583Srdivacky  llvm::APSInt vecSize(32);
1946208600Srdivacky  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
1947208600Srdivacky      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1948200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1949200583Srdivacky      << "vector_size" << sizeExpr->getSourceRange();
1950207619Srdivacky    Attr.setInvalid();
1951200583Srdivacky    return;
1952200583Srdivacky  }
1953200583Srdivacky  // the base type must be integer or float, and can't already be a vector.
1954200583Srdivacky  if (CurType->isVectorType() ||
1955200583Srdivacky      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1956200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1957207619Srdivacky    Attr.setInvalid();
1958200583Srdivacky    return;
1959200583Srdivacky  }
1960200583Srdivacky  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1961200583Srdivacky  // vecSize is specified in bytes - convert to bits.
1962200583Srdivacky  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1963200583Srdivacky
1964200583Srdivacky  // the vector size needs to be an integral multiple of the type size.
1965200583Srdivacky  if (vectorSize % typeSize) {
1966200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1967200583Srdivacky      << sizeExpr->getSourceRange();
1968207619Srdivacky    Attr.setInvalid();
1969200583Srdivacky    return;
1970200583Srdivacky  }
1971200583Srdivacky  if (vectorSize == 0) {
1972200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1973200583Srdivacky      << sizeExpr->getSourceRange();
1974207619Srdivacky    Attr.setInvalid();
1975200583Srdivacky    return;
1976200583Srdivacky  }
1977200583Srdivacky
1978200583Srdivacky  // Success! Instantiate the vector type, the number of elements is > 0, and
1979200583Srdivacky  // not required to be a power of 2, unlike GCC.
1980203955Srdivacky  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false);
1981200583Srdivacky}
1982200583Srdivacky
1983203955Srdivackyvoid ProcessTypeAttributeList(Sema &S, QualType &Result,
1984204643Srdivacky                              bool IsDeclSpec, const AttributeList *AL,
1985203955Srdivacky                              DelayedAttributeSet &FnAttrs) {
1986193326Sed  // Scan through and apply attributes to this type where it makes sense.  Some
1987193326Sed  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1988193326Sed  // type, but others can be present in the type specifiers even though they
1989193326Sed  // apply to the decl.  Here we apply type attributes and ignore the rest.
1990193326Sed  for (; AL; AL = AL->getNext()) {
1991207619Srdivacky    // Skip attributes that were marked to be invalid.
1992207619Srdivacky    if (AL->isInvalid())
1993207619Srdivacky      continue;
1994207619Srdivacky
1995207619Srdivacky    // If this is an attribute we can handle, do so now,
1996207619Srdivacky    // otherwise, add it to the FnAttrs list for rechaining.
1997193326Sed    switch (AL->getKind()) {
1998193326Sed    default: break;
1999203955Srdivacky
2000193326Sed    case AttributeList::AT_address_space:
2001203955Srdivacky      HandleAddressSpaceTypeAttribute(Result, *AL, S);
2002193326Sed      break;
2003193326Sed    case AttributeList::AT_objc_gc:
2004203955Srdivacky      HandleObjCGCTypeAttribute(Result, *AL, S);
2005193326Sed      break;
2006203955Srdivacky    case AttributeList::AT_vector_size:
2007203955Srdivacky      HandleVectorSizeAttr(Result, *AL, S);
2008203955Srdivacky      break;
2009203955Srdivacky
2010198092Srdivacky    case AttributeList::AT_noreturn:
2011203955Srdivacky    case AttributeList::AT_cdecl:
2012203955Srdivacky    case AttributeList::AT_fastcall:
2013203955Srdivacky    case AttributeList::AT_stdcall:
2014208600Srdivacky    case AttributeList::AT_thiscall:
2015206084Srdivacky    case AttributeList::AT_regparm:
2016204643Srdivacky      // Don't process these on the DeclSpec.
2017204643Srdivacky      if (IsDeclSpec ||
2018204643Srdivacky          ProcessFnAttr(S, Result, *AL))
2019203955Srdivacky        FnAttrs.push_back(DelayedAttribute(AL, Result));
2020198092Srdivacky      break;
2021193326Sed    }
2022193326Sed  }
2023193326Sed}
2024193326Sed
2025198092Srdivacky/// @brief Ensure that the type T is a complete type.
2026193326Sed///
2027193326Sed/// This routine checks whether the type @p T is complete in any
2028193326Sed/// context where a complete type is required. If @p T is a complete
2029193326Sed/// type, returns false. If @p T is a class template specialization,
2030193326Sed/// this routine then attempts to perform class template
2031193326Sed/// instantiation. If instantiation fails, or if @p T is incomplete
2032193326Sed/// and cannot be completed, issues the diagnostic @p diag (giving it
2033193326Sed/// the type @p T) and returns true.
2034193326Sed///
2035193326Sed/// @param Loc  The location in the source that the incomplete type
2036193326Sed/// diagnostic should refer to.
2037193326Sed///
2038193326Sed/// @param T  The type that this routine is examining for completeness.
2039193326Sed///
2040198092Srdivacky/// @param PD The partial diagnostic that will be printed out if T is not a
2041198092Srdivacky/// complete type.
2042193326Sed///
2043193326Sed/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
2044193326Sed/// @c false otherwise.
2045198092Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2046198092Srdivacky                               const PartialDiagnostic &PD,
2047198092Srdivacky                               std::pair<SourceLocation,
2048198092Srdivacky                                         PartialDiagnostic> Note) {
2049198092Srdivacky  unsigned diag = PD.getDiagID();
2050198092Srdivacky
2051198398Srdivacky  // FIXME: Add this assertion to make sure we always get instantiation points.
2052198398Srdivacky  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
2053193326Sed  // FIXME: Add this assertion to help us flush out problems with
2054193326Sed  // checking for dependent types and type-dependent expressions.
2055193326Sed  //
2056198092Srdivacky  //  assert(!T->isDependentType() &&
2057193326Sed  //         "Can't ask whether a dependent type is complete");
2058193326Sed
2059193326Sed  // If we have a complete type, we're done.
2060193326Sed  if (!T->isIncompleteType())
2061193326Sed    return false;
2062193326Sed
2063193326Sed  // If we have a class template specialization or a class member of a
2064198954Srdivacky  // class template specialization, or an array with known size of such,
2065198954Srdivacky  // try to instantiate it.
2066198954Srdivacky  QualType MaybeTemplate = T;
2067199482Srdivacky  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
2068198954Srdivacky    MaybeTemplate = Array->getElementType();
2069198954Srdivacky  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
2070193326Sed    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
2071193326Sed          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
2072198893Srdivacky      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
2073198893Srdivacky        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
2074198092Srdivacky                                                      TSK_ImplicitInstantiation,
2075198092Srdivacky                                                      /*Complain=*/diag != 0);
2076198092Srdivacky    } else if (CXXRecordDecl *Rec
2077193326Sed                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
2078193326Sed      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
2079198092Srdivacky        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
2080198092Srdivacky        assert(MSInfo && "Missing member specialization information?");
2081198092Srdivacky        // This record was instantiated from a class within a template.
2082198092Srdivacky        if (MSInfo->getTemplateSpecializationKind()
2083198893Srdivacky                                               != TSK_ExplicitSpecialization)
2084198092Srdivacky          return InstantiateClass(Loc, Rec, Pattern,
2085198092Srdivacky                                  getTemplateInstantiationArgs(Rec),
2086198092Srdivacky                                  TSK_ImplicitInstantiation,
2087198092Srdivacky                                  /*Complain=*/diag != 0);
2088193326Sed      }
2089193326Sed    }
2090193326Sed  }
2091193326Sed
2092198092Srdivacky  if (diag == 0)
2093198092Srdivacky    return true;
2094193326Sed
2095206084Srdivacky  const TagType *Tag = 0;
2096206084Srdivacky  if (const RecordType *Record = T->getAs<RecordType>())
2097206084Srdivacky    Tag = Record;
2098206084Srdivacky  else if (const EnumType *Enum = T->getAs<EnumType>())
2099206084Srdivacky    Tag = Enum;
2100206084Srdivacky
2101206084Srdivacky  // Avoid diagnosing invalid decls as incomplete.
2102206084Srdivacky  if (Tag && Tag->getDecl()->isInvalidDecl())
2103206084Srdivacky    return true;
2104206084Srdivacky
2105193326Sed  // We have an incomplete type. Produce a diagnostic.
2106198092Srdivacky  Diag(Loc, PD) << T;
2107193326Sed
2108198092Srdivacky  // If we have a note, produce it.
2109198092Srdivacky  if (!Note.first.isInvalid())
2110198092Srdivacky    Diag(Note.first, Note.second);
2111198092Srdivacky
2112193326Sed  // If the type was a forward declaration of a class/struct/union
2113206084Srdivacky  // type, produce a note.
2114193326Sed  if (Tag && !Tag->getDecl()->isInvalidDecl())
2115198092Srdivacky    Diag(Tag->getDecl()->getLocation(),
2116193326Sed         Tag->isBeingDefined() ? diag::note_type_being_defined
2117193326Sed                               : diag::note_forward_declaration)
2118193326Sed        << QualType(Tag, 0);
2119193326Sed
2120193326Sed  return true;
2121193326Sed}
2122193326Sed
2123206084Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2124206084Srdivacky                               const PartialDiagnostic &PD) {
2125206084Srdivacky  return RequireCompleteType(Loc, T, PD,
2126206084Srdivacky                             std::make_pair(SourceLocation(), PDiag(0)));
2127206084Srdivacky}
2128206084Srdivacky
2129206084Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2130206084Srdivacky                               unsigned DiagID) {
2131206084Srdivacky  return RequireCompleteType(Loc, T, PDiag(DiagID),
2132206084Srdivacky                             std::make_pair(SourceLocation(), PDiag(0)));
2133206084Srdivacky}
2134206084Srdivacky
2135208600Srdivacky/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
2136208600Srdivacky/// and qualified by the nested-name-specifier contained in SS.
2137208600SrdivackyQualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
2138208600Srdivacky                                 const CXXScopeSpec &SS, QualType T) {
2139208600Srdivacky  if (T.isNull())
2140193326Sed    return T;
2141208600Srdivacky  NestedNameSpecifier *NNS;
2142208600Srdivacky  if (SS.isValid())
2143208600Srdivacky    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2144208600Srdivacky  else {
2145208600Srdivacky    if (Keyword == ETK_None)
2146208600Srdivacky      return T;
2147208600Srdivacky    NNS = 0;
2148208600Srdivacky  }
2149208600Srdivacky  return Context.getElaboratedType(Keyword, NNS, T);
2150193326Sed}
2151195341Sed
2152195341SedQualType Sema::BuildTypeofExprType(Expr *E) {
2153201361Srdivacky  if (E->getType() == Context.OverloadTy) {
2154201361Srdivacky    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2155201361Srdivacky    // function template specialization wherever deduction cannot occur.
2156201361Srdivacky    if (FunctionDecl *Specialization
2157201361Srdivacky        = ResolveSingleFunctionTemplateSpecialization(E)) {
2158207619Srdivacky      // The access doesn't really matter in this case.
2159207619Srdivacky      DeclAccessPair Found = DeclAccessPair::make(Specialization,
2160207619Srdivacky                                                  Specialization->getAccess());
2161207619Srdivacky      E = FixOverloadedFunctionReference(E, Found, Specialization);
2162201361Srdivacky      if (!E)
2163201361Srdivacky        return QualType();
2164201361Srdivacky    } else {
2165201361Srdivacky      Diag(E->getLocStart(),
2166201361Srdivacky           diag::err_cannot_determine_declared_type_of_overloaded_function)
2167201361Srdivacky        << false << E->getSourceRange();
2168201361Srdivacky      return QualType();
2169201361Srdivacky    }
2170201361Srdivacky  }
2171201361Srdivacky
2172195341Sed  return Context.getTypeOfExprType(E);
2173195341Sed}
2174195341Sed
2175195341SedQualType Sema::BuildDecltypeType(Expr *E) {
2176195341Sed  if (E->getType() == Context.OverloadTy) {
2177201361Srdivacky    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2178201361Srdivacky    // function template specialization wherever deduction cannot occur.
2179201361Srdivacky    if (FunctionDecl *Specialization
2180201361Srdivacky          = ResolveSingleFunctionTemplateSpecialization(E)) {
2181207619Srdivacky      // The access doesn't really matter in this case.
2182207619Srdivacky      DeclAccessPair Found = DeclAccessPair::make(Specialization,
2183207619Srdivacky                                                  Specialization->getAccess());
2184207619Srdivacky      E = FixOverloadedFunctionReference(E, Found, Specialization);
2185201361Srdivacky      if (!E)
2186201361Srdivacky        return QualType();
2187201361Srdivacky    } else {
2188201361Srdivacky      Diag(E->getLocStart(),
2189201361Srdivacky           diag::err_cannot_determine_declared_type_of_overloaded_function)
2190201361Srdivacky        << true << E->getSourceRange();
2191201361Srdivacky      return QualType();
2192201361Srdivacky    }
2193195341Sed  }
2194201361Srdivacky
2195195341Sed  return Context.getDecltypeType(E);
2196195341Sed}
2197