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/Sema/DeclSpec.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/NestedNameSpecifier.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Parse/ParseDiagnostic.h" // FIXME: remove this back-dependency!
22 #include "clang/Sema/LocInfoType.h"
23 #include "clang/Sema/ParsedTemplate.h"
24 #include "clang/Sema/Sema.h"
25 #include "clang/Sema/SemaDiagnostic.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <cstring>
30 using namespace clang;
31 
32 
33 static DiagnosticBuilder Diag(DiagnosticsEngine &D, SourceLocation Loc,
34                               unsigned DiagID) {
35   return D.Report(Loc, DiagID);
36 }
37 
38 
39 void UnqualifiedId::setTemplateId(TemplateIdAnnotation *TemplateId) {
40   assert(TemplateId && "NULL template-id annotation?");
41   Kind = IK_TemplateId;
42   this->TemplateId = TemplateId;
43   StartLocation = TemplateId->TemplateNameLoc;
44   EndLocation = TemplateId->RAngleLoc;
45 }
46 
47 void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) {
48   assert(TemplateId && "NULL template-id annotation?");
49   Kind = IK_ConstructorTemplateId;
50   this->TemplateId = TemplateId;
51   StartLocation = TemplateId->TemplateNameLoc;
52   EndLocation = TemplateId->RAngleLoc;
53 }
54 
55 void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc,
56                           TypeLoc TL, SourceLocation ColonColonLoc) {
57   Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc);
58   if (Range.getBegin().isInvalid())
59     Range.setBegin(TL.getBeginLoc());
60   Range.setEnd(ColonColonLoc);
61 
62   assert(Range == Builder.getSourceRange() &&
63          "NestedNameSpecifierLoc range computation incorrect");
64 }
65 
66 void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier,
67                           SourceLocation IdentifierLoc,
68                           SourceLocation ColonColonLoc) {
69   Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc);
70 
71   if (Range.getBegin().isInvalid())
72     Range.setBegin(IdentifierLoc);
73   Range.setEnd(ColonColonLoc);
74 
75   assert(Range == Builder.getSourceRange() &&
76          "NestedNameSpecifierLoc range computation incorrect");
77 }
78 
79 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace,
80                           SourceLocation NamespaceLoc,
81                           SourceLocation ColonColonLoc) {
82   Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc);
83 
84   if (Range.getBegin().isInvalid())
85     Range.setBegin(NamespaceLoc);
86   Range.setEnd(ColonColonLoc);
87 
88   assert(Range == Builder.getSourceRange() &&
89          "NestedNameSpecifierLoc range computation incorrect");
90 }
91 
92 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
93                           SourceLocation AliasLoc,
94                           SourceLocation ColonColonLoc) {
95   Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc);
96 
97   if (Range.getBegin().isInvalid())
98     Range.setBegin(AliasLoc);
99   Range.setEnd(ColonColonLoc);
100 
101   assert(Range == Builder.getSourceRange() &&
102          "NestedNameSpecifierLoc range computation incorrect");
103 }
104 
105 void CXXScopeSpec::MakeGlobal(ASTContext &Context,
106                               SourceLocation ColonColonLoc) {
107   Builder.MakeGlobal(Context, ColonColonLoc);
108 
109   Range = SourceRange(ColonColonLoc);
110 
111   assert(Range == Builder.getSourceRange() &&
112          "NestedNameSpecifierLoc range computation incorrect");
113 }
114 
115 void CXXScopeSpec::MakeTrivial(ASTContext &Context,
116                                NestedNameSpecifier *Qualifier, SourceRange R) {
117   Builder.MakeTrivial(Context, Qualifier, R);
118   Range = R;
119 }
120 
121 void CXXScopeSpec::Adopt(NestedNameSpecifierLoc Other) {
122   if (!Other) {
123     Range = SourceRange();
124     Builder.Clear();
125     return;
126   }
127 
128   Range = Other.getSourceRange();
129   Builder.Adopt(Other);
130 }
131 
132 SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const {
133   if (!Builder.getRepresentation())
134     return SourceLocation();
135   return Builder.getTemporary().getLocalBeginLoc();
136 }
137 
138 NestedNameSpecifierLoc
139 CXXScopeSpec::getWithLocInContext(ASTContext &Context) const {
140   if (!Builder.getRepresentation())
141     return NestedNameSpecifierLoc();
142 
143   return Builder.getWithLocInContext(Context);
144 }
145 
146 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
147 /// "TheDeclarator" is the declarator that this will be added to.
148 DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto,
149                                              bool isAmbiguous,
150                                              SourceLocation LParenLoc,
151                                              ParamInfo *ArgInfo,
152                                              unsigned NumArgs,
153                                              SourceLocation EllipsisLoc,
154                                              SourceLocation RParenLoc,
155                                              unsigned TypeQuals,
156                                              bool RefQualifierIsLvalueRef,
157                                              SourceLocation RefQualifierLoc,
158                                              SourceLocation ConstQualifierLoc,
159                                              SourceLocation
160                                                  VolatileQualifierLoc,
161                                              SourceLocation MutableLoc,
162                                              ExceptionSpecificationType
163                                                  ESpecType,
164                                              SourceLocation ESpecLoc,
165                                              ParsedType *Exceptions,
166                                              SourceRange *ExceptionRanges,
167                                              unsigned NumExceptions,
168                                              Expr *NoexceptExpr,
169                                              SourceLocation LocalRangeBegin,
170                                              SourceLocation LocalRangeEnd,
171                                              Declarator &TheDeclarator,
172                                              TypeResult TrailingReturnType) {
173   assert(!(TypeQuals & DeclSpec::TQ_atomic) &&
174          "function cannot have _Atomic qualifier");
175 
176   DeclaratorChunk I;
177   I.Kind                        = Function;
178   I.Loc                         = LocalRangeBegin;
179   I.EndLoc                      = LocalRangeEnd;
180   I.Fun.AttrList                = 0;
181   I.Fun.hasPrototype            = hasProto;
182   I.Fun.isVariadic              = EllipsisLoc.isValid();
183   I.Fun.isAmbiguous             = isAmbiguous;
184   I.Fun.LParenLoc               = LParenLoc.getRawEncoding();
185   I.Fun.EllipsisLoc             = EllipsisLoc.getRawEncoding();
186   I.Fun.RParenLoc               = RParenLoc.getRawEncoding();
187   I.Fun.DeleteArgInfo           = false;
188   I.Fun.TypeQuals               = TypeQuals;
189   I.Fun.NumArgs                 = NumArgs;
190   I.Fun.ArgInfo                 = 0;
191   I.Fun.RefQualifierIsLValueRef = RefQualifierIsLvalueRef;
192   I.Fun.RefQualifierLoc         = RefQualifierLoc.getRawEncoding();
193   I.Fun.ConstQualifierLoc       = ConstQualifierLoc.getRawEncoding();
194   I.Fun.VolatileQualifierLoc    = VolatileQualifierLoc.getRawEncoding();
195   I.Fun.MutableLoc              = MutableLoc.getRawEncoding();
196   I.Fun.ExceptionSpecType       = ESpecType;
197   I.Fun.ExceptionSpecLoc        = ESpecLoc.getRawEncoding();
198   I.Fun.NumExceptions           = 0;
199   I.Fun.Exceptions              = 0;
200   I.Fun.NoexceptExpr            = 0;
201   I.Fun.HasTrailingReturnType   = TrailingReturnType.isUsable() ||
202                                   TrailingReturnType.isInvalid();
203   I.Fun.TrailingReturnType      = TrailingReturnType.get();
204 
205   // new[] an argument array if needed.
206   if (NumArgs) {
207     // If the 'InlineParams' in Declarator is unused and big enough, put our
208     // parameter list there (in an effort to avoid new/delete traffic).  If it
209     // is already used (consider a function returning a function pointer) or too
210     // small (function taking too many arguments), go to the heap.
211     if (!TheDeclarator.InlineParamsUsed &&
212         NumArgs <= llvm::array_lengthof(TheDeclarator.InlineParams)) {
213       I.Fun.ArgInfo = TheDeclarator.InlineParams;
214       I.Fun.DeleteArgInfo = false;
215       TheDeclarator.InlineParamsUsed = true;
216     } else {
217       I.Fun.ArgInfo = new DeclaratorChunk::ParamInfo[NumArgs];
218       I.Fun.DeleteArgInfo = true;
219     }
220     memcpy(I.Fun.ArgInfo, ArgInfo, sizeof(ArgInfo[0])*NumArgs);
221   }
222 
223   // Check what exception specification information we should actually store.
224   switch (ESpecType) {
225   default: break; // By default, save nothing.
226   case EST_Dynamic:
227     // new[] an exception array if needed
228     if (NumExceptions) {
229       I.Fun.NumExceptions = NumExceptions;
230       I.Fun.Exceptions = new DeclaratorChunk::TypeAndRange[NumExceptions];
231       for (unsigned i = 0; i != NumExceptions; ++i) {
232         I.Fun.Exceptions[i].Ty = Exceptions[i];
233         I.Fun.Exceptions[i].Range = ExceptionRanges[i];
234       }
235     }
236     break;
237 
238   case EST_ComputedNoexcept:
239     I.Fun.NoexceptExpr = NoexceptExpr;
240     break;
241   }
242   return I;
243 }
244 
245 bool Declarator::isDeclarationOfFunction() const {
246   for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
247     switch (DeclTypeInfo[i].Kind) {
248     case DeclaratorChunk::Function:
249       return true;
250     case DeclaratorChunk::Paren:
251       continue;
252     case DeclaratorChunk::Pointer:
253     case DeclaratorChunk::Reference:
254     case DeclaratorChunk::Array:
255     case DeclaratorChunk::BlockPointer:
256     case DeclaratorChunk::MemberPointer:
257       return false;
258     }
259     llvm_unreachable("Invalid type chunk");
260   }
261 
262   switch (DS.getTypeSpecType()) {
263     case TST_atomic:
264     case TST_auto:
265     case TST_bool:
266     case TST_char:
267     case TST_char16:
268     case TST_char32:
269     case TST_class:
270     case TST_decimal128:
271     case TST_decimal32:
272     case TST_decimal64:
273     case TST_double:
274     case TST_enum:
275     case TST_error:
276     case TST_float:
277     case TST_half:
278     case TST_int:
279     case TST_int128:
280     case TST_struct:
281     case TST_interface:
282     case TST_union:
283     case TST_unknown_anytype:
284     case TST_unspecified:
285     case TST_void:
286     case TST_wchar:
287     case TST_image1d_t:
288     case TST_image1d_array_t:
289     case TST_image1d_buffer_t:
290     case TST_image2d_t:
291     case TST_image2d_array_t:
292     case TST_image3d_t:
293     case TST_sampler_t:
294     case TST_event_t:
295       return false;
296 
297     case TST_decltype:
298     case TST_typeofExpr:
299       if (Expr *E = DS.getRepAsExpr())
300         return E->getType()->isFunctionType();
301       return false;
302 
303     case TST_underlyingType:
304     case TST_typename:
305     case TST_typeofType: {
306       QualType QT = DS.getRepAsType().get();
307       if (QT.isNull())
308         return false;
309 
310       if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT))
311         QT = LIT->getType();
312 
313       if (QT.isNull())
314         return false;
315 
316       return QT->isFunctionType();
317     }
318   }
319 
320   llvm_unreachable("Invalid TypeSpecType!");
321 }
322 
323 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
324 /// declaration specifier includes.
325 ///
326 unsigned DeclSpec::getParsedSpecifiers() const {
327   unsigned Res = 0;
328   if (StorageClassSpec != SCS_unspecified ||
329       ThreadStorageClassSpec != TSCS_unspecified)
330     Res |= PQ_StorageClassSpecifier;
331 
332   if (TypeQualifiers != TQ_unspecified)
333     Res |= PQ_TypeQualifier;
334 
335   if (hasTypeSpecifier())
336     Res |= PQ_TypeSpecifier;
337 
338   if (FS_inline_specified || FS_virtual_specified || FS_explicit_specified ||
339       FS_noreturn_specified)
340     Res |= PQ_FunctionSpecifier;
341   return Res;
342 }
343 
344 template <class T> static bool BadSpecifier(T TNew, T TPrev,
345                                             const char *&PrevSpec,
346                                             unsigned &DiagID,
347                                             bool IsExtension = true) {
348   PrevSpec = DeclSpec::getSpecifierName(TPrev);
349   if (TNew != TPrev)
350     DiagID = diag::err_invalid_decl_spec_combination;
351   else
352     DiagID = IsExtension ? diag::ext_duplicate_declspec :
353                            diag::warn_duplicate_declspec;
354   return true;
355 }
356 
357 const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) {
358   switch (S) {
359   case DeclSpec::SCS_unspecified: return "unspecified";
360   case DeclSpec::SCS_typedef:     return "typedef";
361   case DeclSpec::SCS_extern:      return "extern";
362   case DeclSpec::SCS_static:      return "static";
363   case DeclSpec::SCS_auto:        return "auto";
364   case DeclSpec::SCS_register:    return "register";
365   case DeclSpec::SCS_private_extern: return "__private_extern__";
366   case DeclSpec::SCS_mutable:     return "mutable";
367   }
368   llvm_unreachable("Unknown typespec!");
369 }
370 
371 const char *DeclSpec::getSpecifierName(DeclSpec::TSCS S) {
372   switch (S) {
373   case DeclSpec::TSCS_unspecified:   return "unspecified";
374   case DeclSpec::TSCS___thread:      return "__thread";
375   case DeclSpec::TSCS_thread_local:  return "thread_local";
376   case DeclSpec::TSCS__Thread_local: return "_Thread_local";
377   }
378   llvm_unreachable("Unknown typespec!");
379 }
380 
381 const char *DeclSpec::getSpecifierName(TSW W) {
382   switch (W) {
383   case TSW_unspecified: return "unspecified";
384   case TSW_short:       return "short";
385   case TSW_long:        return "long";
386   case TSW_longlong:    return "long long";
387   }
388   llvm_unreachable("Unknown typespec!");
389 }
390 
391 const char *DeclSpec::getSpecifierName(TSC C) {
392   switch (C) {
393   case TSC_unspecified: return "unspecified";
394   case TSC_imaginary:   return "imaginary";
395   case TSC_complex:     return "complex";
396   }
397   llvm_unreachable("Unknown typespec!");
398 }
399 
400 
401 const char *DeclSpec::getSpecifierName(TSS S) {
402   switch (S) {
403   case TSS_unspecified: return "unspecified";
404   case TSS_signed:      return "signed";
405   case TSS_unsigned:    return "unsigned";
406   }
407   llvm_unreachable("Unknown typespec!");
408 }
409 
410 const char *DeclSpec::getSpecifierName(DeclSpec::TST T) {
411   switch (T) {
412   case DeclSpec::TST_unspecified: return "unspecified";
413   case DeclSpec::TST_void:        return "void";
414   case DeclSpec::TST_char:        return "char";
415   case DeclSpec::TST_wchar:       return "wchar_t";
416   case DeclSpec::TST_char16:      return "char16_t";
417   case DeclSpec::TST_char32:      return "char32_t";
418   case DeclSpec::TST_int:         return "int";
419   case DeclSpec::TST_int128:      return "__int128";
420   case DeclSpec::TST_half:        return "half";
421   case DeclSpec::TST_float:       return "float";
422   case DeclSpec::TST_double:      return "double";
423   case DeclSpec::TST_bool:        return "_Bool";
424   case DeclSpec::TST_decimal32:   return "_Decimal32";
425   case DeclSpec::TST_decimal64:   return "_Decimal64";
426   case DeclSpec::TST_decimal128:  return "_Decimal128";
427   case DeclSpec::TST_enum:        return "enum";
428   case DeclSpec::TST_class:       return "class";
429   case DeclSpec::TST_union:       return "union";
430   case DeclSpec::TST_struct:      return "struct";
431   case DeclSpec::TST_interface:   return "__interface";
432   case DeclSpec::TST_typename:    return "type-name";
433   case DeclSpec::TST_typeofType:
434   case DeclSpec::TST_typeofExpr:  return "typeof";
435   case DeclSpec::TST_auto:        return "auto";
436   case DeclSpec::TST_decltype:    return "(decltype)";
437   case DeclSpec::TST_underlyingType: return "__underlying_type";
438   case DeclSpec::TST_unknown_anytype: return "__unknown_anytype";
439   case DeclSpec::TST_atomic: return "_Atomic";
440   case DeclSpec::TST_image1d_t:   return "image1d_t";
441   case DeclSpec::TST_image1d_array_t: return "image1d_array_t";
442   case DeclSpec::TST_image1d_buffer_t: return "image1d_buffer_t";
443   case DeclSpec::TST_image2d_t:   return "image2d_t";
444   case DeclSpec::TST_image2d_array_t: return "image2d_array_t";
445   case DeclSpec::TST_image3d_t:   return "image3d_t";
446   case DeclSpec::TST_sampler_t:   return "sampler_t";
447   case DeclSpec::TST_event_t:     return "event_t";
448   case DeclSpec::TST_error:       return "(error)";
449   }
450   llvm_unreachable("Unknown typespec!");
451 }
452 
453 const char *DeclSpec::getSpecifierName(TQ T) {
454   switch (T) {
455   case DeclSpec::TQ_unspecified: return "unspecified";
456   case DeclSpec::TQ_const:       return "const";
457   case DeclSpec::TQ_restrict:    return "restrict";
458   case DeclSpec::TQ_volatile:    return "volatile";
459   case DeclSpec::TQ_atomic:      return "_Atomic";
460   }
461   llvm_unreachable("Unknown typespec!");
462 }
463 
464 bool DeclSpec::SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
465                                    const char *&PrevSpec,
466                                    unsigned &DiagID) {
467   // OpenCL v1.1 s6.8g: "The extern, static, auto and register storage-class
468   // specifiers are not supported.
469   // It seems sensible to prohibit private_extern too
470   // The cl_clang_storage_class_specifiers extension enables support for
471   // these storage-class specifiers.
472   // OpenCL v1.2 s6.8 changes this to "The auto and register storage-class
473   // specifiers are not supported."
474   if (S.getLangOpts().OpenCL &&
475       !S.getOpenCLOptions().cl_clang_storage_class_specifiers) {
476     switch (SC) {
477     case SCS_extern:
478     case SCS_private_extern:
479     case SCS_static:
480         if (S.getLangOpts().OpenCLVersion < 120) {
481           DiagID   = diag::err_not_opencl_storage_class_specifier;
482           PrevSpec = getSpecifierName(SC);
483           return true;
484         }
485         break;
486     case SCS_auto:
487     case SCS_register:
488       DiagID   = diag::err_not_opencl_storage_class_specifier;
489       PrevSpec = getSpecifierName(SC);
490       return true;
491     default:
492       break;
493     }
494   }
495 
496   if (StorageClassSpec != SCS_unspecified) {
497     // Maybe this is an attempt to use C++0x 'auto' outside of C++0x mode.
498     bool isInvalid = true;
499     if (TypeSpecType == TST_unspecified && S.getLangOpts().CPlusPlus) {
500       if (SC == SCS_auto)
501         return SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID);
502       if (StorageClassSpec == SCS_auto) {
503         isInvalid = SetTypeSpecType(TST_auto, StorageClassSpecLoc,
504                                     PrevSpec, DiagID);
505         assert(!isInvalid && "auto SCS -> TST recovery failed");
506       }
507     }
508 
509     // Changing storage class is allowed only if the previous one
510     // was the 'extern' that is part of a linkage specification and
511     // the new storage class is 'typedef'.
512     if (isInvalid &&
513         !(SCS_extern_in_linkage_spec &&
514           StorageClassSpec == SCS_extern &&
515           SC == SCS_typedef))
516       return BadSpecifier(SC, (SCS)StorageClassSpec, PrevSpec, DiagID);
517   }
518   StorageClassSpec = SC;
519   StorageClassSpecLoc = Loc;
520   assert((unsigned)SC == StorageClassSpec && "SCS constants overflow bitfield");
521   return false;
522 }
523 
524 bool DeclSpec::SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
525                                          const char *&PrevSpec,
526                                          unsigned &DiagID) {
527   if (ThreadStorageClassSpec != TSCS_unspecified)
528     return BadSpecifier(TSC, (TSCS)ThreadStorageClassSpec, PrevSpec, DiagID);
529 
530   ThreadStorageClassSpec = TSC;
531   ThreadStorageClassSpecLoc = Loc;
532   return false;
533 }
534 
535 /// These methods set the specified attribute of the DeclSpec, but return true
536 /// and ignore the request if invalid (e.g. "extern" then "auto" is
537 /// specified).
538 bool DeclSpec::SetTypeSpecWidth(TSW W, SourceLocation Loc,
539                                 const char *&PrevSpec,
540                                 unsigned &DiagID) {
541   // Overwrite TSWLoc only if TypeSpecWidth was unspecified, so that
542   // for 'long long' we will keep the source location of the first 'long'.
543   if (TypeSpecWidth == TSW_unspecified)
544     TSWLoc = Loc;
545   // Allow turning long -> long long.
546   else if (W != TSW_longlong || TypeSpecWidth != TSW_long)
547     return BadSpecifier(W, (TSW)TypeSpecWidth, PrevSpec, DiagID);
548   TypeSpecWidth = W;
549   if (TypeAltiVecVector && !TypeAltiVecBool &&
550       ((TypeSpecWidth == TSW_long) || (TypeSpecWidth == TSW_longlong))) {
551     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
552     DiagID = diag::warn_vector_long_decl_spec_combination;
553     return true;
554   }
555   return false;
556 }
557 
558 bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc,
559                                   const char *&PrevSpec,
560                                   unsigned &DiagID) {
561   if (TypeSpecComplex != TSC_unspecified)
562     return BadSpecifier(C, (TSC)TypeSpecComplex, PrevSpec, DiagID);
563   TypeSpecComplex = C;
564   TSCLoc = Loc;
565   return false;
566 }
567 
568 bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc,
569                                const char *&PrevSpec,
570                                unsigned &DiagID) {
571   if (TypeSpecSign != TSS_unspecified)
572     return BadSpecifier(S, (TSS)TypeSpecSign, PrevSpec, DiagID);
573   TypeSpecSign = S;
574   TSSLoc = Loc;
575   return false;
576 }
577 
578 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
579                                const char *&PrevSpec,
580                                unsigned &DiagID,
581                                ParsedType Rep) {
582   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep);
583 }
584 
585 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
586                                SourceLocation TagNameLoc,
587                                const char *&PrevSpec,
588                                unsigned &DiagID,
589                                ParsedType Rep) {
590   assert(isTypeRep(T) && "T does not store a type");
591   assert(Rep && "no type provided!");
592   if (TypeSpecType != TST_unspecified) {
593     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
594     DiagID = diag::err_invalid_decl_spec_combination;
595     return true;
596   }
597   TypeSpecType = T;
598   TypeRep = Rep;
599   TSTLoc = TagKwLoc;
600   TSTNameLoc = TagNameLoc;
601   TypeSpecOwned = false;
602   return false;
603 }
604 
605 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
606                                const char *&PrevSpec,
607                                unsigned &DiagID,
608                                Expr *Rep) {
609   assert(isExprRep(T) && "T does not store an expr");
610   assert(Rep && "no expression provided!");
611   if (TypeSpecType != TST_unspecified) {
612     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
613     DiagID = diag::err_invalid_decl_spec_combination;
614     return true;
615   }
616   TypeSpecType = T;
617   ExprRep = Rep;
618   TSTLoc = Loc;
619   TSTNameLoc = Loc;
620   TypeSpecOwned = false;
621   return false;
622 }
623 
624 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
625                                const char *&PrevSpec,
626                                unsigned &DiagID,
627                                Decl *Rep, bool Owned) {
628   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Owned);
629 }
630 
631 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
632                                SourceLocation TagNameLoc,
633                                const char *&PrevSpec,
634                                unsigned &DiagID,
635                                Decl *Rep, bool Owned) {
636   assert(isDeclRep(T) && "T does not store a decl");
637   // Unlike the other cases, we don't assert that we actually get a decl.
638 
639   if (TypeSpecType != TST_unspecified) {
640     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
641     DiagID = diag::err_invalid_decl_spec_combination;
642     return true;
643   }
644   TypeSpecType = T;
645   DeclRep = Rep;
646   TSTLoc = TagKwLoc;
647   TSTNameLoc = TagNameLoc;
648   TypeSpecOwned = Owned;
649   return false;
650 }
651 
652 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
653                                const char *&PrevSpec,
654                                unsigned &DiagID) {
655   assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
656          "rep required for these type-spec kinds!");
657   if (TypeSpecType != TST_unspecified) {
658     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
659     DiagID = diag::err_invalid_decl_spec_combination;
660     return true;
661   }
662   TSTLoc = Loc;
663   TSTNameLoc = Loc;
664   if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
665     TypeAltiVecBool = true;
666     return false;
667   }
668   TypeSpecType = T;
669   TypeSpecOwned = false;
670   if (TypeAltiVecVector && !TypeAltiVecBool && (TypeSpecType == TST_double)) {
671     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
672     DiagID = diag::err_invalid_vector_decl_spec;
673     return true;
674   }
675   return false;
676 }
677 
678 bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
679                           const char *&PrevSpec, unsigned &DiagID) {
680   if (TypeSpecType != TST_unspecified) {
681     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
682     DiagID = diag::err_invalid_vector_decl_spec_combination;
683     return true;
684   }
685   TypeAltiVecVector = isAltiVecVector;
686   AltiVecLoc = Loc;
687   return false;
688 }
689 
690 bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
691                           const char *&PrevSpec, unsigned &DiagID) {
692   if (!TypeAltiVecVector || TypeAltiVecPixel ||
693       (TypeSpecType != TST_unspecified)) {
694     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
695     DiagID = diag::err_invalid_pixel_decl_spec_combination;
696     return true;
697   }
698   TypeAltiVecPixel = isAltiVecPixel;
699   TSTLoc = Loc;
700   TSTNameLoc = Loc;
701   return false;
702 }
703 
704 bool DeclSpec::SetTypeSpecError() {
705   TypeSpecType = TST_error;
706   TypeSpecOwned = false;
707   TSTLoc = SourceLocation();
708   TSTNameLoc = SourceLocation();
709   return false;
710 }
711 
712 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
713                            unsigned &DiagID, const LangOptions &Lang) {
714   // Duplicates are permitted in C99, but are not permitted in C++. However,
715   // since this is likely not what the user intended, we will always warn.  We
716   // do not need to set the qualifier's location since we already have it.
717   if (TypeQualifiers & T) {
718     bool IsExtension = true;
719     if (Lang.C99)
720       IsExtension = false;
721     return BadSpecifier(T, T, PrevSpec, DiagID, IsExtension);
722   }
723   TypeQualifiers |= T;
724 
725   switch (T) {
726   case TQ_unspecified: break;
727   case TQ_const:    TQ_constLoc = Loc; return false;
728   case TQ_restrict: TQ_restrictLoc = Loc; return false;
729   case TQ_volatile: TQ_volatileLoc = Loc; return false;
730   case TQ_atomic:   TQ_atomicLoc = Loc; return false;
731   }
732 
733   llvm_unreachable("Unknown type qualifier!");
734 }
735 
736 bool DeclSpec::setFunctionSpecInline(SourceLocation Loc) {
737   // 'inline inline' is ok.
738   FS_inline_specified = true;
739   FS_inlineLoc = Loc;
740   return false;
741 }
742 
743 bool DeclSpec::setFunctionSpecVirtual(SourceLocation Loc) {
744   // 'virtual virtual' is ok.
745   FS_virtual_specified = true;
746   FS_virtualLoc = Loc;
747   return false;
748 }
749 
750 bool DeclSpec::setFunctionSpecExplicit(SourceLocation Loc) {
751   // 'explicit explicit' is ok.
752   FS_explicit_specified = true;
753   FS_explicitLoc = Loc;
754   return false;
755 }
756 
757 bool DeclSpec::setFunctionSpecNoreturn(SourceLocation Loc) {
758   // '_Noreturn _Noreturn' is ok.
759   FS_noreturn_specified = true;
760   FS_noreturnLoc = Loc;
761   return false;
762 }
763 
764 bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
765                              unsigned &DiagID) {
766   if (Friend_specified) {
767     PrevSpec = "friend";
768     DiagID = diag::ext_duplicate_declspec;
769     return true;
770   }
771 
772   Friend_specified = true;
773   FriendLoc = Loc;
774   return false;
775 }
776 
777 bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
778                                     unsigned &DiagID) {
779   if (isModulePrivateSpecified()) {
780     PrevSpec = "__module_private__";
781     DiagID = diag::ext_duplicate_declspec;
782     return true;
783   }
784 
785   ModulePrivateLoc = Loc;
786   return false;
787 }
788 
789 bool DeclSpec::SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
790                                 unsigned &DiagID) {
791   // 'constexpr constexpr' is ok.
792   Constexpr_specified = true;
793   ConstexprLoc = Loc;
794   return false;
795 }
796 
797 void DeclSpec::setProtocolQualifiers(Decl * const *Protos,
798                                      unsigned NP,
799                                      SourceLocation *ProtoLocs,
800                                      SourceLocation LAngleLoc) {
801   if (NP == 0) return;
802   Decl **ProtoQuals = new Decl*[NP];
803   memcpy(ProtoQuals, Protos, sizeof(Decl*)*NP);
804   ProtocolQualifiers = ProtoQuals;
805   ProtocolLocs = new SourceLocation[NP];
806   memcpy(ProtocolLocs, ProtoLocs, sizeof(SourceLocation)*NP);
807   NumProtocolQualifiers = NP;
808   ProtocolLAngleLoc = LAngleLoc;
809 }
810 
811 void DeclSpec::SaveWrittenBuiltinSpecs() {
812   writtenBS.Sign = getTypeSpecSign();
813   writtenBS.Width = getTypeSpecWidth();
814   writtenBS.Type = getTypeSpecType();
815   // Search the list of attributes for the presence of a mode attribute.
816   writtenBS.ModeAttr = false;
817   AttributeList* attrs = getAttributes().getList();
818   while (attrs) {
819     if (attrs->getKind() == AttributeList::AT_Mode) {
820       writtenBS.ModeAttr = true;
821       break;
822     }
823     attrs = attrs->getNext();
824   }
825 }
826 
827 /// Finish - This does final analysis of the declspec, rejecting things like
828 /// "_Imaginary" (lacking an FP type).  This returns a diagnostic to issue or
829 /// diag::NUM_DIAGNOSTICS if there is no error.  After calling this method,
830 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
831 void DeclSpec::Finish(DiagnosticsEngine &D, Preprocessor &PP) {
832   // Before possibly changing their values, save specs as written.
833   SaveWrittenBuiltinSpecs();
834 
835   // Check the type specifier components first.
836 
837   // Validate and finalize AltiVec vector declspec.
838   if (TypeAltiVecVector) {
839     if (TypeAltiVecBool) {
840       // Sign specifiers are not allowed with vector bool. (PIM 2.1)
841       if (TypeSpecSign != TSS_unspecified) {
842         Diag(D, TSSLoc, diag::err_invalid_vector_bool_decl_spec)
843           << getSpecifierName((TSS)TypeSpecSign);
844       }
845 
846       // Only char/int are valid with vector bool. (PIM 2.1)
847       if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
848            (TypeSpecType != TST_int)) || TypeAltiVecPixel) {
849         Diag(D, TSTLoc, diag::err_invalid_vector_bool_decl_spec)
850           << (TypeAltiVecPixel ? "__pixel" :
851                                  getSpecifierName((TST)TypeSpecType));
852       }
853 
854       // Only 'short' is valid with vector bool. (PIM 2.1)
855       if ((TypeSpecWidth != TSW_unspecified) && (TypeSpecWidth != TSW_short))
856         Diag(D, TSWLoc, diag::err_invalid_vector_bool_decl_spec)
857           << getSpecifierName((TSW)TypeSpecWidth);
858 
859       // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
860       if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
861           (TypeSpecWidth != TSW_unspecified))
862         TypeSpecSign = TSS_unsigned;
863     }
864 
865     if (TypeAltiVecPixel) {
866       //TODO: perform validation
867       TypeSpecType = TST_int;
868       TypeSpecSign = TSS_unsigned;
869       TypeSpecWidth = TSW_short;
870       TypeSpecOwned = false;
871     }
872   }
873 
874   // signed/unsigned are only valid with int/char/wchar_t.
875   if (TypeSpecSign != TSS_unspecified) {
876     if (TypeSpecType == TST_unspecified)
877       TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
878     else if (TypeSpecType != TST_int  && TypeSpecType != TST_int128 &&
879              TypeSpecType != TST_char && TypeSpecType != TST_wchar) {
880       Diag(D, TSSLoc, diag::err_invalid_sign_spec)
881         << getSpecifierName((TST)TypeSpecType);
882       // signed double -> double.
883       TypeSpecSign = TSS_unspecified;
884     }
885   }
886 
887   // Validate the width of the type.
888   switch (TypeSpecWidth) {
889   case TSW_unspecified: break;
890   case TSW_short:    // short int
891   case TSW_longlong: // long long int
892     if (TypeSpecType == TST_unspecified)
893       TypeSpecType = TST_int; // short -> short int, long long -> long long int.
894     else if (TypeSpecType != TST_int) {
895       Diag(D, TSWLoc,
896            TypeSpecWidth == TSW_short ? diag::err_invalid_short_spec
897                                       : diag::err_invalid_longlong_spec)
898         <<  getSpecifierName((TST)TypeSpecType);
899       TypeSpecType = TST_int;
900       TypeSpecOwned = false;
901     }
902     break;
903   case TSW_long:  // long double, long int
904     if (TypeSpecType == TST_unspecified)
905       TypeSpecType = TST_int;  // long -> long int.
906     else if (TypeSpecType != TST_int && TypeSpecType != TST_double) {
907       Diag(D, TSWLoc, diag::err_invalid_long_spec)
908         << getSpecifierName((TST)TypeSpecType);
909       TypeSpecType = TST_int;
910       TypeSpecOwned = false;
911     }
912     break;
913   }
914 
915   // TODO: if the implementation does not implement _Complex or _Imaginary,
916   // disallow their use.  Need information about the backend.
917   if (TypeSpecComplex != TSC_unspecified) {
918     if (TypeSpecType == TST_unspecified) {
919       Diag(D, TSCLoc, diag::ext_plain_complex)
920         << FixItHint::CreateInsertion(
921                               PP.getLocForEndOfToken(getTypeSpecComplexLoc()),
922                                                  " double");
923       TypeSpecType = TST_double;   // _Complex -> _Complex double.
924     } else if (TypeSpecType == TST_int || TypeSpecType == TST_char) {
925       // Note that this intentionally doesn't include _Complex _Bool.
926       if (!PP.getLangOpts().CPlusPlus)
927         Diag(D, TSTLoc, diag::ext_integer_complex);
928     } else if (TypeSpecType != TST_float && TypeSpecType != TST_double) {
929       Diag(D, TSCLoc, diag::err_invalid_complex_spec)
930         << getSpecifierName((TST)TypeSpecType);
931       TypeSpecComplex = TSC_unspecified;
932     }
933   }
934 
935   // C11 6.7.1/3, C++11 [dcl.stc]p1, GNU TLS: __thread, thread_local and
936   // _Thread_local can only appear with the 'static' and 'extern' storage class
937   // specifiers. We also allow __private_extern__ as an extension.
938   if (ThreadStorageClassSpec != TSCS_unspecified) {
939     switch (StorageClassSpec) {
940     case SCS_unspecified:
941     case SCS_extern:
942     case SCS_private_extern:
943     case SCS_static:
944       break;
945     default:
946       if (PP.getSourceManager().isBeforeInTranslationUnit(
947             getThreadStorageClassSpecLoc(), getStorageClassSpecLoc()))
948         Diag(D, getStorageClassSpecLoc(),
949              diag::err_invalid_decl_spec_combination)
950           << DeclSpec::getSpecifierName(getThreadStorageClassSpec())
951           << SourceRange(getThreadStorageClassSpecLoc());
952       else
953         Diag(D, getThreadStorageClassSpecLoc(),
954              diag::err_invalid_decl_spec_combination)
955           << DeclSpec::getSpecifierName(getStorageClassSpec())
956           << SourceRange(getStorageClassSpecLoc());
957       // Discard the thread storage class specifier to recover.
958       ThreadStorageClassSpec = TSCS_unspecified;
959       ThreadStorageClassSpecLoc = SourceLocation();
960     }
961   }
962 
963   // If no type specifier was provided and we're parsing a language where
964   // the type specifier is not optional, but we got 'auto' as a storage
965   // class specifier, then assume this is an attempt to use C++0x's 'auto'
966   // type specifier.
967   // FIXME: Does Microsoft really support implicit int in C++?
968   if (PP.getLangOpts().CPlusPlus && !PP.getLangOpts().MicrosoftExt &&
969       TypeSpecType == TST_unspecified && StorageClassSpec == SCS_auto) {
970     TypeSpecType = TST_auto;
971     StorageClassSpec = SCS_unspecified;
972     TSTLoc = TSTNameLoc = StorageClassSpecLoc;
973     StorageClassSpecLoc = SourceLocation();
974   }
975   // Diagnose if we've recovered from an ill-formed 'auto' storage class
976   // specifier in a pre-C++0x dialect of C++.
977   if (!PP.getLangOpts().CPlusPlus11 && TypeSpecType == TST_auto)
978     Diag(D, TSTLoc, diag::ext_auto_type_specifier);
979   if (PP.getLangOpts().CPlusPlus && !PP.getLangOpts().CPlusPlus11 &&
980       StorageClassSpec == SCS_auto)
981     Diag(D, StorageClassSpecLoc, diag::warn_auto_storage_class)
982       << FixItHint::CreateRemoval(StorageClassSpecLoc);
983   if (TypeSpecType == TST_char16 || TypeSpecType == TST_char32)
984     Diag(D, TSTLoc, diag::warn_cxx98_compat_unicode_type)
985       << (TypeSpecType == TST_char16 ? "char16_t" : "char32_t");
986   if (Constexpr_specified)
987     Diag(D, ConstexprLoc, diag::warn_cxx98_compat_constexpr);
988 
989   // C++ [class.friend]p6:
990   //   No storage-class-specifier shall appear in the decl-specifier-seq
991   //   of a friend declaration.
992   if (isFriendSpecified() &&
993       (getStorageClassSpec() || getThreadStorageClassSpec())) {
994     SmallString<32> SpecName;
995     SourceLocation SCLoc;
996     FixItHint StorageHint, ThreadHint;
997 
998     if (DeclSpec::SCS SC = getStorageClassSpec()) {
999       SpecName = getSpecifierName(SC);
1000       SCLoc = getStorageClassSpecLoc();
1001       StorageHint = FixItHint::CreateRemoval(SCLoc);
1002     }
1003 
1004     if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) {
1005       if (!SpecName.empty()) SpecName += " ";
1006       SpecName += getSpecifierName(TSC);
1007       SCLoc = getThreadStorageClassSpecLoc();
1008       ThreadHint = FixItHint::CreateRemoval(SCLoc);
1009     }
1010 
1011     Diag(D, SCLoc, diag::err_friend_storage_spec)
1012       << SpecName << StorageHint << ThreadHint;
1013 
1014     ClearStorageClassSpecs();
1015   }
1016 
1017   assert(!TypeSpecOwned || isDeclRep((TST) TypeSpecType));
1018 
1019   // Okay, now we can infer the real type.
1020 
1021   // TODO: return "auto function" and other bad things based on the real type.
1022 
1023   // 'data definition has no type or storage class'?
1024 }
1025 
1026 bool DeclSpec::isMissingDeclaratorOk() {
1027   TST tst = getTypeSpecType();
1028   return isDeclRep(tst) && getRepAsDecl() != 0 &&
1029     StorageClassSpec != DeclSpec::SCS_typedef;
1030 }
1031 
1032 void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
1033                                           OverloadedOperatorKind Op,
1034                                           SourceLocation SymbolLocations[3]) {
1035   Kind = IK_OperatorFunctionId;
1036   StartLocation = OperatorLoc;
1037   EndLocation = OperatorLoc;
1038   OperatorFunctionId.Operator = Op;
1039   for (unsigned I = 0; I != 3; ++I) {
1040     OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding();
1041 
1042     if (SymbolLocations[I].isValid())
1043       EndLocation = SymbolLocations[I];
1044   }
1045 }
1046 
1047 bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
1048                                   const char *&PrevSpec) {
1049   LastLocation = Loc;
1050 
1051   if (Specifiers & VS) {
1052     PrevSpec = getSpecifierName(VS);
1053     return true;
1054   }
1055 
1056   Specifiers |= VS;
1057 
1058   switch (VS) {
1059   default: llvm_unreachable("Unknown specifier!");
1060   case VS_Override: VS_overrideLoc = Loc; break;
1061   case VS_Final:    VS_finalLoc = Loc; break;
1062   }
1063 
1064   return false;
1065 }
1066 
1067 const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
1068   switch (VS) {
1069   default: llvm_unreachable("Unknown specifier");
1070   case VS_Override: return "override";
1071   case VS_Final: return "final";
1072   }
1073 }
1074