SemaDeclCXX.cpp revision de933f025e839bde4b119f3437c320c2137bbe1f
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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 C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Parse/DeclSpec.h"
21#include "llvm/Support/Compiler.h"
22
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// CheckDefaultArgumentVisitor
27//===----------------------------------------------------------------------===//
28
29namespace {
30  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
31  /// the default argument of a parameter to determine whether it
32  /// contains any ill-formed subexpressions. For example, this will
33  /// diagnose the use of local variables or parameters within the
34  /// default argument expression.
35  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
36    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
37    Expr *DefaultArg;
38    Sema *S;
39
40  public:
41    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
42      : DefaultArg(defarg), S(s) {}
43
44    bool VisitExpr(Expr *Node);
45    bool VisitDeclRefExpr(DeclRefExpr *DRE);
46  };
47
48  /// VisitExpr - Visit all of the children of this expression.
49  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
50    bool IsInvalid = false;
51    for (Stmt::child_iterator I = Node->child_begin(),
52         E = Node->child_end(); I != E; ++I)
53      IsInvalid |= Visit(*I);
54    return IsInvalid;
55  }
56
57  /// VisitDeclRefExpr - Visit a reference to a declaration, to
58  /// determine whether this declaration can be used in the default
59  /// argument expression.
60  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
61    ValueDecl *Decl = DRE->getDecl();
62    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
63      // C++ [dcl.fct.default]p9
64      //   Default arguments are evaluated each time the function is
65      //   called. The order of evaluation of function arguments is
66      //   unspecified. Consequently, parameters of a function shall not
67      //   be used in default argument expressions, even if they are not
68      //   evaluated. Parameters of a function declared before a default
69      //   argument expression are in scope and can hide namespace and
70      //   class member names.
71      return S->Diag(DRE->getSourceRange().getBegin(),
72                     diag::err_param_default_argument_references_param,
73                     Param->getName(), DefaultArg->getSourceRange());
74    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
75      // C++ [dcl.fct.default]p7
76      //   Local variables shall not be used in default argument
77      //   expressions.
78      if (VDecl->isBlockVarDecl())
79        return S->Diag(DRE->getSourceRange().getBegin(),
80                       diag::err_param_default_argument_references_local,
81                       VDecl->getName(), DefaultArg->getSourceRange());
82    }
83
84    // FIXME: when Clang has support for member functions, "this"
85    // will also need to be diagnosed.
86
87    return false;
88  }
89}
90
91/// ActOnParamDefaultArgument - Check whether the default argument
92/// provided for a function parameter is well-formed. If so, attach it
93/// to the parameter declaration.
94void
95Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
96                                ExprTy *defarg) {
97  ParmVarDecl *Param = (ParmVarDecl *)param;
98  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
99  QualType ParamType = Param->getType();
100
101  // Default arguments are only permitted in C++
102  if (!getLangOptions().CPlusPlus) {
103    Diag(EqualLoc, diag::err_param_default_argument,
104         DefaultArg->getSourceRange());
105    return;
106  }
107
108  // C++ [dcl.fct.default]p5
109  //   A default argument expression is implicitly converted (clause
110  //   4) to the parameter type. The default argument expression has
111  //   the same semantic constraints as the initializer expression in
112  //   a declaration of a variable of the parameter type, using the
113  //   copy-initialization semantics (8.5).
114  //
115  // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
116  // for C++ (since we want copy-initialization, not copy-assignment),
117  // but we don't have the right semantics implemented yet. Because of
118  // this, our error message is also very poor.
119  QualType DefaultArgType = DefaultArg->getType();
120  Expr *DefaultArgPtr = DefaultArg.get();
121  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
122                                                              DefaultArgPtr);
123  if (DefaultArgPtr != DefaultArg.get()) {
124    DefaultArg.take();
125    DefaultArg.reset(DefaultArgPtr);
126  }
127  if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
128                               ParamType, DefaultArgType, DefaultArg.get(),
129                               "in default argument")) {
130    return;
131  }
132
133  // Check that the default argument is well-formed
134  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
135  if (DefaultArgChecker.Visit(DefaultArg.get()))
136    return;
137
138  // Okay: add the default argument to the parameter
139  Param->setDefaultArg(DefaultArg.take());
140}
141
142/// CheckExtraCXXDefaultArguments - Check for any extra default
143/// arguments in the declarator, which is not a function declaration
144/// or definition and therefore is not permitted to have default
145/// arguments. This routine should be invoked for every declarator
146/// that is not a function declaration or definition.
147void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
148  // C++ [dcl.fct.default]p3
149  //   A default argument expression shall be specified only in the
150  //   parameter-declaration-clause of a function declaration or in a
151  //   template-parameter (14.1). It shall not be specified for a
152  //   parameter pack. If it is specified in a
153  //   parameter-declaration-clause, it shall not occur within a
154  //   declarator or abstract-declarator of a parameter-declaration.
155  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
156    DeclaratorChunk &chunk = D.getTypeObject(i);
157    if (chunk.Kind == DeclaratorChunk::Function) {
158      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
159        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
160        if (Param->getDefaultArg()) {
161          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
162               Param->getDefaultArg()->getSourceRange());
163          Param->setDefaultArg(0);
164        }
165      }
166    }
167  }
168}
169
170// MergeCXXFunctionDecl - Merge two declarations of the same C++
171// function, once we already know that they have the same
172// type. Subroutine of MergeFunctionDecl.
173FunctionDecl *
174Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
175  // C++ [dcl.fct.default]p4:
176  //
177  //   For non-template functions, default arguments can be added in
178  //   later declarations of a function in the same
179  //   scope. Declarations in different scopes have completely
180  //   distinct sets of default arguments. That is, declarations in
181  //   inner scopes do not acquire default arguments from
182  //   declarations in outer scopes, and vice versa. In a given
183  //   function declaration, all parameters subsequent to a
184  //   parameter with a default argument shall have default
185  //   arguments supplied in this or previous declarations. A
186  //   default argument shall not be redefined by a later
187  //   declaration (not even to the same value).
188  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
189    ParmVarDecl *OldParam = Old->getParamDecl(p);
190    ParmVarDecl *NewParam = New->getParamDecl(p);
191
192    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
193      Diag(NewParam->getLocation(),
194           diag::err_param_default_argument_redefinition,
195           NewParam->getDefaultArg()->getSourceRange());
196      Diag(OldParam->getLocation(), diag::err_previous_definition);
197    } else if (OldParam->getDefaultArg()) {
198      // Merge the old default argument into the new parameter
199      NewParam->setDefaultArg(OldParam->getDefaultArg());
200    }
201  }
202
203  return New;
204}
205
206/// CheckCXXDefaultArguments - Verify that the default arguments for a
207/// function declaration are well-formed according to C++
208/// [dcl.fct.default].
209void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
210  unsigned NumParams = FD->getNumParams();
211  unsigned p;
212
213  // Find first parameter with a default argument
214  for (p = 0; p < NumParams; ++p) {
215    ParmVarDecl *Param = FD->getParamDecl(p);
216    if (Param->getDefaultArg())
217      break;
218  }
219
220  // C++ [dcl.fct.default]p4:
221  //   In a given function declaration, all parameters
222  //   subsequent to a parameter with a default argument shall
223  //   have default arguments supplied in this or previous
224  //   declarations. A default argument shall not be redefined
225  //   by a later declaration (not even to the same value).
226  unsigned LastMissingDefaultArg = 0;
227  for(; p < NumParams; ++p) {
228    ParmVarDecl *Param = FD->getParamDecl(p);
229    if (!Param->getDefaultArg()) {
230      if (Param->getIdentifier())
231        Diag(Param->getLocation(),
232             diag::err_param_default_argument_missing_name,
233             Param->getIdentifier()->getName());
234      else
235        Diag(Param->getLocation(),
236             diag::err_param_default_argument_missing);
237
238      LastMissingDefaultArg = p;
239    }
240  }
241
242  if (LastMissingDefaultArg > 0) {
243    // Some default arguments were missing. Clear out all of the
244    // default arguments up to (and including) the last missing
245    // default argument, so that we leave the function parameters
246    // in a semantically valid state.
247    for (p = 0; p <= LastMissingDefaultArg; ++p) {
248      ParmVarDecl *Param = FD->getParamDecl(p);
249      if (Param->getDefaultArg()) {
250        delete Param->getDefaultArg();
251        Param->setDefaultArg(0);
252      }
253    }
254  }
255}
256
257/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
258/// one entry in the base class list of a class specifier, for
259/// example:
260///    class foo : public bar, virtual private baz {
261/// 'public bar' and 'virtual private baz' are each base-specifiers.
262void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
263                              bool Virtual, AccessSpecifier Access,
264                              TypeTy *basetype, SourceLocation BaseLoc) {
265  RecordDecl *Decl = (RecordDecl*)classdecl;
266  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
267
268  // Base specifiers must be record types.
269  if (!BaseType->isRecordType()) {
270    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
271    return;
272  }
273
274  // C++ [class.union]p1:
275  //   A union shall not be used as a base class.
276  if (BaseType->isUnionType()) {
277    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
278    return;
279  }
280
281  // C++ [class.union]p1:
282  //   A union shall not have base classes.
283  if (Decl->isUnion()) {
284    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
285         SpecifierRange);
286    Decl->setInvalidDecl();
287    return;
288  }
289
290  // C++ [class.derived]p2:
291  //   The class-name in a base-specifier shall not be an incompletely
292  //   defined class.
293  if (BaseType->isIncompleteType()) {
294    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
295    return;
296  }
297
298  // FIXME: C++ [class.mi]p3:
299  //   A class shall not be specified as a direct base class of a
300  //   derived class more than once.
301
302  // FIXME: Attach base class to the record.
303}
304
305//===----------------------------------------------------------------------===//
306// C++ class member Handling
307//===----------------------------------------------------------------------===//
308
309/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
310/// definition, when on C++.
311void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
312  Decl *Dcl = static_cast<Decl *>(D);
313  PushDeclContext(cast<CXXRecordDecl>(Dcl));
314  FieldCollector->StartClass();
315}
316
317/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
318/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
319/// bitfield width if there is one and 'InitExpr' specifies the initializer if
320/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
321/// declarators on it.
322///
323/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
324/// an instance field is declared, a new CXXFieldDecl is created but the method
325/// does *not* return it; it returns LastInGroup instead. The other C++ members
326/// (which are all ScopedDecls) are returned after appending them to
327/// LastInGroup.
328Sema::DeclTy *
329Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
330                               ExprTy *BW, ExprTy *InitExpr,
331                               DeclTy *LastInGroup) {
332  const DeclSpec &DS = D.getDeclSpec();
333  IdentifierInfo *II = D.getIdentifier();
334  Expr *BitWidth = static_cast<Expr*>(BW);
335  Expr *Init = static_cast<Expr*>(InitExpr);
336  SourceLocation Loc = D.getIdentifierLoc();
337
338  // C++ 9.2p6: A member shall not be declared to have automatic storage
339  // duration (auto, register) or with the extern storage-class-specifier.
340  switch (DS.getStorageClassSpec()) {
341    case DeclSpec::SCS_unspecified:
342    case DeclSpec::SCS_typedef:
343    case DeclSpec::SCS_static:
344      // FALL THROUGH.
345      break;
346    default:
347      if (DS.getStorageClassSpecLoc().isValid())
348        Diag(DS.getStorageClassSpecLoc(),
349             diag::err_storageclass_invalid_for_member);
350      else
351        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
352      D.getMutableDeclSpec().ClearStorageClassSpecs();
353  }
354
355  bool isFunc = D.isFunctionDeclarator();
356  if (!isFunc && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef) {
357    // Check also for this case:
358    //
359    // typedef int f();
360    // f a;
361    //
362    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
363    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
364  }
365
366  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
367                      !isFunc);
368
369  Decl *Member;
370  bool InvalidDecl = false;
371
372  if (isInstField)
373    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
374  else
375    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
376
377  if (!Member) return LastInGroup;
378
379  assert(II || isInstField && "No identifier for non-field ?");
380
381  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
382  // specific methods. Use a wrapper class that can be used with all C++ class
383  // member decls.
384  CXXClassMemberWrapper(Member).setAccess(AS);
385
386  if (BitWidth) {
387    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
388    // constant-expression be a value equal to zero.
389    // FIXME: Check this.
390
391    if (D.isFunctionDeclarator()) {
392      // FIXME: Emit diagnostic about only constructors taking base initializers
393      // or something similar, when constructor support is in place.
394      Diag(Loc, diag::err_not_bitfield_type,
395           II->getName(), BitWidth->getSourceRange());
396      InvalidDecl = true;
397
398    } else if (isInstField) {
399      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
400      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
401        Diag(Loc, diag::err_not_integral_type_bitfield,
402             II->getName(), BitWidth->getSourceRange());
403        InvalidDecl = true;
404      }
405
406    } else if (isa<FunctionDecl>(Member)) {
407      // A function typedef ("typedef int f(); f a;").
408      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
409      Diag(Loc, diag::err_not_integral_type_bitfield,
410           II->getName(), BitWidth->getSourceRange());
411      InvalidDecl = true;
412
413    } else if (isa<TypedefDecl>(Member)) {
414      // "cannot declare 'A' to be a bit-field type"
415      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
416           BitWidth->getSourceRange());
417      InvalidDecl = true;
418
419    } else {
420      assert(isa<CXXClassVarDecl>(Member) &&
421             "Didn't we cover all member kinds?");
422      // C++ 9.6p3: A bit-field shall not be a static member.
423      // "static member 'A' cannot be a bit-field"
424      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
425           BitWidth->getSourceRange());
426      InvalidDecl = true;
427    }
428  }
429
430  if (Init) {
431    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
432    // if it declares a static member of const integral or const enumeration
433    // type.
434    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
435      // ...static member of...
436      CVD->setInit(Init);
437      // ...const integral or const enumeration type.
438      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
439          CVD->getType()->isIntegralType()) {
440        // constant-initializer
441        if (CheckForConstantInitializer(Init, CVD->getType()))
442          InvalidDecl = true;
443
444      } else {
445        // not const integral.
446        Diag(Loc, diag::err_member_initialization,
447             II->getName(), Init->getSourceRange());
448        InvalidDecl = true;
449      }
450
451    } else {
452      // not static member.
453      Diag(Loc, diag::err_member_initialization,
454           II->getName(), Init->getSourceRange());
455      InvalidDecl = true;
456    }
457  }
458
459  if (InvalidDecl)
460    Member->setInvalidDecl();
461
462  if (isInstField) {
463    FieldCollector->Add(cast<CXXFieldDecl>(Member));
464    return LastInGroup;
465  }
466  return Member;
467}
468
469void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
470                                             DeclTy *TagDecl,
471                                             SourceLocation LBrac,
472                                             SourceLocation RBrac) {
473  ActOnFields(S, RLoc, TagDecl,
474              (DeclTy**)FieldCollector->getCurFields(),
475              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
476}
477
478void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
479  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
480  FieldCollector->FinishClass();
481  PopDeclContext();
482
483  // Everything, including inline method definitions, have been parsed.
484  // Let the consumer know of the new TagDecl definition.
485  Consumer.HandleTagDeclDefinition(Rec);
486}
487
488//===----------------------------------------------------------------------===//
489// Namespace Handling
490//===----------------------------------------------------------------------===//
491
492/// ActOnStartNamespaceDef - This is called at the start of a namespace
493/// definition.
494Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
495                                           SourceLocation IdentLoc,
496                                           IdentifierInfo *II,
497                                           SourceLocation LBrace) {
498  NamespaceDecl *Namespc =
499      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
500  Namespc->setLBracLoc(LBrace);
501
502  Scope *DeclRegionScope = NamespcScope->getParent();
503
504  if (II) {
505    // C++ [namespace.def]p2:
506    // The identifier in an original-namespace-definition shall not have been
507    // previously defined in the declarative region in which the
508    // original-namespace-definition appears. The identifier in an
509    // original-namespace-definition is the name of the namespace. Subsequently
510    // in that declarative region, it is treated as an original-namespace-name.
511
512    Decl *PrevDecl =
513        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
514                   /*enableLazyBuiltinCreation=*/false);
515
516    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
517      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
518        // This is an extended namespace definition.
519        // Attach this namespace decl to the chain of extended namespace
520        // definitions.
521        NamespaceDecl *NextNS = OrigNS;
522        while (NextNS->getNextNamespace())
523          NextNS = NextNS->getNextNamespace();
524
525        NextNS->setNextNamespace(Namespc);
526        Namespc->setOriginalNamespace(OrigNS);
527
528        // We won't add this decl to the current scope. We want the namespace
529        // name to return the original namespace decl during a name lookup.
530      } else {
531        // This is an invalid name redefinition.
532        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
533          Namespc->getName());
534        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
535        Namespc->setInvalidDecl();
536        // Continue on to push Namespc as current DeclContext and return it.
537      }
538    } else {
539      // This namespace name is declared for the first time.
540      PushOnScopeChains(Namespc, DeclRegionScope);
541    }
542  }
543  else {
544    // FIXME: Handle anonymous namespaces
545  }
546
547  // Although we could have an invalid decl (i.e. the namespace name is a
548  // redefinition), push it as current DeclContext and try to continue parsing.
549  PushDeclContext(Namespc->getOriginalNamespace());
550  return Namespc;
551}
552
553/// ActOnFinishNamespaceDef - This callback is called after a namespace is
554/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
555void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
556  Decl *Dcl = static_cast<Decl *>(D);
557  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
558  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
559  Namespc->setRBracLoc(RBrace);
560  PopDeclContext();
561}
562
563
564/// AddCXXDirectInitializerToDecl - This action is called immediately after
565/// ActOnDeclarator, when a C++ direct initializer is present.
566/// e.g: "int x(1);"
567void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
568                                         ExprTy **ExprTys, unsigned NumExprs,
569                                         SourceLocation *CommaLocs,
570                                         SourceLocation RParenLoc) {
571  assert(NumExprs != 0 && ExprTys && "missing expressions");
572  Decl *RealDecl = static_cast<Decl *>(Dcl);
573
574  // If there is no declaration, there was an error parsing it.  Just ignore
575  // the initializer.
576  if (RealDecl == 0) {
577    for (unsigned i = 0; i != NumExprs; ++i)
578      delete static_cast<Expr *>(ExprTys[i]);
579    return;
580  }
581
582  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
583  if (!VDecl) {
584    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
585    RealDecl->setInvalidDecl();
586    return;
587  }
588
589  // We will treat direct-initialization as a copy-initialization:
590  //    int x(1);  -as-> int x = 1;
591  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
592  //
593  // Clients that want to distinguish between the two forms, can check for
594  // direct initializer using VarDecl::hasCXXDirectInitializer().
595  // A major benefit is that clients that don't particularly care about which
596  // exactly form was it (like the CodeGen) can handle both cases without
597  // special case code.
598
599  // C++ 8.5p11:
600  // The form of initialization (using parentheses or '=') is generally
601  // insignificant, but does matter when the entity being initialized has a
602  // class type.
603
604  if (VDecl->getType()->isRecordType()) {
605    // FIXME: When constructors for class types are supported, determine how
606    // exactly semantic checking will be done for direct initializers.
607    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
608                           "initialization for class types is not handled yet");
609    Diag(VDecl->getLocation(), DiagID);
610    RealDecl->setInvalidDecl();
611    return;
612  }
613
614  if (NumExprs > 1) {
615    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
616         SourceRange(VDecl->getLocation(), RParenLoc));
617    RealDecl->setInvalidDecl();
618    return;
619  }
620
621  // Let clients know that initialization was done with a direct initializer.
622  VDecl->setCXXDirectInitializer(true);
623
624  assert(NumExprs == 1 && "Expected 1 expression");
625  // Set the init expression, handles conversions.
626  AddInitializerToDecl(Dcl, ExprTys[0]);
627}
628