DeclSpec.cpp revision a5fc472b353b88be3b4981da946fb01f5a5cc0c6
1//===--- SemaDeclSpec.cpp - Declaration Specifier Semantic Analysis -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for declaration specifiers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/ParseDiagnostic.h" // FIXME: remove this back-dependency!
15#include "clang/Sema/DeclSpec.h"
16#include "clang/Sema/ParsedTemplate.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/NestedNameSpecifier.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Support/ErrorHandling.h"
24#include <cstring>
25using namespace clang;
26
27
28static DiagnosticBuilder Diag(Diagnostic &D, SourceLocation Loc,
29                              unsigned DiagID) {
30  return D.Report(Loc, DiagID);
31}
32
33
34void UnqualifiedId::setTemplateId(TemplateIdAnnotation *TemplateId) {
35  assert(TemplateId && "NULL template-id annotation?");
36  Kind = IK_TemplateId;
37  this->TemplateId = TemplateId;
38  StartLocation = TemplateId->TemplateNameLoc;
39  EndLocation = TemplateId->RAngleLoc;
40}
41
42void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) {
43  assert(TemplateId && "NULL template-id annotation?");
44  Kind = IK_ConstructorTemplateId;
45  this->TemplateId = TemplateId;
46  StartLocation = TemplateId->TemplateNameLoc;
47  EndLocation = TemplateId->RAngleLoc;
48}
49
50void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc,
51                          TypeLoc TL, SourceLocation ColonColonLoc) {
52  Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc);
53  if (Range.getBegin().isInvalid())
54    Range.setBegin(TL.getBeginLoc());
55  Range.setEnd(ColonColonLoc);
56
57  assert(Range == Builder.getSourceRange() &&
58         "NestedNameSpecifierLoc range computation incorrect");
59}
60
61void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier,
62                          SourceLocation IdentifierLoc,
63                          SourceLocation ColonColonLoc) {
64  Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc);
65
66  if (Range.getBegin().isInvalid())
67    Range.setBegin(IdentifierLoc);
68  Range.setEnd(ColonColonLoc);
69
70  assert(Range == Builder.getSourceRange() &&
71         "NestedNameSpecifierLoc range computation incorrect");
72}
73
74void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace,
75                          SourceLocation NamespaceLoc,
76                          SourceLocation ColonColonLoc) {
77  Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc);
78
79  if (Range.getBegin().isInvalid())
80    Range.setBegin(NamespaceLoc);
81  Range.setEnd(ColonColonLoc);
82
83  assert(Range == Builder.getSourceRange() &&
84         "NestedNameSpecifierLoc range computation incorrect");
85}
86
87void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
88                          SourceLocation AliasLoc,
89                          SourceLocation ColonColonLoc) {
90  Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc);
91
92  if (Range.getBegin().isInvalid())
93    Range.setBegin(AliasLoc);
94  Range.setEnd(ColonColonLoc);
95
96  assert(Range == Builder.getSourceRange() &&
97         "NestedNameSpecifierLoc range computation incorrect");
98}
99
100void CXXScopeSpec::MakeGlobal(ASTContext &Context,
101                              SourceLocation ColonColonLoc) {
102  Builder.MakeGlobal(Context, ColonColonLoc);
103
104  Range = SourceRange(ColonColonLoc);
105
106  assert(Range == Builder.getSourceRange() &&
107         "NestedNameSpecifierLoc range computation incorrect");
108}
109
110void CXXScopeSpec::MakeTrivial(ASTContext &Context,
111                               NestedNameSpecifier *Qualifier, SourceRange R) {
112  Builder.MakeTrivial(Context, Qualifier, R);
113  Range = R;
114}
115
116void CXXScopeSpec::Adopt(NestedNameSpecifierLoc Other) {
117  if (!Other) {
118    Range = SourceRange();
119    Builder.Clear();
120    return;
121  }
122
123  Range = Other.getSourceRange();
124  Builder.Adopt(Other);
125}
126
127NestedNameSpecifierLoc
128CXXScopeSpec::getWithLocInContext(ASTContext &Context) const {
129  if (!Builder.getRepresentation())
130    return NestedNameSpecifierLoc();
131
132  return Builder.getWithLocInContext(Context);
133}
134
135/// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
136/// "TheDeclarator" is the declarator that this will be added to.
137DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto, bool isVariadic,
138                                             SourceLocation EllipsisLoc,
139                                             ParamInfo *ArgInfo,
140                                             unsigned NumArgs,
141                                             unsigned TypeQuals,
142                                             bool RefQualifierIsLvalueRef,
143                                             SourceLocation RefQualifierLoc,
144                                             ExceptionSpecificationType
145                                                 ESpecType,
146                                             SourceLocation ESpecLoc,
147                                             ParsedType *Exceptions,
148                                             SourceRange *ExceptionRanges,
149                                             unsigned NumExceptions,
150                                             Expr *NoexceptExpr,
151                                             SourceLocation LocalRangeBegin,
152                                             SourceLocation LocalRangeEnd,
153                                             Declarator &TheDeclarator,
154                                             ParsedType TrailingReturnType) {
155  DeclaratorChunk I;
156  I.Kind                        = Function;
157  I.Loc                         = LocalRangeBegin;
158  I.EndLoc                      = LocalRangeEnd;
159  I.Fun.AttrList                = 0;
160  I.Fun.hasPrototype            = hasProto;
161  I.Fun.isVariadic              = isVariadic;
162  I.Fun.EllipsisLoc             = EllipsisLoc.getRawEncoding();
163  I.Fun.DeleteArgInfo           = false;
164  I.Fun.TypeQuals               = TypeQuals;
165  I.Fun.NumArgs                 = NumArgs;
166  I.Fun.ArgInfo                 = 0;
167  I.Fun.RefQualifierIsLValueRef = RefQualifierIsLvalueRef;
168  I.Fun.RefQualifierLoc         = RefQualifierLoc.getRawEncoding();
169  I.Fun.ExceptionSpecType       = ESpecType;
170  I.Fun.ExceptionSpecLoc        = ESpecLoc.getRawEncoding();
171  I.Fun.NumExceptions           = 0;
172  I.Fun.Exceptions              = 0;
173  I.Fun.NoexceptExpr            = 0;
174  I.Fun.TrailingReturnType   = TrailingReturnType.getAsOpaquePtr();
175
176  // new[] an argument array if needed.
177  if (NumArgs) {
178    // If the 'InlineParams' in Declarator is unused and big enough, put our
179    // parameter list there (in an effort to avoid new/delete traffic).  If it
180    // is already used (consider a function returning a function pointer) or too
181    // small (function taking too many arguments), go to the heap.
182    if (!TheDeclarator.InlineParamsUsed &&
183        NumArgs <= llvm::array_lengthof(TheDeclarator.InlineParams)) {
184      I.Fun.ArgInfo = TheDeclarator.InlineParams;
185      I.Fun.DeleteArgInfo = false;
186      TheDeclarator.InlineParamsUsed = true;
187    } else {
188      I.Fun.ArgInfo = new DeclaratorChunk::ParamInfo[NumArgs];
189      I.Fun.DeleteArgInfo = true;
190    }
191    memcpy(I.Fun.ArgInfo, ArgInfo, sizeof(ArgInfo[0])*NumArgs);
192  }
193
194  // Check what exception specification information we should actually store.
195  switch (ESpecType) {
196  default: break; // By default, save nothing.
197  case EST_Dynamic:
198    // new[] an exception array if needed
199    if (NumExceptions) {
200      I.Fun.NumExceptions = NumExceptions;
201      I.Fun.Exceptions = new DeclaratorChunk::TypeAndRange[NumExceptions];
202      for (unsigned i = 0; i != NumExceptions; ++i) {
203        I.Fun.Exceptions[i].Ty = Exceptions[i];
204        I.Fun.Exceptions[i].Range = ExceptionRanges[i];
205      }
206    }
207    break;
208
209  case EST_ComputedNoexcept:
210    I.Fun.NoexceptExpr = NoexceptExpr;
211    break;
212  }
213  return I;
214}
215
216/// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
217/// declaration specifier includes.
218///
219unsigned DeclSpec::getParsedSpecifiers() const {
220  unsigned Res = 0;
221  if (StorageClassSpec != SCS_unspecified ||
222      SCS_thread_specified)
223    Res |= PQ_StorageClassSpecifier;
224
225  if (TypeQualifiers != TQ_unspecified)
226    Res |= PQ_TypeQualifier;
227
228  if (hasTypeSpecifier())
229    Res |= PQ_TypeSpecifier;
230
231  if (FS_inline_specified || FS_virtual_specified || FS_explicit_specified)
232    Res |= PQ_FunctionSpecifier;
233  return Res;
234}
235
236template <class T> static bool BadSpecifier(T TNew, T TPrev,
237                                            const char *&PrevSpec,
238                                            unsigned &DiagID) {
239  PrevSpec = DeclSpec::getSpecifierName(TPrev);
240  DiagID = (TNew == TPrev ? diag::ext_duplicate_declspec
241            : diag::err_invalid_decl_spec_combination);
242  return true;
243}
244
245const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) {
246  switch (S) {
247  case DeclSpec::SCS_unspecified: return "unspecified";
248  case DeclSpec::SCS_typedef:     return "typedef";
249  case DeclSpec::SCS_extern:      return "extern";
250  case DeclSpec::SCS_static:      return "static";
251  case DeclSpec::SCS_auto:        return "auto";
252  case DeclSpec::SCS_register:    return "register";
253  case DeclSpec::SCS_private_extern: return "__private_extern__";
254  case DeclSpec::SCS_mutable:     return "mutable";
255  }
256  llvm_unreachable("Unknown typespec!");
257}
258
259const char *DeclSpec::getSpecifierName(TSW W) {
260  switch (W) {
261  case TSW_unspecified: return "unspecified";
262  case TSW_short:       return "short";
263  case TSW_long:        return "long";
264  case TSW_longlong:    return "long long";
265  }
266  llvm_unreachable("Unknown typespec!");
267}
268
269const char *DeclSpec::getSpecifierName(TSC C) {
270  switch (C) {
271  case TSC_unspecified: return "unspecified";
272  case TSC_imaginary:   return "imaginary";
273  case TSC_complex:     return "complex";
274  }
275  llvm_unreachable("Unknown typespec!");
276}
277
278
279const char *DeclSpec::getSpecifierName(TSS S) {
280  switch (S) {
281  case TSS_unspecified: return "unspecified";
282  case TSS_signed:      return "signed";
283  case TSS_unsigned:    return "unsigned";
284  }
285  llvm_unreachable("Unknown typespec!");
286}
287
288const char *DeclSpec::getSpecifierName(DeclSpec::TST T) {
289  switch (T) {
290  case DeclSpec::TST_unspecified: return "unspecified";
291  case DeclSpec::TST_void:        return "void";
292  case DeclSpec::TST_char:        return "char";
293  case DeclSpec::TST_wchar:       return "wchar_t";
294  case DeclSpec::TST_char16:      return "char16_t";
295  case DeclSpec::TST_char32:      return "char32_t";
296  case DeclSpec::TST_int:         return "int";
297  case DeclSpec::TST_float:       return "float";
298  case DeclSpec::TST_double:      return "double";
299  case DeclSpec::TST_bool:        return "_Bool";
300  case DeclSpec::TST_decimal32:   return "_Decimal32";
301  case DeclSpec::TST_decimal64:   return "_Decimal64";
302  case DeclSpec::TST_decimal128:  return "_Decimal128";
303  case DeclSpec::TST_enum:        return "enum";
304  case DeclSpec::TST_class:       return "class";
305  case DeclSpec::TST_union:       return "union";
306  case DeclSpec::TST_struct:      return "struct";
307  case DeclSpec::TST_typename:    return "type-name";
308  case DeclSpec::TST_typeofType:
309  case DeclSpec::TST_typeofExpr:  return "typeof";
310  case DeclSpec::TST_auto:        return "auto";
311  case DeclSpec::TST_decltype:    return "(decltype)";
312  case DeclSpec::TST_unknown_anytype: return "__unknown_anytype";
313  case DeclSpec::TST_error:       return "(error)";
314  }
315  llvm_unreachable("Unknown typespec!");
316}
317
318const char *DeclSpec::getSpecifierName(TQ T) {
319  switch (T) {
320  case DeclSpec::TQ_unspecified: return "unspecified";
321  case DeclSpec::TQ_const:       return "const";
322  case DeclSpec::TQ_restrict:    return "restrict";
323  case DeclSpec::TQ_volatile:    return "volatile";
324  }
325  llvm_unreachable("Unknown typespec!");
326}
327
328bool DeclSpec::SetStorageClassSpec(SCS S, SourceLocation Loc,
329                                   const char *&PrevSpec,
330                                   unsigned &DiagID,
331                                   const LangOptions &Lang) {
332  // OpenCL prohibits extern, auto, register, and static
333  // It seems sensible to prohibit private_extern too
334  if (Lang.OpenCL) {
335    switch (S) {
336    case SCS_extern:
337    case SCS_private_extern:
338    case SCS_auto:
339    case SCS_register:
340    case SCS_static:
341      DiagID   = diag::err_not_opencl_storage_class_specifier;
342      PrevSpec = getSpecifierName(S);
343      return true;
344    default:
345      break;
346    }
347  }
348
349  if (StorageClassSpec != SCS_unspecified) {
350    // Changing storage class is allowed only if the previous one
351    // was the 'extern' that is part of a linkage specification and
352    // the new storage class is 'typedef'.
353    if (!(SCS_extern_in_linkage_spec &&
354          StorageClassSpec == SCS_extern &&
355          S == SCS_typedef))
356      return BadSpecifier(S, (SCS)StorageClassSpec, PrevSpec, DiagID);
357  }
358  StorageClassSpec = S;
359  StorageClassSpecLoc = Loc;
360  assert((unsigned)S == StorageClassSpec && "SCS constants overflow bitfield");
361  return false;
362}
363
364bool DeclSpec::SetStorageClassSpecThread(SourceLocation Loc,
365                                         const char *&PrevSpec,
366                                         unsigned &DiagID) {
367  if (SCS_thread_specified) {
368    PrevSpec = "__thread";
369    DiagID = diag::ext_duplicate_declspec;
370    return true;
371  }
372  SCS_thread_specified = true;
373  SCS_threadLoc = Loc;
374  return false;
375}
376
377/// These methods set the specified attribute of the DeclSpec, but return true
378/// and ignore the request if invalid (e.g. "extern" then "auto" is
379/// specified).
380bool DeclSpec::SetTypeSpecWidth(TSW W, SourceLocation Loc,
381                                const char *&PrevSpec,
382                                unsigned &DiagID) {
383  // Overwrite TSWLoc only if TypeSpecWidth was unspecified, so that
384  // for 'long long' we will keep the source location of the first 'long'.
385  if (TypeSpecWidth == TSW_unspecified)
386    TSWLoc = Loc;
387  // Allow turning long -> long long.
388  else if (W != TSW_longlong || TypeSpecWidth != TSW_long)
389    return BadSpecifier(W, (TSW)TypeSpecWidth, PrevSpec, DiagID);
390  TypeSpecWidth = W;
391  if (TypeAltiVecVector && !TypeAltiVecBool &&
392      ((TypeSpecWidth == TSW_long) || (TypeSpecWidth == TSW_longlong))) {
393    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
394    DiagID = diag::warn_vector_long_decl_spec_combination;
395    return true;
396  }
397  return false;
398}
399
400bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc,
401                                  const char *&PrevSpec,
402                                  unsigned &DiagID) {
403  if (TypeSpecComplex != TSC_unspecified)
404    return BadSpecifier(C, (TSC)TypeSpecComplex, PrevSpec, DiagID);
405  TypeSpecComplex = C;
406  TSCLoc = Loc;
407  return false;
408}
409
410bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc,
411                               const char *&PrevSpec,
412                               unsigned &DiagID) {
413  if (TypeSpecSign != TSS_unspecified)
414    return BadSpecifier(S, (TSS)TypeSpecSign, PrevSpec, DiagID);
415  TypeSpecSign = S;
416  TSSLoc = Loc;
417  return false;
418}
419
420bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
421                               const char *&PrevSpec,
422                               unsigned &DiagID,
423                               ParsedType Rep) {
424  return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep);
425}
426
427bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
428                               SourceLocation TagNameLoc,
429                               const char *&PrevSpec,
430                               unsigned &DiagID,
431                               ParsedType Rep) {
432  assert(isTypeRep(T) && "T does not store a type");
433  assert(Rep && "no type provided!");
434  if (TypeSpecType != TST_unspecified) {
435    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
436    DiagID = diag::err_invalid_decl_spec_combination;
437    return true;
438  }
439  TypeSpecType = T;
440  TypeRep = Rep;
441  TSTLoc = TagKwLoc;
442  TSTNameLoc = TagNameLoc;
443  TypeSpecOwned = false;
444  return false;
445}
446
447bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
448                               const char *&PrevSpec,
449                               unsigned &DiagID,
450                               Expr *Rep) {
451  assert(isExprRep(T) && "T does not store an expr");
452  assert(Rep && "no expression provided!");
453  if (TypeSpecType != TST_unspecified) {
454    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
455    DiagID = diag::err_invalid_decl_spec_combination;
456    return true;
457  }
458  TypeSpecType = T;
459  ExprRep = Rep;
460  TSTLoc = Loc;
461  TSTNameLoc = Loc;
462  TypeSpecOwned = false;
463  return false;
464}
465
466bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
467                               const char *&PrevSpec,
468                               unsigned &DiagID,
469                               Decl *Rep, bool Owned) {
470  return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Owned);
471}
472
473bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
474                               SourceLocation TagNameLoc,
475                               const char *&PrevSpec,
476                               unsigned &DiagID,
477                               Decl *Rep, bool Owned) {
478  assert(isDeclRep(T) && "T does not store a decl");
479  // Unlike the other cases, we don't assert that we actually get a decl.
480
481  if (TypeSpecType != TST_unspecified) {
482    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
483    DiagID = diag::err_invalid_decl_spec_combination;
484    return true;
485  }
486  TypeSpecType = T;
487  DeclRep = Rep;
488  TSTLoc = TagKwLoc;
489  TSTNameLoc = TagNameLoc;
490  TypeSpecOwned = Owned;
491  return false;
492}
493
494bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
495                               const char *&PrevSpec,
496                               unsigned &DiagID) {
497  assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
498         "rep required for these type-spec kinds!");
499  if (TypeSpecType != TST_unspecified) {
500    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
501    DiagID = diag::err_invalid_decl_spec_combination;
502    return true;
503  }
504  TSTLoc = Loc;
505  TSTNameLoc = Loc;
506  if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
507    TypeAltiVecBool = true;
508    return false;
509  }
510  TypeSpecType = T;
511  TypeSpecOwned = false;
512  if (TypeAltiVecVector && !TypeAltiVecBool && (TypeSpecType == TST_double)) {
513    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
514    DiagID = diag::err_invalid_vector_decl_spec;
515    return true;
516  }
517  return false;
518}
519
520bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
521                          const char *&PrevSpec, unsigned &DiagID) {
522  if (TypeSpecType != TST_unspecified) {
523    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
524    DiagID = diag::err_invalid_vector_decl_spec_combination;
525    return true;
526  }
527  TypeAltiVecVector = isAltiVecVector;
528  AltiVecLoc = Loc;
529  return false;
530}
531
532bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
533                          const char *&PrevSpec, unsigned &DiagID) {
534  if (!TypeAltiVecVector || TypeAltiVecPixel ||
535      (TypeSpecType != TST_unspecified)) {
536    PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
537    DiagID = diag::err_invalid_pixel_decl_spec_combination;
538    return true;
539  }
540  TypeAltiVecPixel = isAltiVecPixel;
541  TSTLoc = Loc;
542  TSTNameLoc = Loc;
543  return false;
544}
545
546bool DeclSpec::SetTypeSpecError() {
547  TypeSpecType = TST_error;
548  TypeSpecOwned = false;
549  TSTLoc = SourceLocation();
550  TSTNameLoc = SourceLocation();
551  return false;
552}
553
554bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
555                           unsigned &DiagID, const LangOptions &Lang) {
556  // Duplicates turn into warnings pre-C99.
557  if ((TypeQualifiers & T) && !Lang.C99)
558    return BadSpecifier(T, T, PrevSpec, DiagID);
559  TypeQualifiers |= T;
560
561  switch (T) {
562  default: assert(0 && "Unknown type qualifier!");
563  case TQ_const:    TQ_constLoc = Loc; break;
564  case TQ_restrict: TQ_restrictLoc = Loc; break;
565  case TQ_volatile: TQ_volatileLoc = Loc; break;
566  }
567  return false;
568}
569
570bool DeclSpec::SetFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
571                                     unsigned &DiagID) {
572  // 'inline inline' is ok.
573  FS_inline_specified = true;
574  FS_inlineLoc = Loc;
575  return false;
576}
577
578bool DeclSpec::SetFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
579                                      unsigned &DiagID) {
580  // 'virtual virtual' is ok.
581  FS_virtual_specified = true;
582  FS_virtualLoc = Loc;
583  return false;
584}
585
586bool DeclSpec::SetFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
587                                       unsigned &DiagID) {
588  // 'explicit explicit' is ok.
589  FS_explicit_specified = true;
590  FS_explicitLoc = Loc;
591  return false;
592}
593
594bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
595                             unsigned &DiagID) {
596  if (Friend_specified) {
597    PrevSpec = "friend";
598    DiagID = diag::ext_duplicate_declspec;
599    return true;
600  }
601
602  Friend_specified = true;
603  FriendLoc = Loc;
604  return false;
605}
606
607bool DeclSpec::SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
608                                unsigned &DiagID) {
609  // 'constexpr constexpr' is ok.
610  Constexpr_specified = true;
611  ConstexprLoc = Loc;
612  return false;
613}
614
615void DeclSpec::setProtocolQualifiers(Decl * const *Protos,
616                                     unsigned NP,
617                                     SourceLocation *ProtoLocs,
618                                     SourceLocation LAngleLoc) {
619  if (NP == 0) return;
620  ProtocolQualifiers = new Decl*[NP];
621  ProtocolLocs = new SourceLocation[NP];
622  memcpy((void*)ProtocolQualifiers, Protos, sizeof(Decl*)*NP);
623  memcpy(ProtocolLocs, ProtoLocs, sizeof(SourceLocation)*NP);
624  NumProtocolQualifiers = NP;
625  ProtocolLAngleLoc = LAngleLoc;
626}
627
628void DeclSpec::SaveWrittenBuiltinSpecs() {
629  writtenBS.Sign = getTypeSpecSign();
630  writtenBS.Width = getTypeSpecWidth();
631  writtenBS.Type = getTypeSpecType();
632  // Search the list of attributes for the presence of a mode attribute.
633  writtenBS.ModeAttr = false;
634  AttributeList* attrs = getAttributes().getList();
635  while (attrs) {
636    if (attrs->getKind() == AttributeList::AT_mode) {
637      writtenBS.ModeAttr = true;
638      break;
639    }
640    attrs = attrs->getNext();
641  }
642}
643
644void DeclSpec::SaveStorageSpecifierAsWritten() {
645  if (SCS_extern_in_linkage_spec && StorageClassSpec == SCS_extern)
646    // If 'extern' is part of a linkage specification,
647    // then it is not a storage class "as written".
648    StorageClassSpecAsWritten = SCS_unspecified;
649  else
650    StorageClassSpecAsWritten = StorageClassSpec;
651}
652
653/// Finish - This does final analysis of the declspec, rejecting things like
654/// "_Imaginary" (lacking an FP type).  This returns a diagnostic to issue or
655/// diag::NUM_DIAGNOSTICS if there is no error.  After calling this method,
656/// DeclSpec is guaranteed self-consistent, even if an error occurred.
657void DeclSpec::Finish(Diagnostic &D, Preprocessor &PP) {
658  // Before possibly changing their values, save specs as written.
659  SaveWrittenBuiltinSpecs();
660  SaveStorageSpecifierAsWritten();
661
662  // Check the type specifier components first.
663
664  // Validate and finalize AltiVec vector declspec.
665  if (TypeAltiVecVector) {
666    if (TypeAltiVecBool) {
667      // Sign specifiers are not allowed with vector bool. (PIM 2.1)
668      if (TypeSpecSign != TSS_unspecified) {
669        Diag(D, TSSLoc, diag::err_invalid_vector_bool_decl_spec)
670          << getSpecifierName((TSS)TypeSpecSign);
671      }
672
673      // Only char/int are valid with vector bool. (PIM 2.1)
674      if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
675           (TypeSpecType != TST_int)) || TypeAltiVecPixel) {
676        Diag(D, TSTLoc, diag::err_invalid_vector_bool_decl_spec)
677          << (TypeAltiVecPixel ? "__pixel" :
678                                 getSpecifierName((TST)TypeSpecType));
679      }
680
681      // Only 'short' is valid with vector bool. (PIM 2.1)
682      if ((TypeSpecWidth != TSW_unspecified) && (TypeSpecWidth != TSW_short))
683        Diag(D, TSWLoc, diag::err_invalid_vector_bool_decl_spec)
684          << getSpecifierName((TSW)TypeSpecWidth);
685
686      // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
687      if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
688          (TypeSpecWidth != TSW_unspecified))
689        TypeSpecSign = TSS_unsigned;
690    }
691
692    if (TypeAltiVecPixel) {
693      //TODO: perform validation
694      TypeSpecType = TST_int;
695      TypeSpecSign = TSS_unsigned;
696      TypeSpecWidth = TSW_short;
697      TypeSpecOwned = false;
698    }
699  }
700
701  // signed/unsigned are only valid with int/char/wchar_t.
702  if (TypeSpecSign != TSS_unspecified) {
703    if (TypeSpecType == TST_unspecified)
704      TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
705    else if (TypeSpecType != TST_int  &&
706             TypeSpecType != TST_char && TypeSpecType != TST_wchar) {
707      Diag(D, TSSLoc, diag::err_invalid_sign_spec)
708        << getSpecifierName((TST)TypeSpecType);
709      // signed double -> double.
710      TypeSpecSign = TSS_unspecified;
711    }
712  }
713
714  // Validate the width of the type.
715  switch (TypeSpecWidth) {
716  case TSW_unspecified: break;
717  case TSW_short:    // short int
718  case TSW_longlong: // long long int
719    if (TypeSpecType == TST_unspecified)
720      TypeSpecType = TST_int; // short -> short int, long long -> long long int.
721    else if (TypeSpecType != TST_int) {
722      Diag(D, TSWLoc,
723           TypeSpecWidth == TSW_short ? diag::err_invalid_short_spec
724                                      : diag::err_invalid_longlong_spec)
725        <<  getSpecifierName((TST)TypeSpecType);
726      TypeSpecType = TST_int;
727      TypeSpecOwned = false;
728    }
729    break;
730  case TSW_long:  // long double, long int
731    if (TypeSpecType == TST_unspecified)
732      TypeSpecType = TST_int;  // long -> long int.
733    else if (TypeSpecType != TST_int && TypeSpecType != TST_double) {
734      Diag(D, TSWLoc, diag::err_invalid_long_spec)
735        << getSpecifierName((TST)TypeSpecType);
736      TypeSpecType = TST_int;
737      TypeSpecOwned = false;
738    }
739    break;
740  }
741
742  // TODO: if the implementation does not implement _Complex or _Imaginary,
743  // disallow their use.  Need information about the backend.
744  if (TypeSpecComplex != TSC_unspecified) {
745    if (TypeSpecType == TST_unspecified) {
746      Diag(D, TSCLoc, diag::ext_plain_complex)
747        << FixItHint::CreateInsertion(
748                              PP.getLocForEndOfToken(getTypeSpecComplexLoc()),
749                                                 " double");
750      TypeSpecType = TST_double;   // _Complex -> _Complex double.
751    } else if (TypeSpecType == TST_int || TypeSpecType == TST_char) {
752      // Note that this intentionally doesn't include _Complex _Bool.
753      Diag(D, TSTLoc, diag::ext_integer_complex);
754    } else if (TypeSpecType != TST_float && TypeSpecType != TST_double) {
755      Diag(D, TSCLoc, diag::err_invalid_complex_spec)
756        << getSpecifierName((TST)TypeSpecType);
757      TypeSpecComplex = TSC_unspecified;
758    }
759  }
760
761  // C++ [class.friend]p6:
762  //   No storage-class-specifier shall appear in the decl-specifier-seq
763  //   of a friend declaration.
764  if (isFriendSpecified() && getStorageClassSpec()) {
765    DeclSpec::SCS SC = getStorageClassSpec();
766    const char *SpecName = getSpecifierName(SC);
767
768    SourceLocation SCLoc = getStorageClassSpecLoc();
769    SourceLocation SCEndLoc = SCLoc.getFileLocWithOffset(strlen(SpecName));
770
771    Diag(D, SCLoc, diag::err_friend_storage_spec)
772      << SpecName
773      << FixItHint::CreateRemoval(SourceRange(SCLoc, SCEndLoc));
774
775    ClearStorageClassSpecs();
776  }
777
778  assert(!TypeSpecOwned || isDeclRep((TST) TypeSpecType));
779
780  // Okay, now we can infer the real type.
781
782  // TODO: return "auto function" and other bad things based on the real type.
783
784  // 'data definition has no type or storage class'?
785}
786
787bool DeclSpec::isMissingDeclaratorOk() {
788  TST tst = getTypeSpecType();
789  return isDeclRep(tst) && getRepAsDecl() != 0 &&
790    StorageClassSpec != DeclSpec::SCS_typedef;
791}
792
793void UnqualifiedId::clear() {
794  if (Kind == IK_TemplateId)
795    TemplateId->Destroy();
796
797  Kind = IK_Identifier;
798  Identifier = 0;
799  StartLocation = SourceLocation();
800  EndLocation = SourceLocation();
801}
802
803void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
804                                          OverloadedOperatorKind Op,
805                                          SourceLocation SymbolLocations[3]) {
806  Kind = IK_OperatorFunctionId;
807  StartLocation = OperatorLoc;
808  EndLocation = OperatorLoc;
809  OperatorFunctionId.Operator = Op;
810  for (unsigned I = 0; I != 3; ++I) {
811    OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding();
812
813    if (SymbolLocations[I].isValid())
814      EndLocation = SymbolLocations[I];
815  }
816}
817
818bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
819                                  const char *&PrevSpec) {
820  LastLocation = Loc;
821
822  if (Specifiers & VS) {
823    PrevSpec = getSpecifierName(VS);
824    return true;
825  }
826
827  Specifiers |= VS;
828
829  switch (VS) {
830  default: assert(0 && "Unknown specifier!");
831  case VS_Override: VS_overrideLoc = Loc; break;
832  case VS_Final:    VS_finalLoc = Loc; break;
833  }
834
835  return false;
836}
837
838const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
839  switch (VS) {
840  default: assert(0 && "Unknown specifier");
841  case VS_Override: return "override";
842  case VS_Final: return "final";
843  }
844}
845