 |
|
 |
|
| Files: |
1 |
|
Branches Taken: |
82.3% |
1638 / 1990 |
| Generated: |
2010-02-10 01:31 |
|
Branches Executed: |
97.0% |
1930 / 1990 |
| |
|
Line Coverage: |
92.7% |
2107 / 2273 |
| |
 |
|
 |
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 "SemaInit.h"
16 : #include "Lookup.h"
17 : #include "clang/AST/ASTConsumer.h"
18 : #include "clang/AST/ASTContext.h"
19 : #include "clang/AST/RecordLayout.h"
20 : #include "clang/AST/CXXInheritance.h"
21 : #include "clang/AST/DeclVisitor.h"
22 : #include "clang/AST/TypeLoc.h"
23 : #include "clang/AST/TypeOrdering.h"
24 : #include "clang/AST/StmtVisitor.h"
25 : #include "clang/Parse/DeclSpec.h"
26 : #include "clang/Parse/Template.h"
27 : #include "clang/Basic/PartialDiagnostic.h"
28 : #include "clang/Lex/Preprocessor.h"
29 : #include "llvm/ADT/STLExtras.h"
30 : #include <map>
31 : #include <set>
32 :
33 : using namespace clang;
34 :
35 : //===----------------------------------------------------------------------===//
36 : // CheckDefaultArgumentVisitor
37 : //===----------------------------------------------------------------------===//
38 :
39 : namespace {
40 : /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 : /// the default argument of a parameter to determine whether it
42 : /// contains any ill-formed subexpressions. For example, this will
43 : /// diagnose the use of local variables or parameters within the
44 : /// default argument expression.
45 : class CheckDefaultArgumentVisitor
46 : : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
47 : Expr *DefaultArg;
48 : Sema *S;
49 :
50 : public:
51 161: CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
52 161: : DefaultArg(defarg), S(s) {}
53 :
54 : bool VisitExpr(Expr *Node);
55 : bool VisitDeclRefExpr(DeclRefExpr *DRE);
56 : bool VisitCXXThisExpr(CXXThisExpr *ThisE);
57 : };
58 :
59 : /// VisitExpr - Visit all of the children of this expression.
60 164: bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 164: bool IsInvalid = false;
31: branch 3 taken
164: branch 4 taken
62 359: for (Stmt::child_iterator I = Node->child_begin(),
63 164: E = Node->child_end(); I != E; ++I)
64 31: IsInvalid |= Visit(*I);
65 164: return IsInvalid;
66 : }
67 :
68 : /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 : /// determine whether this declaration can be used in the default
70 : /// argument expression.
71 27: bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
72 27: NamedDecl *Decl = DRE->getDecl();
5: branch 1 taken
22: branch 2 taken
73 27: if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 : // C++ [dcl.fct.default]p9
75 : // Default arguments are evaluated each time the function is
76 : // called. The order of evaluation of function arguments is
77 : // unspecified. Consequently, parameters of a function shall not
78 : // be used in default argument expressions, even if they are not
79 : // evaluated. Parameters of a function declared before a default
80 : // argument expression are in scope and can hide namespace and
81 : // class member names.
82 : return S->Diag(DRE->getSourceRange().getBegin(),
83 : diag::err_param_default_argument_references_param)
84 5: << Param->getDeclName() << DefaultArg->getSourceRange();
16: branch 1 taken
6: branch 2 taken
85 22: } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
86 : // C++ [dcl.fct.default]p7
87 : // Local variables shall not be used in default argument
88 : // expressions.
1: branch 1 taken
15: branch 2 taken
89 16: if (VDecl->isBlockVarDecl())
90 : return S->Diag(DRE->getSourceRange().getBegin(),
91 : diag::err_param_default_argument_references_local)
92 1: << VDecl->getDeclName() << DefaultArg->getSourceRange();
93 : }
94 :
95 21: return false;
96 : }
97 :
98 : /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 1: bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 : // C++ [dcl.fct.default]p8:
101 : // The keyword this shall not be used in a default argument of a
102 : // member function.
103 : return S->Diag(ThisE->getSourceRange().getBegin(),
104 : diag::err_param_default_argument_references_this)
105 1: << ThisE->getSourceRange();
106 : }
107 : }
108 :
109 : bool
110 : Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
111 155: SourceLocation EqualLoc) {
0: branch 10 not taken
155: branch 11 taken
112 155: if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 : diag::err_typecheck_decl_incomplete_type)) {
114 0: Param->setInvalidDecl();
115 0: return true;
116 : }
117 :
118 155: Expr *Arg = (Expr *)DefaultArg.get();
119 :
120 : // C++ [dcl.fct.default]p5
121 : // A default argument expression is implicitly converted (clause
122 : // 4) to the parameter type. The default argument expression has
123 : // the same semantic constraints as the initializer expression in
124 : // a declaration of a variable of the parameter type, using the
125 : // copy-initialization semantics (8.5).
126 155: InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 : InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 155: EqualLoc);
129 155: InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 : OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 155: MultiExprArg(*this, (void**)&Arg, 1));
5: branch 1 taken
150: branch 2 taken
132 155: if (Result.isInvalid())
133 5: return true;
134 150: Arg = Result.takeAs<Expr>();
135 :
136 150: Arg = MaybeCreateCXXExprWithTemporaries(Arg);
137 :
138 : // Okay: add the default argument to the parameter
139 150: Param->setDefaultArg(Arg);
140 :
141 150: DefaultArg.release();
142 :
143 150: return false;
144 : }
145 :
146 : /// ActOnParamDefaultArgument - Check whether the default argument
147 : /// provided for a function parameter is well-formed. If so, attach it
148 : /// to the parameter declaration.
149 : void
150 : Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
151 162: ExprArg defarg) {
162: branch 1 taken
0: branch 2 not taken
0: branch 4 not taken
162: branch 5 taken
0: branch 6 not taken
162: branch 7 taken
152 162: if (!param || !defarg.get())
153 0: return;
154 :
155 162: ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
156 162: UnparsedDefaultArgLocs.erase(Param);
157 :
158 162: ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
159 :
160 : // Default arguments are only permitted in C++
1: branch 1 taken
161: branch 2 taken
161 162: if (!getLangOptions().CPlusPlus) {
162 : Diag(EqualLoc, diag::err_param_default_argument)
163 1: << DefaultArg->getSourceRange();
164 1: Param->setInvalidDecl();
165 7: return;
166 : }
167 :
168 : // Check that the default argument is well-formed
169 161: CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
6: branch 2 taken
155: branch 3 taken
170 161: if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 6: Param->setInvalidDecl();
172 : return;
173 : }
174 :
155: branch 7 taken
7: branch 8 taken
175 155: SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
176 : }
177 :
178 : /// ActOnParamUnparsedDefaultArgument - We've seen a default
179 : /// argument for a function parameter, but we can't parse it yet
180 : /// because we're inside a class definition. Note that this default
181 : /// argument will be parsed later.
182 : void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
183 : SourceLocation EqualLoc,
184 82: SourceLocation ArgLoc) {
0: branch 1 not taken
82: branch 2 taken
185 82: if (!param)
186 0: return;
187 :
188 82: ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
82: branch 0 taken
0: branch 1 not taken
189 82: if (Param)
190 82: Param->setUnparsedDefaultArg();
191 :
192 82: UnparsedDefaultArgLocs[Param] = ArgLoc;
193 : }
194 :
195 : /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196 : /// the default argument for the parameter param failed.
197 6: void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
0: branch 1 not taken
6: branch 2 taken
198 6: if (!param)
199 0: return;
200 :
201 6: ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
202 :
203 6: Param->setInvalidDecl();
204 :
205 6: UnparsedDefaultArgLocs.erase(Param);
206 : }
207 :
208 : /// CheckExtraCXXDefaultArguments - Check for any extra default
209 : /// arguments in the declarator, which is not a function declaration
210 : /// or definition and therefore is not permitted to have default
211 : /// arguments. This routine should be invoked for every declarator
212 : /// that is not a function declaration or definition.
213 18262: void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 : // C++ [dcl.fct.default]p3
215 : // A default argument expression shall be specified only in the
216 : // parameter-declaration-clause of a function declaration or in a
217 : // template-parameter (14.1). It shall not be specified for a
218 : // parameter pack. If it is specified in a
219 : // parameter-declaration-clause, it shall not occur within a
220 : // declarator or abstract-declarator of a parameter-declaration.
7523: branch 1 taken
18262: branch 2 taken
221 25785: for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
222 7523: DeclaratorChunk &chunk = D.getTypeObject(i);
437: branch 0 taken
7086: branch 1 taken
223 7523: if (chunk.Kind == DeclaratorChunk::Function) {
316: branch 0 taken
437: branch 1 taken
224 753: for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 : ParmVarDecl *Param =
226 316: cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
1: branch 1 taken
315: branch 2 taken
227 316: if (Param->hasUnparsedDefaultArg()) {
228 1: CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
229 : Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 1: << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
1: branch 0 taken
0: branch 1 not taken
231 1: delete Toks;
232 1: chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
4: branch 1 taken
311: branch 2 taken
233 315: } else if (Param->getDefaultArg()) {
234 : Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 4: << Param->getDefaultArg()->getSourceRange();
236 4: Param->setDefaultArg(0);
237 : }
238 : }
239 : }
240 : }
241 18262: }
242 :
243 : // MergeCXXFunctionDecl - Merge two declarations of the same C++
244 : // function, once we already know that they have the same
245 : // type. Subroutine of MergeFunctionDecl. Returns true if there was an
246 : // error, false otherwise.
247 474: bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 474: bool Invalid = false;
249 :
250 : // C++ [dcl.fct.default]p4:
251 : // For non-template functions, default arguments can be added in
252 : // later declarations of a function in the same
253 : // scope. Declarations in different scopes have completely
254 : // distinct sets of default arguments. That is, declarations in
255 : // inner scopes do not acquire default arguments from
256 : // declarations in outer scopes, and vice versa. In a given
257 : // function declaration, all parameters subsequent to a
258 : // parameter with a default argument shall have default
259 : // arguments supplied in this or previous declarations. A
260 : // default argument shall not be redefined by a later
261 : // declaration (not even to the same value).
262 : //
263 : // C++ [dcl.fct.default]p6:
264 : // Except for member functions of class templates, the default arguments
265 : // in a member function definition that appears outside of the class
266 : // definition are added to the set of default arguments provided by the
267 : // member function declaration in the class definition.
335: branch 1 taken
474: branch 2 taken
268 809: for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 335: ParmVarDecl *OldParam = Old->getParamDecl(p);
270 335: ParmVarDecl *NewParam = New->getParamDecl(p);
271 :
35: branch 1 taken
300: branch 2 taken
5: branch 4 taken
30: branch 5 taken
5: branch 6 taken
330: branch 7 taken
272 335: if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
273 : // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 : // hint here. Alternatively, we could walk the type-source information
275 : // for NewParam to find the last source location in the type... but it
276 : // isn't worth the effort right now. This is the kind of test case that
277 : // is hard to get right:
278 :
279 : // int f(int);
280 : // void g(int (*fp)(int) = f);
281 : // void g(int (*fp)(int) = &f);
282 : Diag(NewParam->getLocation(),
283 : diag::err_param_default_argument_redefinition)
284 5: << NewParam->getDefaultArgRange();
285 :
286 : // Look for the function declaration where the default argument was
287 : // actually written, which may be a declaration prior to Old.
4: branch 2 taken
2: branch 3 taken
288 6: for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 : Older; Older = Older->getPreviousDeclaration()) {
3: branch 2 taken
1: branch 3 taken
290 4: if (!Older->getParamDecl(p)->hasDefaultArg())
291 3: break;
292 :
293 1: OldParam = Older->getParamDecl(p);
294 : }
295 :
296 : Diag(OldParam->getLocation(), diag::note_previous_definition)
297 5: << OldParam->getDefaultArgRange();
298 5: Invalid = true;
30: branch 1 taken
300: branch 2 taken
299 330: } else if (OldParam->hasDefaultArg()) {
300 : // Merge the old default argument into the new parameter
2: branch 1 taken
28: branch 2 taken
301 30: if (OldParam->hasUninstantiatedDefaultArg())
302 : NewParam->setUninstantiatedDefaultArg(
303 2: OldParam->getUninstantiatedDefaultArg());
304 : else
305 28: NewParam->setDefaultArg(OldParam->getDefaultArg());
23: branch 1 taken
277: branch 2 taken
306 300: } else if (NewParam->hasDefaultArg()) {
2: branch 1 taken
21: branch 2 taken
307 23: if (New->getDescribedFunctionTemplate()) {
308 : // Paragraph 4, quoted above, only applies to non-template functions.
309 : Diag(NewParam->getLocation(),
310 : diag::err_param_default_argument_template_redecl)
311 2: << NewParam->getDefaultArgRange();
312 : Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 2: << false;
21: branch 1 taken
0: branch 2 not taken
2: branch 4 taken
19: branch 5 taken
2: branch 6 taken
19: branch 7 taken
314 21: } else if (New->getTemplateSpecializationKind()
315 : != TSK_ImplicitInstantiation &&
316 : New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 : // C++ [temp.expr.spec]p21:
318 : // Default function arguments shall not be specified in a declaration
319 : // or a definition for one of the following explicit specializations:
320 : // - the explicit specialization of a function template;
321 : // - the explicit specialization of a member function template;
322 : // - the explicit specialization of a member function of a class
323 : // template where the class template specialization to which the
324 : // member function specialization belongs is implicitly
325 : // instantiated.
326 : Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 : << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 : << New->getDeclName()
329 2: << NewParam->getDefaultArgRange();
2: branch 2 taken
17: branch 3 taken
330 19: } else if (New->getDeclContext()->isDependentContext()) {
331 : // C++ [dcl.fct.default]p6 (DR217):
332 : // Default arguments for a member function of a class template shall
333 : // be specified on the initial declaration of the member function
334 : // within the class template.
335 : //
336 : // Reading the tea leaves a bit in DR217 and its reference to DR205
337 : // leads me to the conclusion that one cannot add default function
338 : // arguments for an out-of-line definition of a member function of a
339 : // dependent type.
340 2: int WhichKind = 2;
2: branch 0 taken
0: branch 1 not taken
341 2: if (CXXRecordDecl *Record
342 2: = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
1: branch 1 taken
1: branch 2 taken
343 2: if (Record->getDescribedClassTemplate())
344 1: WhichKind = 0;
0: branch 1 not taken
1: branch 2 taken
345 1: else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 0: WhichKind = 1;
347 : else
348 1: WhichKind = 2;
349 : }
350 :
351 : Diag(NewParam->getLocation(),
352 : diag::err_param_default_argument_member_template_redecl)
353 : << WhichKind
354 2: << NewParam->getDefaultArgRange();
355 : }
356 : }
357 : }
358 :
4: branch 9 taken
470: branch 10 taken
359 474: if (CheckEquivalentExceptionSpec(
360 : Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
361 : New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
362 4: Invalid = true;
363 :
364 474: return Invalid;
365 : }
366 :
367 : /// CheckCXXDefaultArguments - Verify that the default arguments for a
368 : /// function declaration are well-formed according to C++
369 : /// [dcl.fct.default].
370 4116: void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 4116: unsigned NumParams = FD->getNumParams();
372 : unsigned p;
373 :
374 : // Find first parameter with a default argument
4074: branch 0 taken
3968: branch 1 taken
375 8042: for (p = 0; p < NumParams; ++p) {
376 4074: ParmVarDecl *Param = FD->getParamDecl(p);
148: branch 1 taken
3926: branch 2 taken
377 4074: if (Param->hasDefaultArg())
378 148: break;
379 : }
380 :
381 : // C++ [dcl.fct.default]p4:
382 : // In a given function declaration, all parameters
383 : // subsequent to a parameter with a default argument shall
384 : // have default arguments supplied in this or previous
385 : // declarations. A default argument shall not be redefined
386 : // by a later declaration (not even to the same value).
387 4116: unsigned LastMissingDefaultArg = 0;
190: branch 0 taken
4116: branch 1 taken
388 4306: for (; p < NumParams; ++p) {
389 190: ParmVarDecl *Param = FD->getParamDecl(p);
8: branch 1 taken
182: branch 2 taken
390 190: if (!Param->hasDefaultArg()) {
5: branch 1 taken
3: branch 2 taken
391 8: if (Param->isInvalidDecl())
392 : /* We already complained about this parameter. */;
3: branch 1 taken
2: branch 2 taken
393 5: else if (Param->getIdentifier())
394 : Diag(Param->getLocation(),
395 : diag::err_param_default_argument_missing_name)
396 3: << Param->getIdentifier();
397 : else
398 : Diag(Param->getLocation(),
399 2: diag::err_param_default_argument_missing);
400 :
401 8: LastMissingDefaultArg = p;
402 : }
403 : }
404 :
3: branch 0 taken
4113: branch 1 taken
405 4116: if (LastMissingDefaultArg > 0) {
406 : // Some default arguments were missing. Clear out all of the
407 : // default arguments up to (and including) the last missing
408 : // default argument, so that we leave the function parameters
409 : // in a semantically valid state.
14: branch 0 taken
3: branch 1 taken
410 17: for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 14: ParmVarDecl *Param = FD->getParamDecl(p);
5: branch 1 taken
9: branch 2 taken
412 14: if (Param->hasDefaultArg()) {
5: branch 1 taken
0: branch 2 not taken
413 5: if (!Param->hasUnparsedDefaultArg())
414 5: Param->getDefaultArg()->Destroy(Context);
415 5: Param->setDefaultArg(0);
416 : }
417 : }
418 : }
419 4116: }
420 :
421 : /// isCurrentClassName - Determine whether the identifier II is the
422 : /// name of the class type currently being defined. In the case of
423 : /// nested classes, this will only return true if II is the name of
424 : /// the innermost class.
425 : bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 2225: const CXXScopeSpec *SS) {
2225: branch 1 taken
0: branch 2 not taken
427 2225: assert(getLangOptions().CPlusPlus && "No class names in C!");
428 :
429 : CXXRecordDecl *CurDecl;
942: branch 0 taken
1283: branch 1 taken
341: branch 3 taken
601: branch 4 taken
341: branch 6 taken
0: branch 7 not taken
341: branch 8 taken
1884: branch 9 taken
430 3167: if (SS && SS->isSet() && !SS->isInvalid()) {
431 341: DeclContext *DC = computeDeclContext(*SS, true);
432 341: CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 : } else
434 1884: CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435 :
2137: branch 0 taken
88: branch 1 taken
2115: branch 3 taken
22: branch 4 taken
2115: branch 5 taken
110: branch 6 taken
436 2225: if (CurDecl && CurDecl->getIdentifier())
437 2115: return &II == CurDecl->getIdentifier();
438 : else
439 110: return false;
440 : }
441 :
442 : /// \brief Check the validity of a C++ base class specifier.
443 : ///
444 : /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445 : /// and returns NULL otherwise.
446 : CXXBaseSpecifier *
447 : Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 : SourceRange SpecifierRange,
449 : bool Virtual, AccessSpecifier Access,
450 : QualType BaseType,
451 970: SourceLocation BaseLoc) {
452 : // C++ [class.union]p1:
453 : // A union shall not have base classes.
1: branch 1 taken
969: branch 2 taken
454 970: if (Class->isUnion()) {
455 : Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 1: << SpecifierRange;
457 1: return 0;
458 : }
459 :
74: branch 2 taken
895: branch 3 taken
460 969: if (BaseType->isDependentType())
461 : return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
462 : Class->getTagKind() == RecordDecl::TK_class,
74: branch 2 taken
0: branch 3 not taken
463 74: Access, BaseType);
464 :
465 : // Base specifiers must be record types.
2: branch 2 taken
893: branch 3 taken
466 895: if (!BaseType->isRecordType()) {
467 2: Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 2: return 0;
469 : }
470 :
471 : // C++ [class.union]p1:
472 : // A union shall not be used as a base class.
1: branch 2 taken
892: branch 3 taken
473 893: if (BaseType->isUnionType()) {
474 1: Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 1: return 0;
476 : }
477 :
478 : // C++ [class.derived]p2:
479 : // The class-name in a base-specifier shall not be an incompletely
480 : // defined class.
16: branch 9 taken
876: branch 10 taken
481 892: if (RequireCompleteType(BaseLoc, BaseType,
482 : PDiag(diag::err_incomplete_base_class)
483 : << SpecifierRange))
484 16: return 0;
485 :
486 : // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
487 876: RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
0: branch 0 not taken
876: branch 1 taken
488 876: assert(BaseDecl && "Record type has no declaration");
489 876: BaseDecl = BaseDecl->getDefinition(Context);
0: branch 0 not taken
876: branch 1 taken
490 876: assert(BaseDecl && "Base type is not incomplete, but has no definition");
491 876: CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
0: branch 0 not taken
876: branch 1 taken
492 876: assert(CXXBaseDecl && "Base type is not a C++ type");
493 :
494 : // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
1: branch 1 taken
875: branch 2 taken
495 876: if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 1: Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
497 : Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 1: << BaseType;
499 1: return 0;
500 : }
501 :
502 875: SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
503 :
504 : // Create the base specifier.
505 : // FIXME: Allocate via ASTContext?
506 : return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 : Class->getTagKind() == RecordDecl::TK_class,
875: branch 2 taken
0: branch 3 not taken
508 875: Access, BaseType);
509 : }
510 :
511 : void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 : const CXXRecordDecl *BaseClass,
513 903: bool BaseIsVirtual) {
514 : // A class with a non-empty base class is not empty.
515 : // FIXME: Standard ref?
503: branch 1 taken
400: branch 2 taken
516 903: if (!BaseClass->isEmpty())
517 503: Class->setEmpty(false);
518 :
519 : // C++ [class.virtual]p1:
520 : // A class that [...] inherits a virtual function is called a polymorphic
521 : // class.
297: branch 1 taken
606: branch 2 taken
522 903: if (BaseClass->isPolymorphic())
523 297: Class->setPolymorphic(true);
524 :
525 : // C++ [dcl.init.aggr]p1:
526 : // An aggregate is [...] a class with [...] no base classes [...].
527 903: Class->setAggregate(false);
528 :
529 : // C++ [class]p4:
530 : // A POD-struct is an aggregate class...
531 903: Class->setPOD(false);
532 :
198: branch 0 taken
705: branch 1 taken
533 903: if (BaseIsVirtual) {
534 : // C++ [class.ctor]p5:
535 : // A constructor is trivial if its class has no virtual base classes.
536 198: Class->setHasTrivialConstructor(false);
537 :
538 : // C++ [class.copy]p6:
539 : // A copy constructor is trivial if its class has no virtual base classes.
540 198: Class->setHasTrivialCopyConstructor(false);
541 :
542 : // C++ [class.copy]p11:
543 : // A copy assignment operator is trivial if its class has no virtual
544 : // base classes.
545 198: Class->setHasTrivialCopyAssignment(false);
546 :
547 : // C++0x [meta.unary.prop] is_empty:
548 : // T is a class type, but not a union type, with ... no virtual base
549 : // classes
550 198: Class->setEmpty(false);
551 : } else {
552 : // C++ [class.ctor]p5:
553 : // A constructor is trivial if all the direct base classes of its
554 : // class have trivial constructors.
323: branch 1 taken
382: branch 2 taken
555 705: if (!BaseClass->hasTrivialConstructor())
556 323: Class->setHasTrivialConstructor(false);
557 :
558 : // C++ [class.copy]p6:
559 : // A copy constructor is trivial if all the direct base classes of its
560 : // class have trivial copy constructors.
223: branch 1 taken
482: branch 2 taken
561 705: if (!BaseClass->hasTrivialCopyConstructor())
562 223: Class->setHasTrivialCopyConstructor(false);
563 :
564 : // C++ [class.copy]p11:
565 : // A copy assignment operator is trivial if all the direct base classes
566 : // of its class have trivial copy assignment operators.
223: branch 1 taken
482: branch 2 taken
567 705: if (!BaseClass->hasTrivialCopyAssignment())
568 223: Class->setHasTrivialCopyAssignment(false);
569 : }
570 :
571 : // C++ [class.ctor]p3:
572 : // A destructor is trivial if all the direct base classes of its class
573 : // have trivial destructors.
41: branch 1 taken
862: branch 2 taken
574 903: if (!BaseClass->hasTrivialDestructor())
575 41: Class->setHasTrivialDestructor(false);
576 903: }
577 :
578 : /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579 : /// one entry in the base class list of a class specifier, for
580 : /// example:
581 : /// class foo : public bar, virtual private baz {
582 : /// 'public bar' and 'virtual private baz' are each base-specifiers.
583 : Sema::BaseResult
584 : Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
585 : bool Virtual, AccessSpecifier Access,
586 899: TypeTy *basetype, SourceLocation BaseLoc) {
1: branch 1 taken
898: branch 2 taken
587 899: if (!classdecl)
588 1: return true;
589 :
590 898: AdjustDeclIfTemplate(classdecl);
591 898: CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
592 898: QualType BaseType = GetTypeFromParser(basetype);
892: branch 0 taken
6: branch 1 taken
593 898: if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594 : Virtual, Access,
595 898: BaseType, BaseLoc))
596 892: return BaseSpec;
597 :
598 6: return true;
599 : }
600 :
601 : /// \brief Performs the actual work of attaching the given base class
602 : /// specifiers to a C++ class.
603 : bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604 2119: unsigned NumBases) {
1356: branch 0 taken
763: branch 1 taken
605 2119: if (NumBases == 0)
606 1356: return false;
607 :
608 : // Used to keep track of which base types we have already seen, so
609 : // that we can properly diagnose redundant direct base types. Note
610 : // that the key is always the unqualified canonical type of the base
611 : // class.
612 763: std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613 :
614 : // Copy non-redundant base specifiers into permanent storage.
615 763: unsigned NumGoodBases = 0;
616 763: bool Invalid = false;
977: branch 0 taken
763: branch 1 taken
617 1740: for (unsigned idx = 0; idx < NumBases; ++idx) {
618 : QualType NewBaseType
619 977: = Context.getCanonicalType(Bases[idx]->getType());
620 977: NewBaseType = NewBaseType.getLocalUnqualifiedType();
621 :
2: branch 1 taken
975: branch 2 taken
622 977: if (KnownBaseTypes[NewBaseType]) {
623 : // C++ [class.mi]p3:
624 : // A class shall not be specified as a direct base class of a
625 : // derived class more than once.
626 : Diag(Bases[idx]->getSourceRange().getBegin(),
627 : diag::err_duplicate_base_class)
628 : << KnownBaseTypes[NewBaseType]->getType()
629 2: << Bases[idx]->getSourceRange();
630 :
631 : // Delete the duplicate base class specifier; we're going to
632 : // overwrite its pointer later.
633 2: Context.Deallocate(Bases[idx]);
634 :
635 2: Invalid = true;
636 : } else {
637 : // Okay, add this new base class.
638 975: KnownBaseTypes[NewBaseType] = Bases[idx];
639 975: Bases[NumGoodBases++] = Bases[idx];
640 : }
641 : }
642 :
643 : // Attach the remaining base class specifiers to the derived class.
644 763: Class->setBases(Context, Bases, NumGoodBases);
645 :
646 : // Delete the remaining (good) base class specifiers, since their
647 : // data has been copied into the CXXRecordDecl.
975: branch 0 taken
763: branch 1 taken
648 1738: for (unsigned idx = 0; idx < NumGoodBases; ++idx)
649 975: Context.Deallocate(Bases[idx]);
650 :
651 763: return Invalid;
652 : }
653 :
654 : /// ActOnBaseSpecifiers - Attach the given base specifiers to the
655 : /// class, after checking whether there are any duplicate base
656 : /// classes.
657 : void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
658 701: unsigned NumBases) {
700: branch 1 taken
1: branch 2 taken
700: branch 3 taken
0: branch 4 not taken
8: branch 5 taken
692: branch 6 taken
9: branch 7 taken
692: branch 8 taken
659 701: if (!ClassDecl || !Bases || !NumBases)
660 9: return;
661 :
662 692: AdjustDeclIfTemplate(ClassDecl);
663 : AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
664 692: (CXXBaseSpecifier**)(Bases), NumBases);
665 : }
666 :
667 : /// \brief Determine whether the type \p Derived is a C++ class that is
668 : /// derived from the type \p Base.
669 30682: bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
0: branch 1 not taken
30682: branch 2 taken
670 30682: if (!getLangOptions().CPlusPlus)
671 0: return false;
672 :
673 30682: const RecordType *DerivedRT = Derived->getAs<RecordType>();
4651: branch 0 taken
26031: branch 1 taken
674 30682: if (!DerivedRT)
675 4651: return false;
676 :
677 26031: const RecordType *BaseRT = Base->getAs<RecordType>();
23517: branch 0 taken
2514: branch 1 taken
678 26031: if (!BaseRT)
679 23517: return false;
680 :
681 2514: CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682 2514: CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
683 : // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
2512: branch 1 taken
2: branch 2 taken
986: branch 4 taken
1526: branch 5 taken
684 2514: return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
685 : }
686 :
687 : /// \brief Determine whether the type \p Derived is a C++ class that is
688 : /// derived from the type \p Base.
689 540: bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
0: branch 1 not taken
540: branch 2 taken
690 540: if (!getLangOptions().CPlusPlus)
691 0: return false;
692 :
693 540: const RecordType *DerivedRT = Derived->getAs<RecordType>();
5: branch 0 taken
535: branch 1 taken
694 540: if (!DerivedRT)
695 5: return false;
696 :
697 535: const RecordType *BaseRT = Base->getAs<RecordType>();
0: branch 0 not taken
535: branch 1 taken
698 535: if (!BaseRT)
699 0: return false;
700 :
701 535: CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
702 535: CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
703 535: return DerivedRD->isDerivedFrom(BaseRD, Paths);
704 : }
705 :
706 : /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
707 : /// conversion (where Derived and Base are class types) is
708 : /// well-formed, meaning that the conversion is unambiguous (and
709 : /// that all of the base classes are accessible). Returns true
710 : /// and emits a diagnostic if the code is ill-formed, returns false
711 : /// otherwise. Loc is the location where this routine should point to
712 : /// if there is an error, and Range is the source range to highlight
713 : /// if there is an error.
714 : bool
715 : Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
716 : unsigned InaccessibleBaseID,
717 : unsigned AmbigiousBaseConvID,
718 : SourceLocation Loc, SourceRange Range,
719 334: DeclarationName Name) {
720 : // First, determine whether the path from Derived to Base is
721 : // ambiguous. This is slightly more expensive than checking whether
722 : // the Derived to Base conversion exists, because here we need to
723 : // explore multiple paths to determine if there is an ambiguity.
724 : CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
725 334: /*DetectVirtual=*/false);
726 334: bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
727 : assert(DerivationOkay &&
0: branch 0 not taken
334: branch 1 taken
728 334: "Can only be used with a derived-to-base conversion");
729 : (void)DerivationOkay;
730 :
321: branch 4 taken
13: branch 5 taken
731 334: if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
18: branch 0 taken
303: branch 1 taken
732 321: if (InaccessibleBaseID == 0)
733 18: return false;
734 : // Check that the base class can be accessed.
735 : return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
736 303: Name);
737 : }
738 :
739 : // We know that the derived-to-base conversion is ambiguous, and
740 : // we're going to produce a diagnostic. Perform the derived-to-base
741 : // search just one more time to compute all of the possible paths so
742 : // that we can print them out. This is more expensive than any of
743 : // the previous derived-to-base checks we've done, but at this point
744 : // performance isn't as much of an issue.
745 13: Paths.clear();
746 13: Paths.setRecordingPaths(true);
747 13: bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
0: branch 0 not taken
13: branch 1 taken
748 13: assert(StillOkay && "Can only be used with a derived-to-base conversion");
749 : (void)StillOkay;
750 :
751 : // Build up a textual representation of the ambiguous paths, e.g.,
752 : // D -> B -> A, that will be used to illustrate the ambiguous
753 : // conversions in the diagnostic. We only print one of the paths
754 : // to each base class subobject.
755 13: std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
756 :
757 : Diag(Loc, AmbigiousBaseConvID)
758 13: << Derived << Base << PathDisplayStr << Range << Name;
759 13: return true;
760 : }
761 :
762 : bool
763 : Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
764 : SourceLocation Loc, SourceRange Range,
765 303: bool IgnoreAccess) {
766 : return CheckDerivedToBaseConversion(Derived, Base,
767 : IgnoreAccess ? 0 :
768 : diag::err_conv_to_inaccessible_base,
769 : diag::err_ambiguous_derived_to_base_conv,
18: branch 1 taken
285: branch 2 taken
770 303: Loc, Range, DeclarationName());
771 : }
772 :
773 :
774 : /// @brief Builds a string representing ambiguous paths from a
775 : /// specific derived class to different subobjects of the same base
776 : /// class.
777 : ///
778 : /// This function builds a string that can be used in error messages
779 : /// to show the different paths that one can take through the
780 : /// inheritance hierarchy to go from the derived class to different
781 : /// subobjects of a base class. The result looks something like this:
782 : /// @code
783 : /// struct D -> struct B -> struct A
784 : /// struct D -> struct C -> struct A
785 : /// @endcode
786 27: std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
787 27: std::string PathDisplayStr;
788 27: std::set<unsigned> DisplayedPaths;
56: branch 4 taken
27: branch 5 taken
789 83: for (CXXBasePaths::paths_iterator Path = Paths.begin();
790 : Path != Paths.end(); ++Path) {
54: branch 3 taken
2: branch 4 taken
791 56: if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
792 : // We haven't displayed a path to this particular base
793 : // class subobject yet.
794 54: PathDisplayStr += "\n ";
795 54: PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
116: branch 4 taken
54: branch 5 taken
796 170: for (CXXBasePath::const_iterator Element = Path->begin();
797 : Element != Path->end(); ++Element)
798 116: PathDisplayStr += " -> " + Element->Base->getType().getAsString();
799 : }
800 : }
801 :
802 27: return PathDisplayStr;
803 : }
804 :
805 : //===----------------------------------------------------------------------===//
806 : // C++ class member Handling
807 : //===----------------------------------------------------------------------===//
808 :
809 : /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
810 : /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
811 : /// bitfield width if there is one and 'InitExpr' specifies the initializer if
812 : /// any.
813 : Sema::DeclPtrTy
814 : Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
815 : MultiTemplateParamsArg TemplateParameterLists,
816 : ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
817 4641: bool Deleted) {
818 4641: const DeclSpec &DS = D.getDeclSpec();
819 4641: DeclarationName Name = GetNameForDeclarator(D);
820 4641: Expr *BitWidth = static_cast<Expr*>(BW);
821 4641: Expr *Init = static_cast<Expr*>(InitExpr);
822 4641: SourceLocation Loc = D.getIdentifierLoc();
823 :
824 4641: bool isFunc = D.isFunctionDeclarator();
825 :
0: branch 1 not taken
4641: branch 2 taken
826 4641: assert(!DS.isFriendSpecified());
827 :
828 : // C++ 9.2p6: A member shall not be declared to have automatic storage
829 : // duration (auto, register) or with the extern storage-class-specifier.
830 : // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
831 : // data members and cannot be applied to names declared const or static,
832 : // and cannot be applied to reference members.
4624: branch 1 taken
14: branch 2 taken
3: branch 3 taken
833 4641: switch (DS.getStorageClassSpec()) {
834 : case DeclSpec::SCS_unspecified:
835 : case DeclSpec::SCS_typedef:
836 : case DeclSpec::SCS_static:
837 : // FALL THROUGH.
838 4624: break;
839 : case DeclSpec::SCS_mutable:
2: branch 0 taken
12: branch 1 taken
840 14: if (isFunc) {
2: branch 2 taken
0: branch 3 not taken
841 2: if (DS.getStorageClassSpecLoc().isValid())
842 2: Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
843 : else
844 0: Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
845 :
846 : // FIXME: It would be nicer if the keyword was ignored only for this
847 : // declarator. Otherwise we could get follow-up errors.
848 2: D.getMutableDeclSpec().ClearStorageClassSpecs();
849 : } else {
850 12: QualType T = GetTypeForDeclarator(D, S);
851 12: diag::kind err = static_cast<diag::kind>(0);
3: branch 2 taken
9: branch 3 taken
852 12: if (T->isReferenceType())
853 3: err = diag::err_mutable_reference;
3: branch 1 taken
6: branch 2 taken
854 9: else if (T.isConstQualified())
855 3: err = diag::err_mutable_const;
6: branch 0 taken
6: branch 1 taken
856 12: if (err != 0) {
6: branch 2 taken
0: branch 3 not taken
857 6: if (DS.getStorageClassSpecLoc().isValid())
858 6: Diag(DS.getStorageClassSpecLoc(), err);
859 : else
860 0: Diag(DS.getThreadSpecLoc(), err);
861 : // FIXME: It would be nicer if the keyword was ignored only for this
862 : // declarator. Otherwise we could get follow-up errors.
863 6: D.getMutableDeclSpec().ClearStorageClassSpecs();
864 : }
865 : }
866 14: break;
867 : default:
3: branch 2 taken
0: branch 3 not taken
868 3: if (DS.getStorageClassSpecLoc().isValid())
869 : Diag(DS.getStorageClassSpecLoc(),
870 3: diag::err_storageclass_invalid_for_member);
871 : else
872 0: Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
873 3: D.getMutableDeclSpec().ClearStorageClassSpecs();
874 : }
875 :
1940: branch 0 taken
2701: branch 1 taken
428: branch 4 taken
1512: branch 5 taken
323: branch 7 taken
105: branch 8 taken
323: branch 9 taken
4318: branch 10 taken
876 4641: if (!isFunc &&
877 : D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
878 : D.getNumTypeObjects() == 0) {
879 : // Check also for this case:
880 : //
881 : // typedef int f();
882 : // f a;
883 : //
884 323: QualType TDType = GetTypeFromParser(DS.getTypeRep());
885 323: isFunc = TDType->isFunctionType();
886 : }
887 :
888 : bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
889 : DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
469: branch 1 taken
4172: branch 2 taken
6: branch 4 taken
463: branch 5 taken
1552: branch 6 taken
2626: branch 7 taken
890 4641: !isFunc);
891 :
892 : Decl *Member;
1552: branch 0 taken
3089: branch 1 taken
893 4641: if (isInstField) {
894 : // FIXME: Check for template parameters!
895 : Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
896 1552: AS);
0: branch 0 not taken
1552: branch 1 taken
897 1552: assert(Member && "HandleField never returns null");
898 : } else {
899 : Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
900 3089: .getAs<Decl>();
1: branch 0 taken
3088: branch 1 taken
901 3089: if (!Member) {
0: branch 0 not taken
1: branch 1 taken
902 1: if (BitWidth) DeleteExpr(BitWidth);
903 1: return DeclPtrTy();
904 : }
905 :
906 : // Non-instance-fields can't have a bitfield.
3: branch 0 taken
3085: branch 1 taken
907 3088: if (BitWidth) {
3: branch 1 taken
0: branch 2 not taken
908 3: if (Member->isInvalidDecl()) {
909 : // don't emit another diagnostic.
1: branch 1 taken
2: branch 2 taken
910 3: } else if (isa<VarDecl>(Member)) {
911 : // C++ 9.6p3: A bit-field shall not be a static member.
912 : // "static member 'A' cannot be a bit-field"
913 : Diag(Loc, diag::err_static_not_bitfield)
914 1: << Name << BitWidth->getSourceRange();
1: branch 1 taken
1: branch 2 taken
915 2: } else if (isa<TypedefDecl>(Member)) {
916 : // "typedef member 'x' cannot be a bit-field"
917 : Diag(Loc, diag::err_typedef_not_bitfield)
918 1: << Name << BitWidth->getSourceRange();
919 : } else {
920 : // A function typedef ("typedef int f(); f a;").
921 : // C++ 9.6p3: A bit-field shall have integral or enumeration type.
922 : Diag(Loc, diag::err_not_integral_type_bitfield)
923 : << Name << cast<ValueDecl>(Member)->getType()
924 1: << BitWidth->getSourceRange();
925 : }
926 :
927 3: DeleteExpr(BitWidth);
928 3: BitWidth = 0;
929 3: Member->setInvalidDecl();
930 : }
931 :
932 3088: Member->setAccess(AS);
933 :
934 : // If we have declared a member function template, set the access of the
935 : // templated declaration as well.
110: branch 1 taken
2978: branch 2 taken
936 3088: if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
937 110: FunTmpl->getTemplatedDecl()->setAccess(AS);
938 : }
939 :
10: branch 1 taken
4630: branch 2 taken
10: branch 3 taken
0: branch 4 not taken
940 4640: assert((Name || isInstField) && "No identifier for non-field ?");
941 :
157: branch 0 taken
4483: branch 1 taken
942 4640: if (Init)
943 157: AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
8: branch 0 taken
4632: branch 1 taken
944 4640: if (Deleted) // FIXME: Source location is not very good.
945 8: SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
946 :
1552: branch 0 taken
3088: branch 1 taken
947 4640: if (isInstField) {
948 1552: FieldCollector->Add(cast<FieldDecl>(Member));
949 1552: return DeclPtrTy();
950 : }
951 3088: return DeclPtrTy::make(Member);
952 : }
953 :
954 : /// \brief Find the direct and/or virtual base specifiers that
955 : /// correspond to the given base type, for use in base initialization
956 : /// within a constructor.
957 : static bool FindBaseInitializer(Sema &SemaRef,
958 : CXXRecordDecl *ClassDecl,
959 : QualType BaseType,
960 : const CXXBaseSpecifier *&DirectBaseSpec,
961 58: const CXXBaseSpecifier *&VirtualBaseSpec) {
962 : // First, check for a direct base class.
963 58: DirectBaseSpec = 0;
77: branch 1 taken
9: branch 2 taken
964 86: for (CXXRecordDecl::base_class_const_iterator Base
965 58: = ClassDecl->bases_begin();
966 : Base != ClassDecl->bases_end(); ++Base) {
49: branch 2 taken
28: branch 3 taken
967 77: if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
968 : // We found a direct base of this type. That's what we're
969 : // initializing.
970 49: DirectBaseSpec = &*Base;
971 49: break;
972 : }
973 : }
974 :
975 : // Check for a virtual base class.
976 : // FIXME: We might be able to short-circuit this if we know in advance that
977 : // there are no virtual bases.
978 58: VirtualBaseSpec = 0;
49: branch 0 taken
9: branch 1 taken
43: branch 3 taken
6: branch 4 taken
52: branch 5 taken
6: branch 6 taken
979 58: if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
980 : // We haven't found a base yet; search the class hierarchy for a
981 : // virtual base class.
982 : CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
983 52: /*DetectVirtual=*/false);
49: branch 2 taken
3: branch 3 taken
984 52: if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
985 : BaseType, Paths)) {
49: branch 4 taken
44: branch 5 taken
986 93: for (CXXBasePaths::paths_iterator Path = Paths.begin();
987 : Path != Paths.end(); ++Path) {
5: branch 3 taken
44: branch 4 taken
988 49: if (Path->back().Base->isVirtual()) {
989 5: VirtualBaseSpec = Path->back().Base;
990 5: break;
991 : }
992 : }
993 52: }
994 : }
995 :
9: branch 0 taken
49: branch 1 taken
4: branch 2 taken
5: branch 3 taken
996 58: return DirectBaseSpec || VirtualBaseSpec;
997 : }
998 :
999 : /// ActOnMemInitializer - Handle a C++ member initializer.
1000 : Sema::MemInitResult
1001 : Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1002 : Scope *S,
1003 : const CXXScopeSpec &SS,
1004 : IdentifierInfo *MemberOrBase,
1005 : TypeTy *TemplateTypeTy,
1006 : SourceLocation IdLoc,
1007 : SourceLocation LParenLoc,
1008 : ExprTy **Args, unsigned NumArgs,
1009 : SourceLocation *CommaLocs,
1010 307: SourceLocation RParenLoc) {
0: branch 1 not taken
307: branch 2 taken
1011 307: if (!ConstructorD)
1012 0: return true;
1013 :
1014 307: AdjustDeclIfTemplate(ConstructorD);
1015 :
1016 : CXXConstructorDecl *Constructor
1017 307: = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
2: branch 0 taken
305: branch 1 taken
1018 307: if (!Constructor) {
1019 : // The user wrote a constructor initializer on a function that is
1020 : // not a C++ constructor. Ignore the error for now, because we may
1021 : // have more member initializers coming; we'll diagnose it just
1022 : // once in ActOnMemInitializers.
1023 2: return true;
1024 : }
1025 :
1026 305: CXXRecordDecl *ClassDecl = Constructor->getParent();
1027 :
1028 : // C++ [class.base.init]p2:
1029 : // Names in a mem-initializer-id are looked up in the scope of the
1030 : // constructor’s class and, if not found in that scope, are looked
1031 : // up in the scope containing the constructor’s
1032 : // definition. [Note: if the constructor’s class contains a member
1033 : // with the same name as a direct or virtual base class of the
1034 : // class, a mem-initializer-id naming the member or base class and
1035 : // composed of a single identifier refers to the class member. A
1036 : // mem-initializer-id for the hidden base class may be specified
1037 : // using a qualified name. ]
293: branch 1 taken
12: branch 2 taken
285: branch 3 taken
8: branch 4 taken
285: branch 5 taken
20: branch 6 taken
1038 305: if (!SS.getScopeRep() && !TemplateTypeTy) {
1039 : // Look for a member, first.
1040 285: FieldDecl *Member = 0;
1041 : DeclContext::lookup_result Result
1042 285: = ClassDecl->lookup(MemberOrBase);
241: branch 0 taken
44: branch 1 taken
1043 285: if (Result.first != Result.second)
1044 241: Member = dyn_cast<FieldDecl>(*Result.first);
1045 :
1046 : // FIXME: Handle members of an anonymous union.
1047 :
235: branch 0 taken
50: branch 1 taken
1048 285: if (Member)
1049 : return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1050 235: LParenLoc, RParenLoc);
1051 : }
1052 : // It didn't name a member, so see if it names a class.
1053 70: QualType BaseType;
1054 70: TypeSourceInfo *TInfo = 0;
1055 :
10: branch 0 taken
60: branch 1 taken
1056 70: if (TemplateTypeTy) {
1057 10: BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1058 : } else {
1059 60: LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1060 60: LookupParsedName(R, S, &SS);
1061 :
1062 60: TypeDecl *TyD = R.getAsSingle<TypeDecl>();
11: branch 0 taken
49: branch 1 taken
1063 60: if (!TyD) {
0: branch 1 not taken
11: branch 2 taken
1064 17: if (R.isAmbiguous()) return true;
1065 :
5: branch 1 taken
6: branch 2 taken
3: branch 4 taken
2: branch 5 taken
3: branch 6 taken
8: branch 7 taken
1066 11: if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1067 3: bool NotUnknownSpecialization = false;
1068 3: DeclContext *DC = computeDeclContext(SS, false);
0: branch 1 not taken
3: branch 2 taken
1069 3: if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1070 0: NotUnknownSpecialization = !Record->hasAnyDependentBases();
1071 :
3: branch 0 taken
0: branch 1 not taken
1072 3: if (!NotUnknownSpecialization) {
1073 : // When the scope specifier can refer to a member of an unknown
1074 : // specialization, we take it as a type name.
1075 : BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1076 3: *MemberOrBase, SS.getRange());
1077 3: R.clear();
1078 : }
1079 : }
1080 :
1081 : // If no results were found, try to correct typos.
9: branch 1 taken
2: branch 2 taken
6: branch 4 taken
3: branch 5 taken
6: branch 6 taken
0: branch 7 not taken
4: branch 9 taken
2: branch 10 taken
4: branch 12 taken
0: branch 13 not taken
4: branch 14 taken
7: branch 15 taken
1082 11: if (R.empty() && BaseType.isNull() &&
1083 : CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
2: branch 1 taken
2: branch 2 taken
1084 4: if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
2: branch 0 taken
0: branch 1 not taken
2: branch 5 taken
0: branch 6 not taken
1085 2: if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1086 : // We have found a non-static data member with a similar
1087 : // name to what was typed; complain and initialize that
1088 : // member.
1089 : Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1090 : << MemberOrBase << true << R.getLookupName()
1091 : << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1092 2: R.getLookupName().getAsString());
1093 : Diag(Member->getLocation(), diag::note_previous_decl)
1094 2: << Member->getDeclName();
1095 :
1096 : return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1097 2: LParenLoc, RParenLoc);
1098 : }
2: branch 1 taken
0: branch 2 not taken
1099 2: } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1100 : const CXXBaseSpecifier *DirectBaseSpec;
1101 : const CXXBaseSpecifier *VirtualBaseSpec;
2: branch 2 taken
0: branch 3 not taken
1102 2: if (FindBaseInitializer(*this, ClassDecl,
1103 : Context.getTypeDeclType(Type),
1104 : DirectBaseSpec, VirtualBaseSpec)) {
1105 : // We have found a direct or virtual base class with a
1106 : // similar name to what was typed; complain and initialize
1107 : // that base class.
1108 : Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1109 : << MemberOrBase << false << R.getLookupName()
1110 : << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1111 2: R.getLookupName().getAsString());
1112 :
1113 : const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2: branch 0 taken
0: branch 1 not taken
1114 2: : VirtualBaseSpec;
1115 : Diag(BaseSpec->getSourceRange().getBegin(),
1116 : diag::note_base_class_specified_here)
1117 : << BaseSpec->getType()
1118 2: << BaseSpec->getSourceRange();
1119 :
1120 2: TyD = Type;
1121 : }
1122 : }
1123 : }
1124 :
7: branch 0 taken
2: branch 1 taken
4: branch 3 taken
3: branch 4 taken
4: branch 5 taken
5: branch 6 taken
1125 9: if (!TyD && BaseType.isNull()) {
1126 : Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1127 4: << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1128 4: return true;
1129 : }
1130 : }
1131 :
51: branch 1 taken
3: branch 2 taken
1132 54: if (BaseType.isNull()) {
1133 51: BaseType = Context.getTypeDeclType(TyD);
5: branch 1 taken
46: branch 2 taken
1134 51: if (SS.isSet()) {
1135 : NestedNameSpecifier *Qualifier =
1136 5: static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1137 :
1138 : // FIXME: preserve source range information
1139 5: BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1140 : }
54: branch 1 taken
6: branch 2 taken
1141 60: }
1142 : }
1143 :
54: branch 0 taken
10: branch 1 taken
1144 64: if (!TInfo)
1145 54: TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1146 :
1147 : return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1148 64: LParenLoc, RParenLoc, ClassDecl);
1149 : }
1150 :
1151 : /// Checks an initializer expression for use of uninitialized fields, such as
1152 : /// containing the field that is being initialized. Returns true if there is an
1153 : /// uninitialized field was used an updates the SourceLocation parameter; false
1154 : /// otherwise.
1155 : static bool InitExprContainsUninitializedFields(const Stmt* S,
1156 : const FieldDecl* LhsField,
1157 290: SourceLocation* L) {
1158 290: const MemberExpr* ME = dyn_cast<MemberExpr>(S);
20: branch 0 taken
270: branch 1 taken
1159 290: if (ME) {
1160 20: const NamedDecl* RhsField = ME->getMemberDecl();
16: branch 0 taken
4: branch 1 taken
1161 20: if (RhsField == LhsField) {
1162 : // Initializing a field with itself. Throw a warning.
1163 : // But wait; there are exceptions!
1164 : // Exception #1: The field may not belong to this record.
1165 : // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1166 16: const Expr* base = ME->getBase();
16: branch 0 taken
0: branch 1 not taken
9: branch 4 taken
7: branch 5 taken
9: branch 6 taken
7: branch 7 taken
1167 16: if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1168 : // Even though the field matches, it does not belong to this record.
1169 9: return false;
1170 : }
1171 : // None of the exceptions triggered; return true to indicate an
1172 : // uninitialized field was used.
1173 7: *L = ME->getMemberLoc();
1174 7: return true;
1175 : }
1176 : }
1177 274: bool found = false;
64: branch 4 taken
274: branch 5 taken
64: branch 6 taken
0: branch 7 not taken
64: branch 8 taken
274: branch 9 taken
1178 338: for (Stmt::const_child_iterator it = S->child_begin();
1179 : it != S->child_end() && found == false;
1180 : ++it) {
9: branch 1 taken
55: branch 2 taken
1181 64: if (isa<CallExpr>(S)) {
1182 : // Do not descend into function calls or constructors, as the use
1183 : // of an uninitialized field may be valid. One would have to inspect
1184 : // the contents of the function/ctor to determine if it is safe or not.
1185 : // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1186 : // may be safe, depending on what the function/ctor does.
1187 9: continue;
1188 : }
1189 55: found = InitExprContainsUninitializedFields(*it, LhsField, L);
1190 : }
1191 274: return found;
1192 : }
1193 :
1194 : Sema::MemInitResult
1195 : Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1196 : unsigned NumArgs, SourceLocation IdLoc,
1197 : SourceLocation LParenLoc,
1198 250: SourceLocation RParenLoc) {
1199 : // Diagnose value-uses of fields to initialize themselves, e.g.
1200 : // foo(foo)
1201 : // where foo is not also a parameter to the constructor.
1202 : // TODO: implement -Wuninitialized and fold this into that framework.
235: branch 0 taken
250: branch 1 taken
1203 485: for (unsigned i = 0; i < NumArgs; ++i) {
1204 235: SourceLocation L;
7: branch 1 taken
228: branch 2 taken
1205 235: if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1206 : // FIXME: Return true in the case when other fields are used before being
1207 : // uninitialized. For example, let this field be the i'th field. When
1208 : // initializing the i'th field, throw a warning if any of the >= i'th
1209 : // fields are used, as they are not yet initialized.
1210 : // Right now we are only handling the case where the i'th field uses
1211 : // itself in its initializer.
1212 7: Diag(L, diag::warn_field_is_uninit);
1213 : }
1214 : }
1215 :
1216 250: bool HasDependentArg = false;
235: branch 0 taken
250: branch 1 taken
1217 485: for (unsigned i = 0; i < NumArgs; i++)
1218 235: HasDependentArg |= Args[i]->isTypeDependent();
1219 :
1220 250: QualType FieldType = Member->getType();
5: branch 1 taken
245: branch 2 taken
1221 250: if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1222 5: FieldType = Array->getElementType();
1223 250: ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
238: branch 2 taken
12: branch 3 taken
2: branch 4 taken
236: branch 5 taken
14: branch 6 taken
236: branch 7 taken
1224 250: if (FieldType->isDependentType() || HasDependentArg) {
1225 : // Can't check initialization for a member of dependent type or when
1226 : // any of the arguments are type-dependent expressions.
1227 : OwningExprResult Init
1228 : = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
14: branch 1 taken
0: branch 2 not taken
1229 14: RParenLoc));
1230 :
1231 : // Erase any temporaries within this evaluation context; we're not
1232 : // going to track them in the AST, since we'll be rebuilding the
1233 : // ASTs during template instantiation.
1234 : ExprTemporaries.erase(
1235 : ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1236 14: ExprTemporaries.end());
1237 :
1238 : return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1239 : LParenLoc,
1240 : Init.takeAs<Expr>(),
14: branch 2 taken
0: branch 3 not taken
1241 14: RParenLoc);
1242 :
1243 : }
1244 :
1: branch 1 taken
235: branch 2 taken
1245 236: if (Member->isInvalidDecl())
1246 1: return true;
1247 :
1248 : // Initialize the member.
1249 : InitializedEntity MemberEntity =
1250 235: InitializedEntity::InitializeMember(Member, 0);
1251 : InitializationKind Kind =
1252 235: InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1253 :
1254 235: InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1255 :
1256 : OwningExprResult MemberInit =
1257 : InitSeq.Perform(*this, MemberEntity, Kind,
1258 235: MultiExprArg(*this, (void**)Args, NumArgs), 0);
5: branch 1 taken
230: branch 2 taken
1259 235: if (MemberInit.isInvalid())
1260 5: return true;
1261 :
1262 : // C++0x [class.base.init]p7:
1263 : // The initialization of each base and member constitutes a
1264 : // full-expression.
1265 230: MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
0: branch 1 not taken
230: branch 2 taken
1266 230: if (MemberInit.isInvalid())
1267 0: return true;
1268 :
1269 : // If we are in a dependent context, template instantiation will
1270 : // perform this type-checking again. Just save the arguments that we
1271 : // received in a ParenListExpr.
1272 : // FIXME: This isn't quite ideal, since our ASTs don't capture all
1273 : // of the information that we have about the member
1274 : // initializer. However, deconstructing the ASTs is a dicey process,
1275 : // and this approach is far more likely to get the corner cases right.
9: branch 1 taken
221: branch 2 taken
1276 230: if (CurContext->isDependentContext()) {
1277 : // Bump the reference count of all of the arguments.
9: branch 0 taken
9: branch 1 taken
1278 18: for (unsigned I = 0; I != NumArgs; ++I)
1279 9: Args[I]->Retain();
1280 :
1281 : OwningExprResult Init
1282 : = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
9: branch 1 taken
0: branch 2 not taken
1283 9: RParenLoc));
1284 : return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1285 : LParenLoc,
1286 : Init.takeAs<Expr>(),
9: branch 2 taken
0: branch 3 not taken
1287 9: RParenLoc);
1288 : }
1289 :
1290 : return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291 : LParenLoc,
1292 : MemberInit.takeAs<Expr>(),
221: branch 2 taken
0: branch 3 not taken
1293 221: RParenLoc);
1294 : }
1295 :
1296 : Sema::MemInitResult
1297 : Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1298 : Expr **Args, unsigned NumArgs,
1299 : SourceLocation LParenLoc, SourceLocation RParenLoc,
1300 72: CXXRecordDecl *ClassDecl) {
1301 72: bool HasDependentArg = false;
30: branch 0 taken
72: branch 1 taken
1302 102: for (unsigned i = 0; i < NumArgs; i++)
1303 30: HasDependentArg |= Args[i]->isTypeDependent();
1304 :
1305 72: SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
58: branch 2 taken
14: branch 3 taken
1: branch 4 taken
57: branch 5 taken
15: branch 6 taken
57: branch 7 taken
1306 72: if (BaseType->isDependentType() || HasDependentArg) {
1307 : // Can't check initialization for a base of dependent type or when
1308 : // any of the arguments are type-dependent expressions.
1309 : OwningExprResult BaseInit
1310 : = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
15: branch 1 taken
0: branch 2 not taken
1311 15: RParenLoc));
1312 :
1313 : // Erase any temporaries within this evaluation context; we're not
1314 : // going to track them in the AST, since we'll be rebuilding the
1315 : // ASTs during template instantiation.
1316 : ExprTemporaries.erase(
1317 : ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1318 15: ExprTemporaries.end());
1319 :
1320 : return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1321 : LParenLoc,
1322 : BaseInit.takeAs<Expr>(),
15: branch 2 taken
0: branch 3 not taken
1323 15: RParenLoc);
1324 : }
1325 :
1: branch 2 taken
56: branch 3 taken
1326 57: if (!BaseType->isRecordType())
1327 : return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1328 1: << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1329 :
1330 : // C++ [class.base.init]p2:
1331 : // [...] Unless the mem-initializer-id names a nonstatic data
1332 : // member of the constructor’s class or a direct or virtual base
1333 : // of that class, the mem-initializer is ill-formed. A
1334 : // mem-initializer-list can initialize a base class using any
1335 : // name that denotes that base class type.
1336 :
1337 : // Check for direct and virtual base classes.
1338 56: const CXXBaseSpecifier *DirectBaseSpec = 0;
1339 56: const CXXBaseSpecifier *VirtualBaseSpec = 0;
1340 : FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1341 56: VirtualBaseSpec);
1342 :
1343 : // C++ [base.class.init]p2:
1344 : // If a mem-initializer-id is ambiguous because it designates both
1345 : // a direct non-virtual base class and an inherited virtual base
1346 : // class, the mem-initializer is ill-formed.
47: branch 0 taken
9: branch 1 taken
1: branch 2 taken
46: branch 3 taken
1347 56: if (DirectBaseSpec && VirtualBaseSpec)
1348 : return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1349 1: << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1350 : // C++ [base.class.init]p2:
1351 : // Unless the mem-initializer-id names a nonstatic data membeer of the
1352 : // constructor's class ot a direst or virtual base of that class, the
1353 : // mem-initializer is ill-formed.
9: branch 0 taken
46: branch 1 taken
5: branch 2 taken
4: branch 3 taken
1354 55: if (!DirectBaseSpec && !VirtualBaseSpec)
1355 : return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1356 : << BaseType << ClassDecl->getNameAsCString()
1357 5: << BaseTInfo->getTypeLoc().getSourceRange();
1358 :
1359 : CXXBaseSpecifier *BaseSpec
1360 50: = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
4: branch 0 taken
46: branch 1 taken
1361 50: if (!BaseSpec)
1362 4: BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1363 :
1364 : // Initialize the base.
1365 : InitializedEntity BaseEntity =
1366 50: InitializedEntity::InitializeBase(Context, BaseSpec);
1367 : InitializationKind Kind =
1368 50: InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1369 :
1370 50: InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1371 :
1372 : OwningExprResult BaseInit =
1373 : InitSeq.Perform(*this, BaseEntity, Kind,
1374 50: MultiExprArg(*this, (void**)Args, NumArgs), 0);
1: branch 1 taken
49: branch 2 taken
1375 50: if (BaseInit.isInvalid())
1376 1: return true;
1377 :
1378 : // C++0x [class.base.init]p7:
1379 : // The initialization of each base and member constitutes a
1380 : // full-expression.
1381 49: BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
0: branch 1 not taken
49: branch 2 taken
1382 49: if (BaseInit.isInvalid())
1383 0: return true;
1384 :
1385 : // If we are in a dependent context, template instantiation will
1386 : // perform this type-checking again. Just save the arguments that we
1387 : // received in a ParenListExpr.
1388 : // FIXME: This isn't quite ideal, since our ASTs don't capture all
1389 : // of the information that we have about the base
1390 : // initializer. However, deconstructing the ASTs is a dicey process,
1391 : // and this approach is far more likely to get the corner cases right.
0: branch 1 not taken
49: branch 2 taken
1392 49: if (CurContext->isDependentContext()) {
1393 : // Bump the reference count of all of the arguments.
0: branch 0 not taken
0: branch 1 not taken
1394 0: for (unsigned I = 0; I != NumArgs; ++I)
1395 0: Args[I]->Retain();
1396 :
1397 : OwningExprResult Init
1398 : = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
0: branch 1 not taken
0: branch 2 not taken
1399 0: RParenLoc));
1400 : return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1401 : LParenLoc,
1402 : Init.takeAs<Expr>(),
0: branch 2 not taken
0: branch 3 not taken
1403 0: RParenLoc);
1404 : }
1405 :
1406 : return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1407 : LParenLoc,
1408 : BaseInit.takeAs<Expr>(),
49: branch 2 taken
0: branch 3 not taken
1409 49: RParenLoc);
1410 : }
1411 :
1412 : bool
1413 : Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1414 : CXXBaseOrMemberInitializer **Initializers,
1415 : unsigned NumInitializers,
1416 : bool IsImplicitConstructor,
1417 1032: bool AnyErrors) {
1418 : // We need to build the initializer AST according to order of construction
1419 : // and not what user specified in the Initializers list.
1420 1032: CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1421 1032: llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1422 1032: llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1423 1032: bool HasDependentBaseInit = false;
1424 1032: bool HadError = false;
1425 :
300: branch 0 taken
1032: branch 1 taken
1426 1332: for (unsigned i = 0; i < NumInitializers; i++) {
1427 300: CXXBaseOrMemberInitializer *Member = Initializers[i];
62: branch 1 taken
238: branch 2 taken
1428 300: if (Member->isBaseInitializer()) {
14: branch 2 taken
48: branch 3 taken
1429 62: if (Member->getBaseClass()->isDependentType())
1430 14: HasDependentBaseInit = true;
1431 62: AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1432 : } else {
1433 238: AllBaseFields[Member->getMember()] = Member;
1434 : }
1435 : }
1436 :
14: branch 0 taken
1018: branch 1 taken
1437 1032: if (HasDependentBaseInit) {
1438 : // FIXME. This does not preserve the ordering of the initializers.
1439 : // Try (with -Wreorder)
1440 : // template<class X> struct A {};
1441 : // template<class X> struct B : A<X> {
1442 : // B() : x1(10), A<X>() {}
1443 : // int x1;
1444 : // };
1445 : // B<int> x;
1446 : // On seeing one dependent type, we should essentially exit this routine
1447 : // while preserving user-declared initializer list. When this routine is
1448 : // called during instantiatiation process, this routine will rebuild the
1449 : // ordered initializer list correctly.
1450 :
1451 : // If we have a dependent base initialization, we can't determine the
1452 : // association between initializers and bases; just dump the known
1453 : // initializers into the list, and don't try to deal with other bases.
14: branch 0 taken
14: branch 1 taken
1454 28: for (unsigned i = 0; i < NumInitializers; i++) {
1455 14: CXXBaseOrMemberInitializer *Member = Initializers[i];
14: branch 1 taken
0: branch 2 not taken
1456 14: if (Member->isBaseInitializer())
1457 14: AllToInit.push_back(Member);
1458 : }
1459 : } else {
1460 1018: llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1461 :
1462 : // Push virtual bases before others.
287: branch 0 taken
1018: branch 1 taken
1463 1305: for (CXXRecordDecl::base_class_iterator VBase =
1464 1018: ClassDecl->vbases_begin(),
1465 1018: E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
0: branch 3 not taken
287: branch 4 taken
1466 287: if (VBase->getType()->isDependentType())
1467 0: continue;
10: branch 0 taken
277: branch 1 taken
1468 287: if (CXXBaseOrMemberInitializer *Value
1469 287: = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1470 10: AllToInit.push_back(Value);
276: branch 0 taken
1: branch 1 taken
1471 277: } else if (!AnyErrors) {
1472 : InitializedEntity InitEntity
1473 276: = InitializedEntity::InitializeBase(Context, VBase);
1474 : InitializationKind InitKind
1475 276: = InitializationKind::CreateDefault(Constructor->getLocation());
1476 276: InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1477 : OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1478 276: MultiExprArg(*this, 0, 0));
1479 276: BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1: branch 1 taken
275: branch 2 taken
1480 276: if (BaseInit.isInvalid()) {
1481 1: HadError = true;
1482 1: continue;
1483 : }
1484 :
1485 : // Don't attach synthesized base initializers in a dependent
1486 : // context; they'll be checked again at template instantiation
1487 : // time.
0: branch 1 not taken
275: branch 2 taken
1488 275: if (CurContext->isDependentContext())
1489 : continue;
1490 :
1491 : CXXBaseOrMemberInitializer *CXXBaseInit =
1492 : new (Context) CXXBaseOrMemberInitializer(Context,
1493 : Context.getTrivialTypeSourceInfo(VBase->getType(),
1494 : SourceLocation()),
1495 : SourceLocation(),
1496 : BaseInit.takeAs<Expr>(),
275: branch 7 taken
0: branch 8 not taken
1497 275: SourceLocation());
275: branch 2 taken
1: branch 3 taken
275: branch 5 taken
1: branch 6 taken
1498 275: AllToInit.push_back(CXXBaseInit);
1499 : }
1500 : }
1501 :
397: branch 0 taken
1018: branch 1 taken
1502 1415: for (CXXRecordDecl::base_class_iterator Base =
1503 1018: ClassDecl->bases_begin(),
1504 1018: E = ClassDecl->bases_end(); Base != E; ++Base) {
1505 : // Virtuals are in the virtual base list and already constructed.
147: branch 1 taken
250: branch 2 taken
1506 397: if (Base->isVirtual())
1507 147: continue;
1508 : // Skip dependent types.
3: branch 3 taken
247: branch 4 taken
1509 250: if (Base->getType()->isDependentType())
1510 3: continue;
38: branch 0 taken
209: branch 1 taken
1511 247: if (CXXBaseOrMemberInitializer *Value
1512 247: = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1513 38: AllToInit.push_back(Value);
1514 : }
205: branch 0 taken
4: branch 1 taken
1515 209: else if (!AnyErrors) {
1516 : InitializedEntity InitEntity
1517 205: = InitializedEntity::InitializeBase(Context, Base);
1518 : InitializationKind InitKind
1519 205: = InitializationKind::CreateDefault(Constructor->getLocation());
1520 205: InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1521 : OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1522 205: MultiExprArg(*this, 0, 0));
1523 205: BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
3: branch 1 taken
202: branch 2 taken
1524 205: if (BaseInit.isInvalid()) {
1525 3: HadError = true;
1526 3: continue;
1527 : }
1528 :
1529 : // Don't attach synthesized base initializers in a dependent
1530 : // context; they'll be regenerated at template instantiation
1531 : // time.
0: branch 1 not taken
202: branch 2 taken
1532 202: if (CurContext->isDependentContext())
1533 : continue;
1534 :
1535 : CXXBaseOrMemberInitializer *CXXBaseInit =
1536 : new (Context) CXXBaseOrMemberInitializer(Context,
1537 : Context.getTrivialTypeSourceInfo(Base->getType(),
1538 : SourceLocation()),
1539 : SourceLocation(),
1540 : BaseInit.takeAs<Expr>(),
202: branch 7 taken
0: branch 8 not taken
1541 202: SourceLocation());
202: branch 2 taken
3: branch 3 taken
202: branch 5 taken
3: branch 6 taken
1542 202: AllToInit.push_back(CXXBaseInit);
1543 : }
1544 1018: }
1545 : }
1546 :
1547 : // non-static data members.
591: branch 3 taken
1032: branch 4 taken
1548 2655: for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1549 1032: E = ClassDecl->field_end(); Field != E; ++Field) {
27: branch 2 taken
564: branch 3 taken
1550 591: if ((*Field)->isAnonymousStructOrUnion()) {
27: branch 0 taken
0: branch 1 not taken
1551 27: if (const RecordType *FieldClassType =
1552 27: Field->getType()->getAs<RecordType>()) {
1553 : CXXRecordDecl *FieldClassDecl
1554 27: = cast<CXXRecordDecl>(FieldClassType->getDecl());
42: branch 3 taken
3: branch 4 taken
1555 72: for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1556 27: EA = FieldClassDecl->field_end(); FA != EA; FA++) {
24: branch 2 taken
18: branch 3 taken
1557 42: if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1558 : // 'Member' is the anonymous union field and 'AnonUnionMember' is
1559 : // set to the anonymous union data member used in the initializer
1560 : // list.
1561 24: Value->setMember(*Field);
1562 24: Value->setAnonUnionMember(*FA);
1563 24: AllToInit.push_back(Value);
1564 24: break;
1565 : }
1566 : }
1567 : }
1568 27: continue;
1569 : }
214: branch 2 taken
350: branch 3 taken
1570 564: if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1571 214: AllToInit.push_back(Value);
1572 214: continue;
1573 : }
1574 :
338: branch 4 taken
12: branch 5 taken
8: branch 6 taken
330: branch 7 taken
20: branch 8 taken
330: branch 9 taken
1575 350: if ((*Field)->getType()->isDependentType() || AnyErrors)
1576 20: continue;
1577 :
1578 330: QualType FT = Context.getBaseElementType((*Field)->getType());
78: branch 2 taken
252: branch 3 taken
1579 330: if (FT->getAs<RecordType>()) {
1580 : InitializedEntity InitEntity
1581 78: = InitializedEntity::InitializeMember(*Field);
1582 : InitializationKind InitKind
1583 78: = InitializationKind::CreateDefault(Constructor->getLocation());
1584 :
1585 78: InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1586 : OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1587 78: MultiExprArg(*this, 0, 0));
1588 78: MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6: branch 1 taken
72: branch 2 taken
1589 78: if (MemberInit.isInvalid()) {
1590 6: HadError = true;
1591 9: continue;
1592 : }
1593 :
1594 : // Don't attach synthesized member initializers in a dependent
1595 : // context; they'll be regenerated a template instantiation
1596 : // time.
3: branch 1 taken
69: branch 2 taken
1597 72: if (CurContext->isDependentContext())
1598 : continue;
1599 :
1600 : CXXBaseOrMemberInitializer *Member =
1601 : new (Context) CXXBaseOrMemberInitializer(Context,
1602 : *Field, SourceLocation(),
1603 : SourceLocation(),
1604 : MemberInit.takeAs<Expr>(),
69: branch 6 taken
0: branch 7 not taken
1605 69: SourceLocation());
1606 :
69: branch 2 taken
9: branch 3 taken
69: branch 5 taken
9: branch 6 taken
1607 69: AllToInit.push_back(Member);
1608 : }
4: branch 2 taken
248: branch 3 taken
1609 252: else if (FT->isReferenceType()) {
1610 : Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1611 : << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1612 4: << 0 << (*Field)->getDeclName();
1613 4: Diag((*Field)->getLocation(), diag::note_declared_at);
1614 4: HadError = true;
1615 : }
3: branch 1 taken
245: branch 2 taken
1616 248: else if (FT.isConstQualified()) {
1617 : Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1618 : << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1619 3: << 1 << (*Field)->getDeclName();
1620 3: Diag((*Field)->getLocation(), diag::note_declared_at);
1621 3: HadError = true;
1622 : }
1623 : }
1624 :
1625 1032: NumInitializers = AllToInit.size();
425: branch 0 taken
607: branch 1 taken
1626 1032: if (NumInitializers > 0) {
1627 425: Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1628 : CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1629 425: new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1630 :
1631 425: Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
846: branch 0 taken
425: branch 1 taken
1632 1271: for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1633 846: baseOrMemberInitializers[Idx] = AllToInit[Idx];
1634 : }
1635 :
1636 1032: return HadError;
1637 : }
1638 :
1639 36: static void *GetKeyForTopLevelField(FieldDecl *Field) {
1640 : // For anonymous unions, use the class declaration as the key.
8: branch 3 taken
28: branch 4 taken
1641 36: if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4: branch 2 taken
4: branch 3 taken
1642 8: if (RT->getDecl()->isAnonymousStructOrUnion())
1643 4: return static_cast<void *>(RT->getDecl());
1644 : }
1645 32: return static_cast<void *>(Field);
1646 : }
1647 :
1648 107: static void *GetKeyForBase(QualType BaseType) {
107: branch 2 taken
0: branch 3 not taken
1649 107: if (const RecordType *RT = BaseType->getAs<RecordType>())
1650 107: return (void *)RT;
1651 :
1652 0: assert(0 && "Unexpected base type!");
1653 : return 0;
1654 : }
1655 :
1656 : static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1657 325: bool MemberMaybeAnon = false) {
1658 : // For fields injected into the class via declaration of an anonymous union,
1659 : // use its anonymous union class declaration as the unique key.
251: branch 1 taken
74: branch 2 taken
1660 325: if (Member->isMemberInitializer()) {
1661 251: FieldDecl *Field = Member->getMember();
1662 :
1663 : // After SetBaseOrMemberInitializers call, Field is the anonymous union
1664 : // data member of the class. Data member used in the initializer list is
1665 : // in AnonUnionMember field.
30: branch 0 taken
221: branch 1 taken
4: branch 3 taken
26: branch 4 taken
4: branch 5 taken
247: branch 6 taken
1666 251: if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1667 4: Field = Member->getAnonUnionMember();
251: branch 2 taken
0: branch 3 not taken
1668 251: if (Field->getDeclContext()->isRecord()) {
1669 251: RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
26: branch 1 taken
225: branch 2 taken
1670 251: if (RD->isAnonymousStructOrUnion())
1671 26: return static_cast<void *>(RD);
1672 : }
1673 225: return static_cast<void *>(Field);
1674 : }
1675 :
1676 74: return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1677 : }
1678 :
1679 : /// ActOnMemInitializers - Handle the member initializers for a constructor.
1680 : void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1681 : SourceLocation ColonLoc,
1682 : MemInitTy **MemInits, unsigned NumMemInits,
1683 220: bool AnyErrors) {
0: branch 1 not taken
220: branch 2 taken
1684 220: if (!ConstructorDecl)
1685 0: return;
1686 :
1687 220: AdjustDeclIfTemplate(ConstructorDecl);
1688 :
1689 : CXXConstructorDecl *Constructor
1690 220: = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1691 :
2: branch 0 taken
218: branch 1 taken
1692 220: if (!Constructor) {
1693 2: Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1694 2: return;
1695 : }
1696 :
184: branch 1 taken
34: branch 2 taken
1697 218: if (!Constructor->isDependentContext()) {
1698 184: llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1699 184: bool err = false;
270: branch 0 taken
184: branch 1 taken
1700 454: for (unsigned i = 0; i < NumMemInits; i++) {
1701 : CXXBaseOrMemberInitializer *Member =
1702 270: static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1703 270: void *KeyToMember = GetKeyForMember(Member);
1704 270: CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
267: branch 0 taken
3: branch 1 taken
1705 270: if (!PrevMember) {
1706 267: PrevMember = Member;
1707 267: continue;
1708 : }
2: branch 1 taken
1: branch 2 taken
1709 3: if (FieldDecl *Field = Member->getMember())
1710 : Diag(Member->getSourceLocation(),
1711 : diag::error_multiple_mem_initialization)
1712 : << Field->getNameAsString()
1713 2: << Member->getSourceRange();
1714 : else {
1715 1: Type *BaseClass = Member->getBaseClass();
0: branch 0 not taken
1: branch 1 taken
1716 1: assert(BaseClass && "ActOnMemInitializers - neither field or base");
1717 : Diag(Member->getSourceLocation(),
1718 : diag::error_multiple_base_initialization)
1719 : << QualType(BaseClass, 0)
1720 1: << Member->getSourceRange();
1721 : }
1722 : Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1723 3: << 0;
1724 3: err = true;
1725 : }
1726 :
2: branch 0 taken
182: branch 1 taken
1727 184: if (err)
182: branch 1 taken
2: branch 2 taken
1728 184: return;
1729 : }
1730 :
1731 : SetBaseOrMemberInitializers(Constructor,
1732 : reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1733 216: NumMemInits, false, AnyErrors);
1734 :
34: branch 1 taken
182: branch 2 taken
1735 216: if (Constructor->isDependentContext())
1736 34: return;
1737 :
150: branch 1 taken
32: branch 2 taken
150: branch 4 taken
0: branch 5 not taken
150: branch 6 taken
32: branch 7 taken
1738 182: if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1739 : Diagnostic::Ignored &&
1740 : Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1741 : Diagnostic::Ignored)
1742 150: return;
1743 :
1744 : // Also issue warning if order of ctor-initializer list does not match order
1745 : // of 1) base class declarations and 2) order of non-static data members.
1746 32: llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1747 :
1748 : CXXRecordDecl *ClassDecl
1749 32: = cast<CXXRecordDecl>(Constructor->getDeclContext());
1750 : // Push virtual bases before others.
12: branch 0 taken
32: branch 1 taken
1751 44: for (CXXRecordDecl::base_class_iterator VBase =
1752 32: ClassDecl->vbases_begin(),
1753 32: E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1754 12: AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1755 :
27: branch 1 taken
32: branch 2 taken
1756 91: for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1757 32: E = ClassDecl->bases_end(); Base != E; ++Base) {
1758 : // Virtuals are alread in the virtual base list and are constructed
1759 : // first.
6: branch 1 taken
21: branch 2 taken
1760 27: if (Base->isVirtual())
1761 6: continue;
1762 21: AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1763 : }
1764 :
36: branch 3 taken
32: branch 4 taken
1765 100: for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1766 32: E = ClassDecl->field_end(); Field != E; ++Field)
1767 36: AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1768 :
1769 32: int Last = AllBaseOrMembers.size();
1770 32: int curIndex = 0;
1771 32: CXXBaseOrMemberInitializer *PrevMember = 0;
55: branch 0 taken
32: branch 1 taken
1772 87: for (unsigned i = 0; i < NumMemInits; i++) {
1773 : CXXBaseOrMemberInitializer *Member =
1774 55: static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1775 55: void *MemberInCtorList = GetKeyForMember(Member, true);
1776 :
97: branch 0 taken
10: branch 1 taken
1777 107: for (; curIndex < Last; curIndex++)
45: branch 1 taken
52: branch 2 taken
1778 97: if (MemberInCtorList == AllBaseOrMembers[curIndex])
1779 45: break;
10: branch 0 taken
45: branch 1 taken
1780 55: if (curIndex == Last) {
0: branch 0 not taken
10: branch 1 taken
1781 10: assert(PrevMember && "Member not in member list?!");
1782 : // Initializer as specified in ctor-initializer list is out of order.
1783 : // Issue a warning diagnostic.
6: branch 1 taken
4: branch 2 taken
1784 10: if (PrevMember->isBaseInitializer()) {
1785 : // Diagnostics is for an initialized base class.
1786 6: Type *BaseClass = PrevMember->getBaseClass();
1787 : Diag(PrevMember->getSourceLocation(),
1788 : diag::warn_base_initialized)
1789 6: << QualType(BaseClass, 0);
1790 : } else {
1791 4: FieldDecl *Field = PrevMember->getMember();
1792 : Diag(PrevMember->getSourceLocation(),
1793 : diag::warn_field_initialized)
1794 4: << Field->getNameAsString();
1795 : }
1796 : // Also the note!
2: branch 1 taken
8: branch 2 taken
1797 10: if (FieldDecl *Field = Member->getMember())
1798 : Diag(Member->getSourceLocation(),
1799 : diag::note_fieldorbase_initialized_here) << 0
1800 2: << Field->getNameAsString();
1801 : else {
1802 8: Type *BaseClass = Member->getBaseClass();
1803 : Diag(Member->getSourceLocation(),
1804 : diag::note_fieldorbase_initialized_here) << 1
1805 8: << QualType(BaseClass, 0);
1806 : }
15: branch 0 taken
0: branch 1 not taken
1807 15: for (curIndex = 0; curIndex < Last; curIndex++)
10: branch 1 taken
5: branch 2 taken
1808 15: if (MemberInCtorList == AllBaseOrMembers[curIndex])
1809 10: break;
1810 : }
1811 55: PrevMember = Member;
1812 32: }
1813 : }
1814 :
1815 : void
1816 91: Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1817 : // Ignore dependent destructors.
22: branch 1 taken
69: branch 2 taken
1818 91: if (Destructor->isDependentContext())
1819 22: return;
1820 :
1821 69: CXXRecordDecl *ClassDecl = Destructor->getParent();
1822 :
1823 : // Non-static data members.
45: branch 3 taken
69: branch 4 taken
1824 183: for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1825 69: E = ClassDecl->field_end(); I != E; ++I) {
1826 45: FieldDecl *Field = *I;
1827 :
1828 45: QualType FieldType = Context.getBaseElementType(Field->getType());
1829 :
1830 45: const RecordType* RT = FieldType->getAs<RecordType>();
41: branch 0 taken
4: branch 1 taken
1831 45: if (!RT)
1832 41: continue;
1833 :
1834 4: CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
0: branch 1 not taken
4: branch 2 taken
1835 4: if (FieldClassDecl->hasTrivialDestructor())
1836 0: continue;
1837 :
1838 4: const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1839 : MarkDeclarationReferenced(Destructor->getLocation(),
1840 4: const_cast<CXXDestructorDecl*>(Dtor));
1841 : }
1842 :
1843 : // Bases.
13: branch 1 taken
69: branch 2 taken
1844 151: for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1845 69: E = ClassDecl->bases_end(); Base != E; ++Base) {
1846 : // Ignore virtual bases.
1: branch 1 taken
12: branch 2 taken
1847 13: if (Base->isVirtual())
1848 1: continue;
1849 :
1850 : // Ignore trivial destructors.
1851 : CXXRecordDecl *BaseClassDecl
1852 12: = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
0: branch 1 not taken
12: branch 2 taken
1853 12: if (BaseClassDecl->hasTrivialDestructor())
1854 0: continue;
1855 :
1856 12: const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1857 : MarkDeclarationReferenced(Destructor->getLocation(),
1858 12: const_cast<CXXDestructorDecl*>(Dtor));
1859 : }
1860 :
1861 : // Virtual bases.
2: branch 1 taken
69: branch 2 taken
1862 140: for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1863 69: E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1864 : // Ignore trivial destructors.
1865 : CXXRecordDecl *BaseClassDecl
1866 2: = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
0: branch 1 not taken
2: branch 2 taken
1867 2: if (BaseClassDecl->hasTrivialDestructor())
1868 0: continue;
1869 :
1870 2: const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1871 : MarkDeclarationReferenced(Destructor->getLocation(),
1872 2: const_cast<CXXDestructorDecl*>(Dtor));
1873 : }
1874 : }
1875 :
1876 8047: void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
2: branch 1 taken
8045: branch 2 taken
1877 8047: if (!CDtorDecl)
1878 2: return;
1879 :
1880 8045: AdjustDeclIfTemplate(CDtorDecl);
1881 :
160: branch 0 taken
7885: branch 1 taken
1882 8045: if (CXXConstructorDecl *Constructor
1883 8045: = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1884 160: SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
1885 : }
1886 :
1887 : namespace {
1888 : /// PureVirtualMethodCollector - traverses a class and its superclasses
1889 : /// and determines if it has any pure virtual methods.
1890 4763: class PureVirtualMethodCollector {
1891 : ASTContext &Context;
1892 :
1893 : public:
1894 : typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1895 :
1896 : private:
1897 : MethodList Methods;
1898 :
1899 : void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1900 :
1901 : public:
1902 4763: PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1903 4763: : Context(Ctx) {
1904 :
1905 4763: MethodList List;
1906 4763: Collect(RD, List);
1907 :
1908 : // Copy the temporary list to methods, and make sure to ignore any
1909 : // null entries.
28: branch 1 taken
4763: branch 2 taken
1910 4791: for (size_t i = 0, e = List.size(); i != e; ++i) {
11: branch 1 taken
17: branch 2 taken
1911 28: if (List[i])
1912 11: Methods.push_back(List[i]);
1913 4763: }
1914 4763: }
1915 :
1916 4756: bool empty() const { return Methods.empty(); }
1917 :
1918 7: MethodList::const_iterator methods_begin() { return Methods.begin(); }
1919 7: MethodList::const_iterator methods_end() { return Methods.end(); }
1920 : };
1921 :
1922 : void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1923 4783: MethodList& Methods) {
1924 : // First, collect the pure virtual methods for the base classes.
972: branch 1 taken
4783: branch 2 taken
1925 10538: for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1926 4783: BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
899: branch 3 taken
73: branch 4 taken
1927 972: if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1928 899: const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
899: branch 0 taken
0: branch 1 not taken
20: branch 3 taken
879: branch 4 taken
20: branch 5 taken
879: branch 6 taken
1929 899: if (BaseDecl && BaseDecl->isAbstract())
1930 20: Collect(BaseDecl, Methods);
1931 : }
1932 : }
1933 :
1934 : // Next, zero out any pure virtual methods that this class overrides.
1935 : typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1936 :
1937 4783: MethodSetTy OverriddenMethods;
1938 4783: size_t MethodsSize = Methods.size();
1939 :
26172: branch 4 taken
4783: branch 5 taken
1940 30955: for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1941 : i != e; ++i) {
1942 : // Traverse the record, looking for methods.
17926: branch 2 taken
8246: branch 3 taken
1943 26172: if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1944 : // If the method is pure virtual, add it to the methods vector.
28: branch 1 taken
17898: branch 2 taken
1945 17926: if (MD->isPure())
1946 28: Methods.push_back(MD);
1947 :
1948 : // Record all the overridden methods in our set.
139: branch 1 taken
17926: branch 2 taken
1949 35991: for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1950 17926: E = MD->end_overridden_methods(); I != E; ++I) {
1951 : // Keep track of the overridden methods.
1952 139: OverriddenMethods.insert(*I);
1953 : }
1954 : }
1955 : }
1956 :
1957 : // Now go through the methods and zero out all the ones we know are
1958 : // overridden.
28: branch 0 taken
4783: branch 1 taken
1959 4811: for (size_t i = 0, e = MethodsSize; i != e; ++i) {
17: branch 2 taken
11: branch 3 taken
1960 28: if (OverriddenMethods.count(Methods[i]))
1961 17: Methods[i] = 0;
1962 4783: }
1963 :
1964 4783: }
1965 : }
1966 :
1967 :
1968 : bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1969 : unsigned DiagID, AbstractDiagSelID SelID,
1970 43578: const CXXRecordDecl *CurrentRD) {
652: branch 0 taken
42926: branch 1 taken
1971 43578: if (SelID == -1)
1972 : return RequireNonAbstractType(Loc, T,
1973 652: PDiag(DiagID), CurrentRD);
1974 : else
1975 : return RequireNonAbstractType(Loc, T,
1976 42926: PDiag(DiagID) << SelID, CurrentRD);
1977 : }
1978 :
1979 : bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1980 : const PartialDiagnostic &PD,
1981 44226: const CXXRecordDecl *CurrentRD) {
23936: branch 1 taken
20290: branch 2 taken
1982 44226: if (!getLangOptions().CPlusPlus)
1983 23936: return false;
1984 :
621: branch 1 taken
19669: branch 2 taken
1985 20290: if (const ArrayType *AT = Context.getAsArrayType(T))
1986 : return RequireNonAbstractType(Loc, AT->getElementType(), PD,
1987 621: CurrentRD);
1988 :
2512: branch 2 taken
17157: branch 3 taken
1989 19669: if (const PointerType *PT = T->getAs<PointerType>()) {
1990 : // Find the innermost pointer type.
975: branch 3 taken
2512: branch 4 taken
1991 4462: while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
1992 975: PT = T;
1993 :
27: branch 2 taken
2485: branch 3 taken
1994 2512: if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
1995 27: return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
1996 : }
1997 :
1998 19642: const RecordType *RT = T->getAs<RecordType>();
17342: branch 0 taken
2300: branch 1 taken
1999 19642: if (!RT)
2000 17342: return false;
2001 :
2002 2300: const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2003 :
90: branch 0 taken
2210: branch 1 taken
84: branch 2 taken
6: branch 3 taken
2004 2300: if (CurrentRD && CurrentRD != RD)
2005 84: return false;
2006 :
2007 : // FIXME: is this reasonable? It matches current behavior, but....
122: branch 1 taken
2094: branch 2 taken
2008 2216: if (!RD->getDefinition(Context))
2009 122: return false;
2010 :
2071: branch 1 taken
23: branch 2 taken
2011 2094: if (!RD->isAbstract())
2012 2071: return false;
2013 :
2014 23: Diag(Loc, PD) << RD->getDeclName();
2015 :
2016 : // Check if we've already emitted the list of pure virtual functions for this
2017 : // class.
18: branch 1 taken
5: branch 2 taken
16: branch 5 taken
2: branch 6 taken
16: branch 7 taken
7: branch 8 taken
2018 23: if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2019 16: return true;
2020 :
2021 7: PureVirtualMethodCollector Collector(Context, RD);
2022 :
7: branch 0 taken
7: branch 1 taken
2023 14: for (PureVirtualMethodCollector::MethodList::const_iterator I =
2024 7: Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2025 7: const CXXMethodDecl *MD = *I;
2026 :
2027 : Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
2028 7: MD->getDeclName();
2029 : }
2030 :
5: branch 1 taken
2: branch 2 taken
2031 7: if (!PureVirtualClassDiagSet)
2032 5: PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2033 7: PureVirtualClassDiagSet->insert(RD);
2034 :
2035 7: return true;
2036 : }
2037 :
2038 : namespace {
2039 : class AbstractClassUsageDiagnoser
2040 : : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2041 : Sema &SemaRef;
2042 : CXXRecordDecl *AbstractClass;
2043 :
2044 2030: bool VisitDeclContext(const DeclContext *DC) {
2045 2030: bool Invalid = false;
2046 :
6154: branch 3 taken
2030: branch 4 taken
2047 10214: for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2048 2030: E = DC->decls_end(); I != E; ++I)
2049 6154: Invalid |= Visit(*I);
2050 :
2051 2030: return Invalid;
2052 : }
2053 :
2054 : public:
2055 35: AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2056 35: : SemaRef(SemaRef), AbstractClass(ac) {
2057 35: Visit(SemaRef.Context.getTranslationUnitDecl());
2058 35: }
2059 :
2060 4064: bool VisitFunctionDecl(const FunctionDecl *FD) {
388: branch 1 taken
3676: branch 2 taken
2061 4064: if (FD->isThisDeclarationADefinition()) {
2062 : // No need to do the check if we're in a definition, because it requires
2063 : // that the return/param types are complete.
2064 : // because that requires
388: branch 0 taken
0: branch 1 not taken
2065 388: return VisitDeclContext(FD);
2066 : }
2067 :
2068 : // Check the return type.
2069 3676: QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2070 : bool Invalid =
2071 : SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2072 : diag::err_abstract_type_in_decl,
2073 : Sema::AbstractReturnType,
2074 3676: AbstractClass);
2075 :
1730: branch 1 taken
3676: branch 2 taken
2076 9082: for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2077 3676: E = FD->param_end(); I != E; ++I) {
2078 1730: const ParmVarDecl *VD = *I;
2079 : Invalid |=
2080 : SemaRef.RequireNonAbstractType(VD->getLocation(),
2081 : VD->getOriginalType(),
2082 : diag::err_abstract_type_in_decl,
2083 : Sema::AbstractParamType,
2084 1730: AbstractClass);
2085 : }
2086 :
2087 3676: return Invalid;
2088 : }
2089 :
2090 2125: bool VisitDecl(const Decl* D) {
1642: branch 1 taken
483: branch 2 taken
2091 2125: if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2092 1642: return VisitDeclContext(DC);
2093 :
2094 483: return false;
2095 : }
2096 : };
2097 : }
2098 :
2099 : /// \brief Perform semantic checks on a class definition that has been
2100 : /// completing, introducing implicitly-declared members, checking for
2101 : /// abstract types, etc.
2102 4835: void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4835: branch 0 taken
0: branch 1 not taken
48: branch 3 taken
4787: branch 4 taken
48: branch 5 taken
4787: branch 6 taken
2103 4835: if (!Record || Record->isInvalidDecl())
2104 48: return;
2105 :
3879: branch 1 taken
908: branch 2 taken
2106 4787: if (!Record->isDependentType())
2107 3879: AddImplicitlyDeclaredMembersToClass(Record);
2108 :
0: branch 1 not taken
4787: branch 2 taken
2109 4787: if (Record->isInvalidDecl())
2110 0: return;
2111 :
2112 : // Set access bits correctly on the directly-declared conversions.
2113 4787: UnresolvedSetImpl *Convs = Record->getConversionFunctions();
247: branch 4 taken
4787: branch 5 taken
2114 5034: for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2115 247: Convs->setAccess(I, (*I)->getAccess());
2116 :
4756: branch 1 taken
31: branch 2 taken
2117 4787: if (!Record->isAbstract()) {
2118 : // Collect all the pure virtual methods and see if this is an abstract
2119 : // class after all.
2120 4756: PureVirtualMethodCollector Collector(Context, Record);
4: branch 1 taken
4752: branch 2 taken
2121 4756: if (!Collector.empty())
2122 4: Record->setAbstract(true);
2123 : }
2124 :
35: branch 1 taken
4752: branch 2 taken
2125 4787: if (Record->isAbstract())
2126 35: (void)AbstractClassUsageDiagnoser(*this, Record);
2127 : }
2128 :
2129 : void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2130 : DeclPtrTy TagDecl,
2131 : SourceLocation LBrac,
2132 3394: SourceLocation RBrac) {
0: branch 1 not taken
3394: branch 2 taken
2133 3394: if (!TagDecl)
2134 0: return;
2135 :
2136 3394: AdjustDeclIfTemplate(TagDecl);
2137 :
2138 : ActOnFields(S, RLoc, TagDecl,
2139 : (DeclPtrTy*)FieldCollector->getCurFields(),
2140 3394: FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
2141 :
2142 : CheckCompletedCXXClass(
2143 3394: dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2144 : }
2145 :
2146 : /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2147 : /// special functions, such as the default constructor, copy
2148 : /// constructor, or destructor, to the given C++ class (C++
2149 : /// [special]p1). This routine can only be executed just before the
2150 : /// definition of the class is complete.
2151 3879: void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
2152 : CanQualType ClassType
2153 3879: = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2154 :
2155 : // FIXME: Implicit declarations have exception specifications, which are
2156 : // the union of the specifications of the implicitly called functions.
2157 :
3401: branch 1 taken
478: branch 2 taken
2158 3879: if (!ClassDecl->hasUserDeclaredConstructor()) {
2159 : // C++ [class.ctor]p5:
2160 : // A default constructor for a class X is a constructor of class X
2161 : // that can be called without an argument. If there is no
2162 : // user-declared constructor for class X, a default constructor is
2163 : // implicitly declared. An implicitly-declared default constructor
2164 : // is an inline public member of its class.
2165 : DeclarationName Name
2166 3401: = Context.DeclarationNames.getCXXConstructorName(ClassType);
2167 : CXXConstructorDecl *DefaultCon =
2168 : CXXConstructorDecl::Create(Context, ClassDecl,
2169 : ClassDecl->getLocation(), Name,
2170 : Context.getFunctionType(Context.VoidTy,
2171 : 0, 0, false, 0),
2172 : /*TInfo=*/0,
2173 : /*isExplicit=*/false,
2174 : /*isInline=*/true,
2175 3401: /*isImplicitlyDeclared=*/true);
2176 3401: DefaultCon->setAccess(AS_public);
2177 3401: DefaultCon->setImplicit();
2178 3401: DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2179 3401: ClassDecl->addDecl(DefaultCon);
2180 : }
2181 :
3825: branch 1 taken
54: branch 2 taken
2182 3879: if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2183 : // C++ [class.copy]p4:
2184 : // If the class definition does not explicitly declare a copy
2185 : // constructor, one is declared implicitly.
2186 :
2187 : // C++ [class.copy]p5:
2188 : // The implicitly-declared copy constructor for a class X will
2189 : // have the form
2190 : //
2191 : // X::X(const X&)
2192 : //
2193 : // if
2194 3825: bool HasConstCopyConstructor = true;
2195 :
2196 : // -- each direct or virtual base class B of X has a copy
2197 : // constructor whose first parameter is of type const B& or
2198 : // const volatile B&, and
4694: branch 1 taken
3: branch 2 taken
872: branch 4 taken
3822: branch 5 taken
872: branch 6 taken
3825: branch 7 taken
2199 4697: for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2200 : HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2201 : const CXXRecordDecl *BaseClassDecl
2202 872: = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2203 : HasConstCopyConstructor
2204 872: = BaseClassDecl->hasConstCopyConstructor(Context);
2205 : }
2206 :
2207 : // -- for all the nonstatic data members of X that are of a
2208 : // class type M (or array thereof), each such class type
2209 : // has a copy constructor whose first parameter is of type
2210 : // const M& or const volatile M&.
5312: branch 2 taken
4: branch 3 taken
1491: branch 6 taken
3821: branch 7 taken
1491: branch 8 taken
3825: branch 9 taken
2211 5316: for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2212 : HasConstCopyConstructor && Field != ClassDecl->field_end();
2213 : ++Field) {
2214 1491: QualType FieldType = (*Field)->getType();
76: branch 1 taken
1415: branch 2 taken
2215 1491: if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2216 76: FieldType = Array->getElementType();
160: branch 2 taken
1331: branch 3 taken
2217 1491: if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2218 : const CXXRecordDecl *FieldClassDecl
2219 160: = cast<CXXRecordDecl>(FieldClassType->getDecl());
2220 : HasConstCopyConstructor
2221 160: = FieldClassDecl->hasConstCopyConstructor(Context);
2222 : }
2223 : }
2224 :
2225 : // Otherwise, the implicitly declared copy constructor will have
2226 : // the form
2227 : //
2228 : // X::X(X&)
2229 3825: QualType ArgType = ClassType;
3821: branch 0 taken
4: branch 1 taken
2230 3825: if (HasConstCopyConstructor)
2231 3821: ArgType = ArgType.withConst();
2232 3825: ArgType = Context.getLValueReferenceType(ArgType);
2233 :
2234 : // An implicitly-declared copy constructor is an inline public
2235 : // member of its class.
2236 : DeclarationName Name
2237 3825: = Context.DeclarationNames.getCXXConstructorName(ClassType);
2238 : CXXConstructorDecl *CopyConstructor
2239 : = CXXConstructorDecl::Create(Context, ClassDecl,
2240 : ClassDecl->getLocation(), Name,
2241 : Context.getFunctionType(Context.VoidTy,
2242 : &ArgType, 1,
2243 : false, 0),
2244 : /*TInfo=*/0,
2245 : /*isExplicit=*/false,
2246 : /*isInline=*/true,
2247 3825: /*isImplicitlyDeclared=*/true);
2248 3825: CopyConstructor->setAccess(AS_public);
2249 3825: CopyConstructor->setImplicit();
2250 3825: CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2251 :
2252 : // Add the parameter to the constructor.
2253 : ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2254 : ClassDecl->getLocation(),
2255 : /*IdentifierInfo=*/0,
2256 : ArgType, /*TInfo=*/0,
3825: branch 1 taken
0: branch 2 not taken
2257 3825: VarDecl::None, 0);
2258 3825: CopyConstructor->setParams(Context, &FromParam, 1);
2259 3825: ClassDecl->addDecl(CopyConstructor);
2260 : }
2261 :
3860: branch 1 taken
19: branch 2 taken
2262 3879: if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2263 : // Note: The following rules are largely analoguous to the copy
2264 : // constructor rules. Note that virtual bases are not taken into account
2265 : // for determining the argument type of the operator. Note also that
2266 : // operators taking an object instead of a reference are allowed.
2267 : //
2268 : // C++ [class.copy]p10:
2269 : // If the class definition does not explicitly declare a copy
2270 : // assignment operator, one is declared implicitly.
2271 : // The implicitly-defined copy assignment operator for a class X
2272 : // will have the form
2273 : //
2274 : // X& X::operator=(const X&)
2275 : //
2276 : // if
2277 3860: bool HasConstCopyAssignment = true;
2278 :
2279 : // -- each direct base class B of X has a copy assignment operator
2280 : // whose parameter is of type const B&, const volatile B& or B,
2281 : // and
4728: branch 1 taken
2: branch 2 taken
870: branch 4 taken
3858: branch 5 taken
870: branch 6 taken
3860: branch 7 taken
2282 9460: for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2283 : HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2284 : assert(!Base->getType()->isDependentType() &&
870: branch 3 taken
0: branch 4 not taken
2285 870: "Cannot generate implicit members for class with dependent bases.");
2286 : const CXXRecordDecl *BaseClassDecl
2287 870: = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2288 870: const CXXMethodDecl *MD = 0;
2289 : HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2290 870: MD);
2291 : }
2292 :
2293 : // -- for all the nonstatic data members of X that are of a class
2294 : // type M (or array thereof), each such class type has a copy
2295 : // assignment operator whose parameter is of type const M&,
2296 : // const volatile M& or M.
5345: branch 2 taken
4: branch 3 taken
1489: branch 6 taken
3856: branch 7 taken
1489: branch 8 taken
3860: branch 9 taken
2297 5349: for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2298 : HasConstCopyAssignment && Field != ClassDecl->field_end();
2299 : ++Field) {
2300 1489: QualType FieldType = (*Field)->getType();
71: branch 1 taken
1418: branch 2 taken
2301 1489: if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2302 71: FieldType = Array->getElementType();
160: branch 2 taken
1329: branch 3 taken
2303 1489: if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2304 : const CXXRecordDecl *FieldClassDecl
2305 160: = cast<CXXRecordDecl>(FieldClassType->getDecl());
2306 160: const CXXMethodDecl *MD = 0;
2307 : HasConstCopyAssignment
2308 160: = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2309 : }
2310 : }
2311 :
2312 : // Otherwise, the implicitly declared copy assignment operator will
2313 : // have the form
2314 : //
2315 : // X& X::operator=(X&)
2316 3860: QualType ArgType = ClassType;
2317 3860: QualType RetType = Context.getLValueReferenceType(ArgType);
3856: branch 0 taken
4: branch 1 taken
2318 3860: if (HasConstCopyAssignment)
2319 3856: ArgType = ArgType.withConst();
2320 3860: ArgType = Context.getLValueReferenceType(ArgType);
2321 :
2322 : // An implicitly-declared copy assignment operator is an inline public
2323 : // member of its class.
2324 : DeclarationName Name =
2325 3860: Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2326 : CXXMethodDecl *CopyAssignment =
2327 : CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2328 : Context.getFunctionType(RetType, &ArgType, 1,
2329 : false, 0),
2330 3860: /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2331 3860: CopyAssignment->setAccess(AS_public);
2332 3860: CopyAssignment->setImplicit();
2333 3860: CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2334 3860: CopyAssignment->setCopyAssignment(true);
2335 :
2336 : // Add the parameter to the operator.
2337 : ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2338 : ClassDecl->getLocation(),
2339 : /*IdentifierInfo=*/0,
2340 : ArgType, /*TInfo=*/0,
3860: branch 1 taken
0: branch 2 not taken
2341 3860: VarDecl::None, 0);
2342 3860: CopyAssignment->setParams(Context, &FromParam, 1);
2343 :
2344 : // Don't call addedAssignmentOperator. There is no way to distinguish an
2345 : // implicit from an explicit assignment operator.
2346 3860: ClassDecl->addDecl(CopyAssignment);
2347 3860: AddOverriddenMethods(ClassDecl, CopyAssignment);
2348 : }
2349 :
3724: branch 1 taken
155: branch 2 taken
2350 3879: if (!ClassDecl->hasUserDeclaredDestructor()) {
2351 : // C++ [class.dtor]p2:
2352 : // If a class has no user-declared destructor, a destructor is
2353 : // declared implicitly. An implicitly-declared destructor is an
2354 : // inline public member of its class.
2355 : DeclarationName Name
2356 3724: = Context.DeclarationNames.getCXXDestructorName(ClassType);
2357 : CXXDestructorDecl *Destructor
2358 : = CXXDestructorDecl::Create(Context, ClassDecl,
2359 : ClassDecl->getLocation(), Name,
2360 : Context.getFunctionType(Context.VoidTy,
2361 : 0, 0, false, 0),
2362 : /*isInline=*/true,
2363 3724: /*isImplicitlyDeclared=*/true);
2364 3724: Destructor->setAccess(AS_public);
2365 3724: Destructor->setImplicit();
2366 3724: Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2367 3724: ClassDecl->addDecl(Destructor);
2368 :
2369 3724: AddOverriddenMethods(ClassDecl, Destructor);
2370 : }
2371 3879: }
2372 :
2373 67: void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2374 67: Decl *D = TemplateD.getAs<Decl>();
0: branch 0 not taken
67: branch 1 taken
2375 67: if (!D)
2376 0: return;
2377 :
2378 67: TemplateParameterList *Params = 0;
67: branch 1 taken
0: branch 2 not taken
2379 67: if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2380 67: Params = Template->getTemplateParameters();
0: branch 0 not taken
0: branch 1 not taken
2381 0: else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2382 0: = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2383 0: Params = PartialSpec->getTemplateParameters();
2384 : else
2385 0: return;
2386 :
72: branch 1 taken
67: branch 2 taken
2387 206: for (TemplateParameterList::iterator Param = Params->begin(),
2388 67: ParamEnd = Params->end();
2389 : Param != ParamEnd; ++Param) {
2390 72: NamedDecl *Named = cast<NamedDecl>(*Param);
72: branch 2 taken
0: branch 3 not taken
2391 72: if (Named->getDeclName()) {
2392 72: S->AddDecl(DeclPtrTy::make(Named));
2393 72: IdResolver.AddDecl(Named);
2394 : }
2395 : }
2396 : }
2397 :
2398 25: void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
25: branch 1 taken
0: branch 2 not taken
2399 25: if (!RecordD) return;
2400 25: AdjustDeclIfTemplate(RecordD);
2401 25: CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
25: branch 0 taken
0: branch 1 not taken
2402 25: PushDeclContext(S, Record);
2403 : }
2404 :
2405 25: void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
25: branch 1 taken
0: branch 2 not taken
2406 25: if (!RecordD) return;
2407 25: PopDeclContext();
2408 : }
2409 :
2410 : /// ActOnStartDelayedCXXMethodDeclaration - We have completed
2411 : /// parsing a top-level (non-nested) C++ class, and we are now
2412 : /// parsing those parts of the given Method declaration that could
2413 : /// not be parsed earlier (C++ [class.mem]p2), such as default
2414 : /// arguments. This action should enter the scope of the given
2415 : /// Method declaration as if we had just parsed the qualified method
2416 : /// name. However, it should not bring the parameters into scope;
2417 : /// that will be performed by ActOnDelayedCXXMethodParameter.
2418 68: void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2419 68: }
2420 :
2421 : /// ActOnDelayedCXXMethodParameter - We've already started a delayed
2422 : /// C++ method declaration. We're (re-)introducing the given
2423 : /// function parameter into scope for use in parsing later parts of
2424 : /// the method declaration. For example, we could see an
2425 : /// ActOnParamDefaultArgument event for this parameter.
2426 107: void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
0: branch 1 not taken
107: branch 2 taken
2427 107: if (!ParamD)
2428 0: return;
2429 :
2430 107: ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2431 :
2432 : // If this parameter has an unparsed default argument, clear it out
2433 : // to make way for the parsed default argument.
81: branch 1 taken
26: branch 2 taken
2434 107: if (Param->hasUnparsedDefaultArg())
2435 81: Param->setDefaultArg(0);
2436 :
2437 107: S->AddDecl(DeclPtrTy::make(Param));
81: branch 2 taken
26: branch 3 taken
2438 107: if (Param->getDeclName())
2439 81: IdResolver.AddDecl(Param);
2440 : }
2441 :
2442 : /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2443 : /// processing the delayed method declaration for Method. The method
2444 : /// declaration is now considered finished. There may be a separate
2445 : /// ActOnStartOfFunctionDef action later (not necessarily
2446 : /// immediately!) for this method, if it was also defined inside the
2447 : /// class body.
2448 68: void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
0: branch 1 not taken
68: branch 2 taken
2449 68: if (!MethodD)
2450 0: return;
2451 :
2452 68: AdjustDeclIfTemplate(MethodD);
2453 :
2454 68: FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2455 :
2456 : // Now that we have our default arguments, check the constructor
2457 : // again. It could produce additional diagnostics or affect whether
2458 : // the class has implicitly-declared destructors, among other
2459 : // things.
35: branch 1 taken
33: branch 2 taken
2460 68: if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2461 35: CheckConstructor(Constructor);
2462 :
2463 : // Check the default arguments, which we may have added.
65: branch 1 taken
3: branch 2 taken
2464 68: if (!Method->isInvalidDecl())
2465 65: CheckCXXDefaultArguments(Method);
2466 : }
2467 :
2468 : /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2469 : /// the well-formedness of the constructor declarator @p D with type @p
2470 : /// R. If there are any errors in the declarator, this routine will
2471 : /// emit diagnostics and set the invalid bit to true. In any case, the type
2472 : /// will be updated to reflect a well-formed type for the constructor and
2473 : /// returned.
2474 : QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2475 653: FunctionDecl::StorageClass &SC) {
2476 653: bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2477 :
2478 : // C++ [class.ctor]p3:
2479 : // A constructor shall not be virtual (10.3) or static (9.4). A
2480 : // constructor can be invoked for a const, volatile or const
2481 : // volatile object. A constructor shall not be declared const,
2482 : // volatile, or const volatile (9.3.2).
2: branch 0 taken
651: branch 1 taken
2483 653: if (isVirtual) {
2: branch 1 taken
0: branch 2 not taken
2484 2: if (!D.isInvalidType())
2485 : Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2486 : << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2487 2: << SourceRange(D.getIdentifierLoc());
2488 2: D.setInvalidType();
2489 : }
1: branch 0 taken
652: branch 1 taken
2490 653: if (SC == FunctionDecl::Static) {
1: branch 1 taken
0: branch 2 not taken
2491 1: if (!D.isInvalidType())
2492 : Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2493 : << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2494 1: << SourceRange(D.getIdentifierLoc());
2495 1: D.setInvalidType();
2496 1: SC = FunctionDecl::None;
2497 : }
2498 :
2499 653: DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1: branch 0 taken
652: branch 1 taken
2500 653: if (FTI.TypeQuals != 0) {
1: branch 0 taken
0: branch 1 not taken
2501 1: if (FTI.TypeQuals & Qualifiers::Const)
2502 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2503 1: << "const" << SourceRange(D.getIdentifierLoc());
0: branch 0 not taken
1: branch 1 taken
2504 1: if (FTI.TypeQuals & Qualifiers::Volatile)
2505 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2506 0: << "volatile" << SourceRange(D.getIdentifierLoc());
0: branch 0 not taken
1: branch 1 taken
2507 1: if (FTI.TypeQuals & Qualifiers::Restrict)
2508 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2509 0: << "restrict" << SourceRange(D.getIdentifierLoc());
2510 : }
2511 :
2512 : // Rebuild the function type "R" without any type qualifiers (in
2513 : // case any of the errors above fired) and with "void" as the
2514 : // return type, since constructors don't have return types. We
2515 : // *always* have to do this, because GetTypeForDeclarator will
2516 : // put in a result type of "int" when none was specified.
2517 653: const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2518 : return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2519 : Proto->getNumArgs(),
2520 653: Proto->isVariadic(), 0);
2521 : }
2522 :
2523 : /// CheckConstructor - Checks a fully-formed constructor for
2524 : /// well-formedness, issuing any diagnostics required. Returns true if
2525 : /// the constructor declarator is invalid.
2526 798: void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2527 : CXXRecordDecl *ClassDecl
2528 798: = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
0: branch 0 not taken
798: branch 1 taken
2529 798: if (!ClassDecl)
2530 0: return Constructor->setInvalidDecl();
2531 :
2532 : // C++ [class.copy]p3:
2533 : // A declaration of a constructor for a class X is ill-formed if
2534 : // its first parameter is of type (optionally cv-qualified) X and
2535 : // either there are no other parameters or else all other
2536 : // parameters have default arguments.
796: branch 1 taken
2: branch 2 taken
415: branch 4 taken
381: branch 5 taken
55: branch 7 taken
360: branch 8 taken
29: branch 11 taken
26: branch 12 taken
336: branch 14 taken
74: branch 15 taken
336: branch 16 taken
462: branch 17 taken
2537 798: if (!Constructor->isInvalidDecl() &&
2538 : ((Constructor->getNumParams() == 1) ||
2539 : (Constructor->getNumParams() > 1 &&
2540 : Constructor->getParamDecl(1)->hasDefaultArg())) &&
2541 : Constructor->getTemplateSpecializationKind()
2542 : != TSK_ImplicitInstantiation) {
2543 336: QualType ParamType = Constructor->getParamDecl(0)->getType();
2544 336: QualType ClassTy = Context.getTagDeclType(ClassDecl);
4: branch 4 taken
332: branch 5 taken
2545 336: if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2546 4: SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2547 : Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2548 4: << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2549 :
2550 : // FIXME: Rather that making the constructor invalid, we should endeavor
2551 : // to fix the type.
2552 4: Constructor->setInvalidDecl();
2553 : }
2554 : }
2555 :
2556 : // Notify the class that we've added a constructor.
2557 798: ClassDecl->addedConstructor(Context, Constructor);
2558 : }
2559 :
2560 : /// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2561 : /// issuing any diagnostics required. Returns true on error.
2562 205: bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2563 205: CXXRecordDecl *RD = Destructor->getParent();
2564 :
64: branch 1 taken
141: branch 2 taken
2565 205: if (Destructor->isVirtual()) {
2566 64: SourceLocation Loc;
2567 :
46: branch 1 taken
18: branch 2 taken
2568 64: if (!Destructor->isImplicit())
2569 46: Loc = Destructor->getLocation();
2570 : else
2571 18: Loc = RD->getLocation();
2572 :
2573 : // If we have a virtual destructor, look up the deallocation function
2574 64: FunctionDecl *OperatorDelete = 0;
2575 : DeclarationName Name =
2576 64: Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6: branch 1 taken
58: branch 2 taken
2577 64: if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2578 6: return true;
2579 :
2580 58: Destructor->setOperatorDelete(OperatorDelete);
2581 : }
2582 :
2583 199: return false;
2584 : }
2585 :
2586 : static inline bool
2587 2: FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2588 : return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2589 : FTI.ArgInfo[0].Param &&
2: branch 0 taken
0: branch 1 not taken
1: branch 2 taken
1: branch 3 taken
1: branch 4 taken
0: branch 5 not taken
1: branch 7 taken
0: branch 8 not taken
1: branch 13 taken
0: branch 14 not taken
2590 2: FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2591 : }
2592 :
2593 : /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2594 : /// the well-formednes of the destructor declarator @p D with type @p
2595 : /// R. If there are any errors in the declarator, this routine will
2596 : /// emit diagnostics and set the declarator to invalid. Even if this happens,
2597 : /// will be updated to reflect a well-formed type for the destructor and
2598 : /// returned.
2599 : QualType Sema::CheckDestructorDeclarator(Declarator &D,
2600 181: FunctionDecl::StorageClass& SC) {
2601 : // C++ [class.dtor]p1:
2602 : // [...] A typedef-name that names a class is a class-name
2603 : // (7.1.3); however, a typedef-name that names a class shall not
2604 : // be used as the identifier in the declarator for a destructor
2605 : // declaration.
2606 181: QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
1: branch 1 taken
180: branch 2 taken
2607 181: if (isa<TypedefType>(DeclaratorType)) {
2608 : Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2609 1: << DeclaratorType;
2610 1: D.setInvalidType();
2611 : }
2612 :
2613 : // C++ [class.dtor]p2:
2614 : // A destructor is used to destroy objects of its class type. A
2615 : // destructor takes no parameters, and no return type can be
2616 : // specified for it (not even void). The address of a destructor
2617 : // shall not be taken. A destructor shall not be static. A
2618 : // destructor can be invoked for a const, volatile or const
2619 : // volatile object. A destructor shall not be declared const,
2620 : // volatile or const volatile (9.3.2).
1: branch 0 taken
180: branch 1 taken
2621 181: if (SC == FunctionDecl::Static) {
1: branch 1 taken
0: branch 2 not taken
2622 1: if (!D.isInvalidType())
2623 : Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2624 : << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2625 1: << SourceRange(D.getIdentifierLoc());
2626 1: SC = FunctionDecl::None;
2627 1: D.setInvalidType();
2628 : }
2: branch 2 taken
179: branch 3 taken
1: branch 5 taken
1: branch 6 taken
1: branch 7 taken
180: branch 8 taken
2629 181: if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2630 : // Destructors don't have return types, but the parser will
2631 : // happily parse something like:
2632 : //
2633 : // class X {
2634 : // float ~X();
2635 : // };
2636 : //
2637 : // The return type will be eliminated later.
2638 : Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2639 : << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2640 1: << SourceRange(D.getIdentifierLoc());
2641 : }
2642 :
2643 181: DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1: branch 0 taken
180: branch 1 taken
0: branch 3 not taken
1: branch 4 taken
0: branch 5 not taken
181: branch 6 taken
2644 181: if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
0: branch 0 not taken
0: branch 1 not taken
2645 0: if (FTI.TypeQuals & Qualifiers::Const)
2646 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2647 0: << "const" << SourceRange(D.getIdentifierLoc());
0: branch 0 not taken
0: branch 1 not taken
2648 0: if (FTI.TypeQuals & Qualifiers::Volatile)
2649 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2650 0: << "volatile" << SourceRange(D.getIdentifierLoc());
0: branch 0 not taken
0: branch 1 not taken
2651 0: if (FTI.TypeQuals & Qualifiers::Restrict)
2652 : Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2653 0: << "restrict" << SourceRange(D.getIdentifierLoc());
2654 0: D.setInvalidType();
2655 : }
2656 :
2657 : // Make sure we don't have any parameters.
2: branch 0 taken
179: branch 1 taken
1: branch 3 taken
1: branch 4 taken
1: branch 5 taken
180: branch 6 taken
2658 181: if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2659 1: Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2660 :
2661 : // Delete the parameters.
2662 1: FTI.freeArgs();
2663 1: D.setInvalidType();
2664 : }
2665 :
2666 : // Make sure the destructor isn't variadic.
1: branch 0 taken
180: branch 1 taken
2667 181: if (FTI.isVariadic) {
2668 1: Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2669 1: D.setInvalidType();
2670 : }
2671 :
2672 : // Rebuild the function type "R" without any type qualifiers or
2673 : // parameters (in case any of the errors above fired) and with
2674 : // "void" as the return type, since destructors don't have return
2675 : // types. We *always* have to do this, because GetTypeForDeclarator
2676 : // will put in a result type of "int" when none was specified.
2677 181: return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
2678 : }
2679 :
2680 : /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2681 : /// well-formednes of the conversion function declarator @p D with
2682 : /// type @p R. If there are any errors in the declarator, this routine
2683 : /// will emit diagnostics and return true. Otherwise, it will return
2684 : /// false. Either way, the type @p R will be updated to reflect a
2685 : /// well-formed type for the conversion operator.
2686 : void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2687 254: FunctionDecl::StorageClass& SC) {
2688 : // C++ [class.conv.fct]p1:
2689 : // Neither parameter types nor return type can be specified. The
2690 : // type of a conversion function (8.3.5) is "function taking no
2691 : // parameter returning conversion-type-id."
0: branch 0 not taken
254: branch 1 taken
2692 254: if (SC == FunctionDecl::Static) {
0: branch 1 not taken
0: branch 2 not taken
2693 0: if (!D.isInvalidType())
2694 : Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2695 : << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2696 0: << SourceRange(D.getIdentifierLoc());
2697 0: D.setInvalidType();
2698 0: SC = FunctionDecl::None;
2699 : }
1: branch 2 taken
253: branch 3 taken
1: branch 5 taken
0: branch 6 not taken
1: branch 7 taken
253: branch 8 taken
2700 254: if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2701 : // Conversion functions don't have return types, but the parser will
2702 : // happily parse something like:
2703 : //
2704 : // class X {
2705 : // float operator bool();
2706 : // };
2707 : //
2708 : // The return type will be changed later anyway.
2709 : Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2710 : << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2711 1: << SourceRange(D.getIdentifierLoc());
2712 : }
2713 :
2714 : // Make sure we don't have any parameters.
1: branch 3 taken
253: branch 4 taken
2715 254: if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2716 1: Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2717 :
2718 : // Delete the parameters.
2719 1: D.getTypeObject(0).Fun.freeArgs();
2720 1: D.setInvalidType();
2721 : }
2722 :
2723 : // Make sure the conversion function isn't variadic.
2: branch 3 taken
252: branch 4 taken
1: branch 6 taken
1: branch 7 taken
1: branch 8 taken
253: branch 9 taken
2724 254: if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2725 1: Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2726 1: D.setInvalidType();
2727 : }
2728 :
2729 : // C++ [class.conv.fct]p4:
2730 : // The conversion-type-id shall not represent a function type nor
2731 : // an array type.
2732 254: QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
1: branch 2 taken
253: branch 3 taken
2733 254: if (ConvType->isArrayType()) {
2734 1: Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2735 1: ConvType = Context.getPointerType(ConvType);
2736 1: D.setInvalidType();
1: branch 2 taken
252: branch 3 taken
2737 253: } else if (ConvType->isFunctionType()) {
2738 1: Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2739 1: ConvType = Context.getPointerType(ConvType);
2740 1: D.setInvalidType();
2741 : }
2742 :
2743 : // Rebuild the function type "R" without any parameters (in case any
2744 : // of the errors above fired) and with the conversion type as the
2745 : // return type.
2746 : R = Context.getFunctionType(ConvType, 0, 0, false,
2747 254: R->getAs<FunctionProtoType>()->getTypeQuals());
2748 :
2749 : // C++0x explicit conversion operators.
10: branch 2 taken
244: branch 3 taken
5: branch 5 taken
5: branch 6 taken
5: branch 7 taken
249: branch 8 taken
2750 254: if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2751 : Diag(D.getDeclSpec().getExplicitSpecLoc(),
2752 : diag::warn_explicit_conversion_functions)
2753 5: << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2754 254: }
2755 :
2756 : /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2757 : /// the declaration of the given C++ conversion function. This routine
2758 : /// is responsible for recording the conversion function in the C++
2759 : /// class, if possible.
2760 301: Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
0: branch 0 not taken
301: branch 1 taken
2761 301: assert(Conversion && "Expected to receive a conversion function declaration");
2762 :
2763 301: CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2764 :
2765 : // Make sure we aren't redeclaring the conversion function.
2766 301: QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2767 :
2768 : // C++ [class.conv.fct]p1:
2769 : // [...] A conversion function is never used to convert a
2770 : // (possibly cv-qualified) object to the (possibly cv-qualified)
2771 : // same object type (or a reference to it), to a (possibly
2772 : // cv-qualified) base class of that type (or a reference to it),
2773 : // or to (possibly cv-qualified) void.
2774 : // FIXME: Suppress this warning if the conversion function ends up being a
2775 : // virtual function that overrides a virtual function in a base class.
2776 : QualType ClassType
2777 301: = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
49: branch 2 taken
252: branch 3 taken
2778 301: if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2779 49: ConvType = ConvTypeRef->getPointeeType();
68: branch 2 taken
233: branch 3 taken
2780 301: if (ConvType->isRecordType()) {
2781 68: ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1: branch 1 taken
67: branch 2 taken
2782 68: if (ConvType == ClassType)
2783 : Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2784 1: << ClassType;
1: branch 1 taken
66: branch 2 taken
2785 67: else if (IsDerivedFrom(ClassType, ConvType))
2786 : Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2787 1: << ClassType << ConvType;
1: branch 2 taken
232: branch 3 taken
2788 233: } else if (ConvType->isVoidType()) {
2789 : Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2790 1: << ClassType << ConvType;
2791 : }
2792 :
258: branch 1 taken
43: branch 2 taken
2793 301: if (Conversion->getPrimaryTemplate()) {
2794 : // ignore specializations
11: branch 1 taken
247: branch 2 taken
2795 258: } else if (Conversion->getPreviousDeclaration()) {
1: branch 0 taken
10: branch 1 taken
2796 11: if (FunctionTemplateDecl *ConversionTemplate
2797 11: = Conversion->getDescribedFunctionTemplate()) {
1: branch 2 taken
0: branch 3 not taken
2798 1: if (ClassDecl->replaceConversion(
2799 : ConversionTemplate->getPreviousDeclaration(),
2800 : ConversionTemplate))
2801 1: return DeclPtrTy::make(ConversionTemplate);
10: branch 2 taken
0: branch 3 not taken
2802 10: } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2803 : Conversion))
2804 10: return DeclPtrTy::make(Conversion);
0: branch 1 not taken
0: branch 2 not taken
2805 0: assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
19: branch 0 taken
228: branch 1 taken
2806 247: } else if (FunctionTemplateDecl *ConversionTemplate
2807 247: = Conversion->getDescribedFunctionTemplate())
2808 19: ClassDecl->addConversionFunction(ConversionTemplate);
2809 : else
2810 228: ClassDecl->addConversionFunction(Conversion);
2811 :
2812 290: return DeclPtrTy::make(Conversion);
2813 : }
2814 :
2815 : //===----------------------------------------------------------------------===//
2816 : // Namespace Handling
2817 : //===----------------------------------------------------------------------===//
2818 :
2819 : /// ActOnStartNamespaceDef - This is called at the start of a namespace
2820 : /// definition.
2821 : Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2822 : SourceLocation IdentLoc,
2823 : IdentifierInfo *II,
2824 : SourceLocation LBrace,
2825 659: AttributeList *AttrList) {
2826 : NamespaceDecl *Namespc =
2827 659: NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2828 659: Namespc->setLBracLoc(LBrace);
2829 :
2830 659: Scope *DeclRegionScope = NamespcScope->getParent();
2831 :
2832 659: ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2833 :
641: branch 0 taken
18: branch 1 taken
2834 659: if (II) {
2835 : // C++ [namespace.def]p2:
2836 : // The identifier in an original-namespace-definition shall not have been
2837 : // previously defined in the declarative region in which the
2838 : // original-namespace-definition appears. The identifier in an
2839 : // original-namespace-definition is the name of the namespace. Subsequently
2840 : // in that declarative region, it is treated as an original-namespace-name.
2841 :
2842 : NamedDecl *PrevDecl
2843 : = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
2844 641: ForRedeclaration);
2845 :
84: branch 1 taken
557: branch 2 taken
2846 641: if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2847 : // This is an extended namespace definition.
2848 : // Attach this namespace decl to the chain of extended namespace
2849 : // definitions.
2850 84: OrigNS->setNextNamespace(Namespc);
2851 84: Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2852 :
2853 : // Remove the previous declaration from the scope.
77: branch 2 taken
7: branch 3 taken
2854 84: if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2855 77: IdResolver.RemoveDecl(OrigNS);
2856 77: DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2857 : }
2: branch 0 taken
555: branch 1 taken
2858 557: } else if (PrevDecl) {
2859 : // This is an invalid name redefinition.
2860 : Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2861 2: << Namespc->getDeclName();
2862 2: Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2863 2: Namespc->setInvalidDecl();
2864 : // Continue on to push Namespc as current DeclContext and return it.
28: branch 1 taken
527: branch 2 taken
27: branch 5 taken
1: branch 6 taken
27: branch 7 taken
528: branch 8 taken
2865 555: } else if (II->isStr("std") &&
2866 : CurContext->getLookupContext()->isTranslationUnit()) {
2867 : // This is the first "real" definition of the namespace "std", so update
2868 : // our cache of the "std" namespace to point at this definition.
3: branch 0 taken
24: branch 1 taken
2869 27: if (StdNamespace) {
2870 : // We had already defined a dummy namespace "std". Link this new
2871 : // namespace definition to the dummy namespace "std".
2872 3: StdNamespace->setNextNamespace(Namespc);
2873 3: StdNamespace->setLocation(IdentLoc);
2874 3: Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2875 : }
2876 :
2877 : // Make our StdNamespace cache point at the first real definition of the
2878 : // "std" namespace.
2879 27: StdNamespace = Namespc;
2880 : }
2881 :
2882 641: PushOnScopeChains(Namespc, DeclRegionScope);
2883 : } else {
2884 : // Anonymous namespaces.
0: branch 1 not taken
18: branch 2 taken
2885 18: assert(Namespc->isAnonymousNamespace());
2886 18: CurContext->addDecl(Namespc);
2887 :
2888 : // Link the anonymous namespace into its parent.
2889 : NamespaceDecl *PrevDecl;
2890 18: DeclContext *Parent = CurContext->getLookupContext();
14: branch 1 taken
4: branch 2 taken
2891 18: if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2892 14: PrevDecl = TU->getAnonymousNamespace();
2893 14: TU->setAnonymousNamespace(Namespc);
2894 : } else {
2895 4: NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2896 4: PrevDecl = ND->getAnonymousNamespace();
2897 4: ND->setAnonymousNamespace(Namespc);
2898 : }
2899 :
2900 : // Link the anonymous namespace with its previous declaration.
4: branch 0 taken
14: branch 1 taken
2901 18: if (PrevDecl) {
0: branch 1 not taken
4: branch 2 taken
2902 4: assert(PrevDecl->isAnonymousNamespace());
0: branch 1 not taken
4: branch 2 taken
2903 4: assert(!PrevDecl->getNextNamespace());
2904 4: Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2905 4: PrevDecl->setNextNamespace(Namespc);
2906 : }
2907 :
2908 : // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2909 : // behaves as if it were replaced by
2910 : // namespace unique { /* empty body */ }
2911 : // using namespace unique;
2912 : // namespace unique { namespace-body }
2913 : // where all occurrences of 'unique' in a translation unit are
2914 : // replaced by the same identifier and this identifier differs
2915 : // from all other identifiers in the entire program.
2916 :
2917 : // We just create the namespace with an empty name and then add an
2918 : // implicit using declaration, just like the standard suggests.
2919 : //
2920 : // CodeGen enforces the "universally unique" aspect by giving all
2921 : // declarations semantically contained within an anonymous
2922 : // namespace internal linkage.
2923 :
14: branch 0 taken
4: branch 1 taken
2924 18: if (!PrevDecl) {
2925 : UsingDirectiveDecl* UD
2926 : = UsingDirectiveDecl::Create(Context, CurContext,
2927 : /* 'using' */ LBrace,
2928 : /* 'namespace' */ SourceLocation(),
2929 : /* qualifier */ SourceRange(),
2930 : /* NNS */ NULL,
2931 : /* identifier */ SourceLocation(),
2932 : Namespc,
2933 14: /* Ancestor */ CurContext);
2934 14: UD->setImplicit();
2935 14: CurContext->addDecl(UD);
2936 : }
2937 : }
2938 :
2939 : // Although we could have an invalid decl (i.e. the namespace name is a
2940 : // redefinition), push it as current DeclContext and try to continue parsing.
2941 : // FIXME: We should be able to push Namespc here, so that the each DeclContext
2942 : // for the namespace has the declarations that showed up in that particular
2943 : // namespace definition.
659: branch 0 taken
0: branch 1 not taken
2944 659: PushDeclContext(NamespcScope, Namespc);
2945 659: return DeclPtrTy::make(Namespc);
2946 : }
2947 :
2948 : /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2949 : /// is a namespace alias, returns the namespace it points to.
2950 88: static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2: branch 1 taken
86: branch 2 taken
2951 88: if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2952 2: return AD->getNamespace();
2953 86: return dyn_cast_or_null<NamespaceDecl>(D);
2954 : }
2955 :
2956 : /// ActOnFinishNamespaceDef - This callback is called after a namespace is
2957 : /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2958 659: void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2959 659: Decl *Dcl = D.getAs<Decl>();
2960 659: NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
0: branch 0 not taken
659: branch 1 taken
2961 659: assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2962 659: Namespc->setRBracLoc(RBrace);
2963 659: PopDeclContext();
2964 659: }
2965 :
2966 : Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2967 : SourceLocation UsingLoc,
2968 : SourceLocation NamespcLoc,
2969 : const CXXScopeSpec &SS,
2970 : SourceLocation IdentLoc,
2971 : IdentifierInfo *NamespcName,
2972 90: AttributeList *AttrList) {
90: branch 1 taken
0: branch 2 not taken
2973 90: assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
0: branch 0 not taken
90: branch 1 taken
2974 90: assert(NamespcName && "Invalid NamespcName.");
90: branch 1 taken
0: branch 2 not taken
2975 90: assert(IdentLoc.isValid() && "Invalid NamespceName location.");
90: branch 1 taken
0: branch 2 not taken
2976 90: assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2977 :
2978 90: UsingDirectiveDecl *UDir = 0;
2979 :
2980 : // Lookup namespace name.
2981 90: LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2982 90: LookupParsedName(R, S, &SS);
1: branch 1 taken
89: branch 2 taken
2983 90: if (R.isAmbiguous())
2984 1: return DeclPtrTy();
2985 :
85: branch 1 taken
4: branch 2 taken
2986 89: if (!R.empty()) {
2987 85: NamedDecl *Named = R.getFoundDecl();
2988 : assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
1: branch 1 taken
84: branch 2 taken
1: branch 4 taken
0: branch 5 not taken
2989 85: && "expected namespace decl");
2990 : // C++ [namespace.udir]p1:
2991 : // A using-directive specifies that the names in the nominated
2992 : // namespace can be used in the scope in which the
2993 : // using-directive appears after the using-directive. During
2994 : // unqualified name lookup (3.4.1), the names appear as if they
2995 : // were declared in the nearest enclosing namespace which
2996 : // contains both the using-directive and the nominated
2997 : // namespace. [Note: in this context, "contains" means "contains
2998 : // directly or indirectly". ]
2999 :
3000 : // Find enclosing context containing both using-directive and
3001 : // nominated namespace.
3002 85: NamespaceDecl *NS = getNamespaceDecl(Named);
3003 85: DeclContext *CommonAncestor = cast<DeclContext>(NS);
185: branch 0 taken
0: branch 1 not taken
100: branch 3 taken
85: branch 4 taken
100: branch 5 taken
85: branch 6 taken
3004 270: while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3005 100: CommonAncestor = CommonAncestor->getParent();
3006 :
3007 : UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3008 : SS.getRange(),
3009 : (NestedNameSpecifier *)SS.getScopeRep(),
3010 85: IdentLoc, Named, CommonAncestor);
3011 85: PushUsingDirective(S, UDir);
3012 : } else {
3013 4: Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3014 : }
3015 :
3016 : // FIXME: We ignore attributes for now.
0: branch 0 not taken
89: branch 1 taken
3017 89: delete AttrList;
3018 89: return DeclPtrTy::make(UDir);
3019 : }
3020 :
3021 85: void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3022 : // If scope has associated entity, then using directive is at namespace
3023 : // or translation unit scope. We add UsingDirectiveDecls, into
3024 : // it's lookup structure.
85: branch 1 taken
0: branch 2 not taken
3025 85: if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3026 85: Ctx->addDecl(UDir);
3027 : else
3028 : // Otherwise it is block-sope. using-directives will affect lookup
3029 : // only to the end of scope.
3030 0: S->PushUsingDirective(DeclPtrTy::make(UDir));
3031 85: }
3032 :
3033 :
3034 : Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3035 : AccessSpecifier AS,
3036 : bool HasUsingKeyword,
3037 : SourceLocation UsingLoc,
3038 : const CXXScopeSpec &SS,
3039 : UnqualifiedId &Name,
3040 : AttributeList *AttrList,
3041 : bool IsTypeName,
3042 130: SourceLocation TypenameLoc) {
130: branch 1 taken
0: branch 2 not taken
3043 130: assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3044 :
127: branch 1 taken
0: branch 2 not taken
0: branch 3 not taken
3: branch 4 taken
0: branch 5 not taken
3045 130: switch (Name.getKind()) {
3046 : case UnqualifiedId::IK_Identifier:
3047 : case UnqualifiedId::IK_OperatorFunctionId:
3048 : case UnqualifiedId::IK_LiteralOperatorId:
3049 : case UnqualifiedId::IK_ConversionFunctionId:
3050 127: break;
3051 :
3052 : case UnqualifiedId::IK_ConstructorName:
3053 : case UnqualifiedId::IK_ConstructorTemplateId:
3054 : // C++0x inherited constructors.
0: branch 1 not taken
0: branch 2 not taken
3055 0: if (getLangOptions().CPlusPlus0x) break;
3056 :
3057 : Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3058 0: << SS.getRange();
3059 0: return DeclPtrTy();
3060 :
3061 : case UnqualifiedId::IK_DestructorName:
3062 : Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3063 0: << SS.getRange();
3064 0: return DeclPtrTy();
3065 :
3066 : case UnqualifiedId::IK_TemplateId:
3067 : Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3068 3: << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3069 3: return DeclPtrTy();
3070 : }
3071 :
3072 127: DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
0: branch 1 not taken
127: branch 2 taken
3073 127: if (!TargetName)
3074 0: return DeclPtrTy();
3075 :
3076 : // Warn about using declarations.
3077 : // TODO: store that the declaration was written without 'using' and
3078 : // talk about access decls instead of using decls in the
3079 : // diagnostics.
1: branch 0 taken
126: branch 1 taken
3080 127: if (!HasUsingKeyword) {
3081 1: UsingLoc = Name.getSourceRange().getBegin();
3082 :
3083 : Diag(UsingLoc, diag::warn_access_decl_deprecated)
3084 : << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3085 1: "using ");
3086 : }
3087 :
3088 : NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3089 : Name.getSourceRange().getBegin(),
3090 : TargetName, AttrList,
3091 : /* IsInstantiation */ false,
3092 127: IsTypeName, TypenameLoc);
112: branch 0 taken
15: branch 1 taken
3093 127: if (UD)
3094 112: PushOnScopeChains(UD, S, /*AddToContext*/ false);
3095 :
3096 127: return DeclPtrTy::make(UD);
3097 : }
3098 :
3099 : /// Determines whether to create a using shadow decl for a particular
3100 : /// decl, given the set of decls existing prior to this using lookup.
3101 : bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3102 122: const LookupResult &Previous) {
3103 : // Diagnose finding a decl which is not from a base class of the
3104 : // current class. We do this now because there are cases where this
3105 : // function will silently decide not to build a shadow decl, which
3106 : // will pre-empt further diagnostics.
3107 : //
3108 : // We don't need to do this in C++0x because we do the check once on
3109 : // the qualifier.
3110 : //
3111 : // FIXME: diagnose the following if we care enough:
3112 : // struct A { int foo; };
3113 : // struct B : A { using A::foo; };
3114 : // template <class T> struct C : A {};
3115 : // template <class T> struct D : C<T> { using B::foo; } // <---
3116 : // This is invalid (during instantiation) in C++03 because B::foo
3117 : // resolves to the using decl in B, which is not a base class of D<T>.
3118 : // We can't diagnose it immediately because C<T> is an unknown
3119 : // specialization. The UsingShadowDecl in D<T> then points directly
3120 : // to A::foo, which will look well-formed when we instantiate.
3121 : // The right solution is to not collapse the shadow-decl chain.
118: branch 1 taken
4: branch 2 taken