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