blob: 22484745da257a29c05e636613becbe77d8dead3 [file] [log] [blame]
Douglas Gregord87b61f2009-12-10 17:56:55 +00001//===--- SemaInit.h - Semantic Analysis for Initializers --------*- C++ -*-===//
Douglas Gregor20093b42009-12-09 23:02:17 +00002//
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 provides supporting data types for initialization of objects.
11//
12//===----------------------------------------------------------------------===//
13#ifndef LLVM_CLANG_SEMA_INIT_H
14#define LLVM_CLANG_SEMA_INIT_H
15
16#include "SemaOverload.h"
17#include "clang/AST/TypeLoc.h"
18#include "clang/Parse/Action.h"
19#include "clang/Basic/SourceLocation.h"
20#include "llvm/ADT/PointerIntPair.h"
21#include "llvm/ADT/SmallVector.h"
22#include <cassert>
23
24namespace clang {
25
26class CXXBaseSpecifier;
27class DeclaratorDecl;
28class DeclaratorInfo;
29class FieldDecl;
30class FunctionDecl;
31class ParmVarDecl;
32class Sema;
33class TypeLoc;
34class VarDecl;
35
36/// \brief Describes an entity that is being initialized.
37class InitializedEntity {
38public:
39 /// \brief Specifies the kind of entity being initialized.
40 enum EntityKind {
41 /// \brief The entity being initialized is a variable.
42 EK_Variable,
43 /// \brief The entity being initialized is a function parameter.
44 EK_Parameter,
45 /// \brief The entity being initialized is the result of a function call.
46 EK_Result,
47 /// \brief The entity being initialized is an exception object that
48 /// is being thrown.
49 EK_Exception,
50 /// \brief The entity being initialized is a temporary object.
51 EK_Temporary,
52 /// \brief The entity being initialized is a base member subobject.
53 EK_Base,
54 /// \brief The entity being initialized is a non-static data member
55 /// subobject.
56 EK_Member
57 };
58
59private:
60 /// \brief The kind of entity being initialized.
61 EntityKind Kind;
62
63 /// \brief The type of the object or reference being initialized along with
64 /// its location information.
65 TypeLoc TL;
66
67 union {
68 /// \brief When Kind == EK_Variable, EK_Parameter, or EK_Member,
69 /// the VarDecl, ParmVarDecl, or FieldDecl, respectively.
70 DeclaratorDecl *VariableOrMember;
71
72 /// \brief When Kind == EK_Result or EK_Exception, the location of the
73 /// 'return' or 'throw' keyword, respectively. When Kind == EK_Temporary,
74 /// the location where the temporary is being created.
75 unsigned Location;
76
77 /// \brief When Kind == EK_Base, the base specifier that provides the
78 /// base class.
79 CXXBaseSpecifier *Base;
80 };
81
82 InitializedEntity() { }
83
84 /// \brief Create the initialization entity for a variable.
85 InitializedEntity(VarDecl *Var)
86 : Kind(EK_Variable),
87 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Var))
88 {
89 InitDeclLoc();
90 }
91
92 /// \brief Create the initialization entity for a parameter.
93 InitializedEntity(ParmVarDecl *Parm)
94 : Kind(EK_Parameter),
95 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Parm))
96 {
97 InitDeclLoc();
98 }
99
100 /// \brief Create the initialization entity for the result of a function,
101 /// throwing an object, or performing an explicit cast.
102 InitializedEntity(EntityKind Kind, SourceLocation Loc, TypeLoc TL)
103 : Kind(Kind), TL(TL), Location(Loc.getRawEncoding()) { }
104
105 /// \brief Create the initialization entity for a member subobject.
106 InitializedEntity(FieldDecl *Member)
107 : Kind(EK_Member),
108 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Member))
109 {
110 InitDeclLoc();
111 }
112
113 /// \brief Initialize type-location information from a declaration.
114 void InitDeclLoc();
115
116public:
117 /// \brief Create the initialization entity for a variable.
118 static InitializedEntity InitializeVariable(VarDecl *Var) {
119 return InitializedEntity(Var);
120 }
121
122 /// \brief Create the initialization entity for a parameter.
123 static InitializedEntity InitializeParameter(ParmVarDecl *Parm) {
124 return InitializedEntity(Parm);
125 }
126
127 /// \brief Create the initialization entity for the result of a function.
128 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
129 TypeLoc TL) {
130 return InitializedEntity(EK_Result, ReturnLoc, TL);
131 }
132
133 /// \brief Create the initialization entity for an exception object.
134 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
135 TypeLoc TL) {
136 return InitializedEntity(EK_Exception, ThrowLoc, TL);
137 }
138
139 /// \brief Create the initialization entity for a temporary.
140 static InitializedEntity InitializeTemporary(EntityKind Kind, TypeLoc TL) {
141 return InitializedEntity(Kind, SourceLocation(), TL);
142 }
143
144 /// \brief Create the initialization entity for a base class subobject.
145 static InitializedEntity InitializeBase(ASTContext &Context,
146 CXXBaseSpecifier *Base);
147
148 /// \brief Create the initialize entity for a member subobject.
149 static InitializedEntity InitializeMember(FieldDecl *Member) {
150 return InitializedEntity(Member);
151 }
152
153 /// \brief Determine the kind of initialization.
154 EntityKind getKind() const { return Kind; }
155
156 /// \brief Retrieve type being initialized.
157 TypeLoc getType() const { return TL; }
158
159 /// \brief Determine the location of the 'return' keyword when initializing
160 /// the result of a function call.
161 SourceLocation getReturnLoc() const {
162 assert(getKind() == EK_Result && "No 'return' location!");
163 return SourceLocation::getFromRawEncoding(Location);
164 }
165
166 /// \brief Determine the location of the 'throw' keyword when initializing
167 /// an exception object.
168 SourceLocation getThrowLoc() const {
169 assert(getKind() == EK_Exception && "No 'throw' location!");
170 return SourceLocation::getFromRawEncoding(Location);
171 }
172};
173
174/// \brief Describes the kind of initialization being performed, along with
175/// location information for tokens related to the initialization (equal sign,
176/// parentheses).
177class InitializationKind {
178public:
179 /// \brief The kind of initialization being performed.
180 enum InitKind {
181 IK_Direct, ///< Direct initialization
182 IK_Copy, ///< Copy initialization
183 IK_Default, ///< Default initialization
184 IK_Value ///< Value initialization
185 };
186
187private:
188 /// \brief The kind of initialization that we're storing.
189 enum StoredInitKind {
190 SIK_Direct = IK_Direct, ///< Direct initialization
191 SIK_Copy = IK_Copy, ///< Copy initialization
192 SIK_Default = IK_Default, ///< Default initialization
193 SIK_Value = IK_Value, ///< Value initialization
194 SIK_DirectCast, ///< Direct initialization due to a cast
195 /// \brief Direct initialization due to a C-style or functional cast.
196 SIK_DirectCStyleOrFunctionalCast
197 };
198
199 /// \brief The kind of initialization being performed.
200 StoredInitKind Kind;
201
202 /// \brief The source locations involved in the initialization.
203 SourceLocation Locations[3];
204
205 InitializationKind(StoredInitKind Kind, SourceLocation Loc1,
206 SourceLocation Loc2, SourceLocation Loc3)
207 : Kind(Kind)
208 {
209 Locations[0] = Loc1;
210 Locations[1] = Loc2;
211 Locations[2] = Loc3;
212 }
213
214public:
215 /// \brief Create a direct initialization.
216 static InitializationKind CreateDirect(SourceLocation InitLoc,
217 SourceLocation LParenLoc,
218 SourceLocation RParenLoc) {
219 return InitializationKind(SIK_Direct, InitLoc, LParenLoc, RParenLoc);
220 }
221
222 /// \brief Create a direct initialization due to a cast.
223 static InitializationKind CreateCast(SourceRange TypeRange,
224 bool IsCStyleCast) {
225 return InitializationKind(IsCStyleCast? SIK_DirectCStyleOrFunctionalCast
226 : SIK_DirectCast,
227 TypeRange.getBegin(), TypeRange.getBegin(),
228 TypeRange.getEnd());
229 }
230
231 /// \brief Create a copy initialization.
232 static InitializationKind CreateCopy(SourceLocation InitLoc,
233 SourceLocation EqualLoc) {
234 return InitializationKind(SIK_Copy, InitLoc, EqualLoc, EqualLoc);
235 }
236
237 /// \brief Create a default initialization.
238 static InitializationKind CreateDefault(SourceLocation InitLoc) {
239 return InitializationKind(SIK_Default, InitLoc, InitLoc, InitLoc);
240 }
241
242 /// \brief Create a value initialization.
243 static InitializationKind CreateValue(SourceLocation InitLoc,
244 SourceLocation LParenLoc,
245 SourceLocation RParenLoc) {
246 return InitializationKind(SIK_Value, InitLoc, LParenLoc, RParenLoc);
247 }
248
249 /// \brief Determine the initialization kind.
250 InitKind getKind() const {
251 if (Kind > SIK_Value)
252 return IK_Direct;
253
254 return (InitKind)Kind;
255 }
256
257 /// \brief Determine whether this initialization is an explicit cast.
258 bool isExplicitCast() const {
259 return Kind == SIK_DirectCast || Kind == SIK_DirectCStyleOrFunctionalCast;
260 }
261
262 /// \brief Determine whether this initialization is a C-style cast.
263 bool isCStyleOrFunctionalCast() const {
264 return Kind == SIK_DirectCStyleOrFunctionalCast;
265 }
266
267 /// \brief Retrieve the location at which initialization is occurring.
268 SourceLocation getLocation() const { return Locations[0]; }
269
270 /// \brief Retrieve the source range that covers the initialization.
271 SourceRange getRange() const {
272 return SourceRange(Locations[0], Locations[1]);
273 }
274
275 /// \brief Retrieve the location of the equal sign for copy initialization
276 /// (if present).
277 SourceLocation getEqualLoc() const {
278 assert(Kind == SIK_Copy && "Only copy initialization has an '='");
279 return Locations[1];
280 }
281
282 /// \brief Retrieve the source range containing the locations of the open
283 /// and closing parentheses for value and direct initializations.
284 SourceRange getParenRange() const {
285 assert((getKind() == IK_Direct || Kind == SIK_Value) &&
286 "Only direct- and value-initialization have parentheses");
287 return SourceRange(Locations[1], Locations[2]);
288 }
289};
290
291/// \brief Describes the sequence of initializations required to initialize
292/// a given object or reference with a set of arguments.
293class InitializationSequence {
294public:
295 /// \brief Describes the kind of initialization sequence computed.
296 enum SequenceKind {
297 /// \brief A failed initialization sequence. The failure kind tells what
298 /// happened.
299 FailedSequence = 0,
300
301 /// \brief A dependent initialization, which could not be
302 /// type-checked due to the presence of dependent types or
303 /// dependently-type expressions.
304 DependentSequence,
305
Douglas Gregor4a520a22009-12-14 17:27:33 +0000306 /// \brief A user-defined conversion sequence.
307 UserDefinedConversion,
308
Douglas Gregor20093b42009-12-09 23:02:17 +0000309 /// \brief A reference binding.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000310 ReferenceBinding,
311
312 /// \brief List initialization
313 ListInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000314 };
315
316 /// \brief Describes the kind of a particular step in an initialization
317 /// sequence.
318 enum StepKind {
319 /// \brief Resolve the address of an overloaded function to a specific
320 /// function declaration.
321 SK_ResolveAddressOfOverloadedFunction,
322 /// \brief Perform a derived-to-base cast, producing an rvalue.
323 SK_CastDerivedToBaseRValue,
324 /// \brief Perform a derived-to-base cast, producing an lvalue.
325 SK_CastDerivedToBaseLValue,
326 /// \brief Reference binding to an lvalue.
327 SK_BindReference,
328 /// \brief Reference binding to a temporary.
329 SK_BindReferenceToTemporary,
330 /// \brief Perform a user-defined conversion, either via a conversion
331 /// function or via a constructor.
332 SK_UserConversion,
333 /// \brief Perform a qualification conversion, producing an rvalue.
334 SK_QualificationConversionRValue,
335 /// \brief Perform a qualification conversion, producing an lvalue.
336 SK_QualificationConversionLValue,
337 /// \brief Perform an implicit conversion sequence.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000338 SK_ConversionSequence,
339 /// \brief Perform list-initialization
340 SK_ListInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000341 };
342
343 /// \brief A single step in the initialization sequence.
344 class Step {
345 public:
346 /// \brief The kind of conversion or initialization step we are taking.
347 StepKind Kind;
348
349 // \brief The type that results from this initialization.
350 QualType Type;
351
352 union {
353 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
354 /// SK_UserConversion, the function that the expression should be
355 /// resolved to or the conversion function to call, respectively.
356 FunctionDecl *Function;
357
358 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
359 /// sequence
360 ImplicitConversionSequence *ICS;
361 };
362
363 void Destroy();
364 };
365
366private:
367 /// \brief The kind of initialization sequence computed.
368 enum SequenceKind SequenceKind;
369
370 /// \brief Steps taken by this initialization.
371 llvm::SmallVector<Step, 4> Steps;
372
373public:
374 /// \brief Describes why initialization failed.
375 enum FailureKind {
376 /// \brief Too many initializers provided for a reference.
377 FK_TooManyInitsForReference,
378 /// \brief Array must be initialized with an initializer list.
379 FK_ArrayNeedsInitList,
380 /// \brief Array must be initialized with an initializer list or a
381 /// string literal.
382 FK_ArrayNeedsInitListOrStringLiteral,
383 /// \brief Cannot resolve the address of an overloaded function.
384 FK_AddressOfOverloadFailed,
385 /// \brief Overloading due to reference initialization failed.
386 FK_ReferenceInitOverloadFailed,
387 /// \brief Non-const lvalue reference binding to a temporary.
388 FK_NonConstLValueReferenceBindingToTemporary,
389 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
390 /// type.
391 FK_NonConstLValueReferenceBindingToUnrelated,
392 /// \brief Rvalue reference binding to an lvalue.
393 FK_RValueReferenceBindingToLValue,
394 /// \brief Reference binding drops qualifiers.
395 FK_ReferenceInitDropsQualifiers,
396 /// \brief Reference binding failed.
397 FK_ReferenceInitFailed,
398 /// \brief Implicit conversion failed.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000399 FK_ConversionFailed,
400 /// \brief Too many initializers for scalar
401 FK_TooManyInitsForScalar,
402 /// \brief Reference initialization from an initializer list
403 FK_ReferenceBindingToInitList,
404 /// \brief Initialization of some unused destination type with an
405 /// initializer list.
Douglas Gregor4a520a22009-12-14 17:27:33 +0000406 FK_InitListBadDestinationType,
407 /// \brief Overloading for a user-defined conversion failed.
408 FK_UserConversionOverloadFailed
Douglas Gregor20093b42009-12-09 23:02:17 +0000409 };
410
411private:
412 /// \brief The reason why initialization failued.
413 FailureKind Failure;
414
415 /// \brief The failed result of overload resolution.
416 OverloadingResult FailedOverloadResult;
417
418 /// \brief The candidate set created when initialization failed.
419 OverloadCandidateSet FailedCandidateSet;
420
421public:
422 /// \brief Try to perform initialization of the given entity, creating a
423 /// record of the steps required to perform the initialization.
424 ///
425 /// The generated initialization sequence will either contain enough
426 /// information to diagnose
427 ///
428 /// \param S the semantic analysis object.
429 ///
430 /// \param Entity the entity being initialized.
431 ///
432 /// \param Kind the kind of initialization being performed.
433 ///
434 /// \param Args the argument(s) provided for initialization.
435 ///
436 /// \param NumArgs the number of arguments provided for initialization.
437 InitializationSequence(Sema &S,
438 const InitializedEntity &Entity,
439 const InitializationKind &Kind,
440 Expr **Args,
441 unsigned NumArgs);
442
443 ~InitializationSequence();
444
445 /// \brief Perform the actual initialization of the given entity based on
446 /// the computed initialization sequence.
447 ///
448 /// \param S the semantic analysis object.
449 ///
450 /// \param Entity the entity being initialized.
451 ///
452 /// \param Kind the kind of initialization being performed.
453 ///
454 /// \param Args the argument(s) provided for initialization, ownership of
455 /// which is transfered into the routine.
456 ///
Douglas Gregord87b61f2009-12-10 17:56:55 +0000457 /// \param ResultType if non-NULL, will be set to the type of the
458 /// initialized object, which is the type of the declaration in most
459 /// cases. However, when the initialized object is a variable of
460 /// incomplete array type and the initializer is an initializer
461 /// list, this type will be set to the completed array type.
462 ///
Douglas Gregor20093b42009-12-09 23:02:17 +0000463 /// \returns an expression that performs the actual object initialization, if
464 /// the initialization is well-formed. Otherwise, emits diagnostics
465 /// and returns an invalid expression.
466 Action::OwningExprResult Perform(Sema &S,
467 const InitializedEntity &Entity,
468 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +0000469 Action::MultiExprArg Args,
470 QualType *ResultType = 0);
Douglas Gregor20093b42009-12-09 23:02:17 +0000471
472 /// \brief Diagnose an potentially-invalid initialization sequence.
473 ///
474 /// \returns true if the initialization sequence was ill-formed,
475 /// false otherwise.
476 bool Diagnose(Sema &S,
477 const InitializedEntity &Entity,
478 const InitializationKind &Kind,
479 Expr **Args, unsigned NumArgs);
480
481 /// \brief Determine the kind of initialization sequence computed.
482 enum SequenceKind getKind() const { return SequenceKind; }
483
484 /// \brief Set the kind of sequence computed.
485 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
486
487 /// \brief Determine whether the initialization sequence is valid.
488 operator bool() const { return SequenceKind != FailedSequence; }
489
490 typedef llvm::SmallVector<Step, 4>::const_iterator step_iterator;
491 step_iterator step_begin() const { return Steps.begin(); }
492 step_iterator step_end() const { return Steps.end(); }
493
494 /// \brief Add a new step in the initialization that resolves the address
495 /// of an overloaded function to a specific function declaration.
496 ///
497 /// \param Function the function to which the overloaded function reference
498 /// resolves.
499 void AddAddressOverloadResolutionStep(FunctionDecl *Function);
500
501 /// \brief Add a new step in the initialization that performs a derived-to-
502 /// base cast.
503 ///
504 /// \param BaseType the base type to which we will be casting.
505 ///
506 /// \param IsLValue true if the result of this cast will be treated as
507 /// an lvalue.
508 void AddDerivedToBaseCastStep(QualType BaseType, bool IsLValue);
509
510 /// \brief Add a new step binding a reference to an object.
511 ///
512 /// \param BindingTemporary true if we are binding a reference to a temporary
513 /// object (thereby extending its lifetime); false if we are binding to an
514 /// lvalue or an lvalue treated as an rvalue.
515 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
516
517 /// \brief Add a new step invoking a conversion function, which is either
518 /// a constructor or a conversion function.
Eli Friedman03981012009-12-11 02:42:07 +0000519 void AddUserConversionStep(FunctionDecl *Function, QualType T);
Douglas Gregor20093b42009-12-09 23:02:17 +0000520
521 /// \brief Add a new step that performs a qualification conversion to the
522 /// given type.
523 void AddQualificationConversionStep(QualType Ty, bool IsLValue);
524
525 /// \brief Add a new step that applies an implicit conversion sequence.
526 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
527 QualType T);
Douglas Gregord87b61f2009-12-10 17:56:55 +0000528
529 /// \brief Add a list-initialiation step
530 void AddListInitializationStep(QualType T);
531
Douglas Gregor20093b42009-12-09 23:02:17 +0000532 /// \brief Note that this initialization sequence failed.
533 void SetFailed(FailureKind Failure) {
534 SequenceKind = FailedSequence;
535 this->Failure = Failure;
536 }
537
538 /// \brief Note that this initialization sequence failed due to failed
539 /// overload resolution.
540 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
541
542 /// \brief Retrieve a reference to the candidate set when overload
543 /// resolution fails.
544 OverloadCandidateSet &getFailedCandidateSet() {
545 return FailedCandidateSet;
546 }
547
548 /// \brief Determine why initialization failed.
549 FailureKind getFailureKind() const {
550 assert(getKind() == FailedSequence && "Not an initialization failure!");
551 return Failure;
552 }
553};
554
555} // end namespace clang
556
557#endif // LLVM_CLANG_SEMA_INIT_H