blob: 2c05196fb1728e37126fecd218a5eeb179ff44d0 [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 Gregor51c56d62009-12-14 20:49:26 +0000309 /// \brief A constructor call.
Douglas Gregora6ca6502009-12-14 20:57:13 +0000310 ConstructorInitialization,
Douglas Gregor51c56d62009-12-14 20:49:26 +0000311
Douglas Gregor20093b42009-12-09 23:02:17 +0000312 /// \brief A reference binding.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000313 ReferenceBinding,
314
315 /// \brief List initialization
316 ListInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000317 };
318
319 /// \brief Describes the kind of a particular step in an initialization
320 /// sequence.
321 enum StepKind {
322 /// \brief Resolve the address of an overloaded function to a specific
323 /// function declaration.
324 SK_ResolveAddressOfOverloadedFunction,
325 /// \brief Perform a derived-to-base cast, producing an rvalue.
326 SK_CastDerivedToBaseRValue,
327 /// \brief Perform a derived-to-base cast, producing an lvalue.
328 SK_CastDerivedToBaseLValue,
329 /// \brief Reference binding to an lvalue.
330 SK_BindReference,
331 /// \brief Reference binding to a temporary.
332 SK_BindReferenceToTemporary,
333 /// \brief Perform a user-defined conversion, either via a conversion
334 /// function or via a constructor.
335 SK_UserConversion,
336 /// \brief Perform a qualification conversion, producing an rvalue.
337 SK_QualificationConversionRValue,
338 /// \brief Perform a qualification conversion, producing an lvalue.
339 SK_QualificationConversionLValue,
340 /// \brief Perform an implicit conversion sequence.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000341 SK_ConversionSequence,
342 /// \brief Perform list-initialization
Douglas Gregor51c56d62009-12-14 20:49:26 +0000343 SK_ListInitialization,
344 /// \brief Perform initialization via a constructor.
345 SK_ConstructorInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000346 };
347
348 /// \brief A single step in the initialization sequence.
349 class Step {
350 public:
351 /// \brief The kind of conversion or initialization step we are taking.
352 StepKind Kind;
353
354 // \brief The type that results from this initialization.
355 QualType Type;
356
357 union {
358 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
359 /// SK_UserConversion, the function that the expression should be
360 /// resolved to or the conversion function to call, respectively.
361 FunctionDecl *Function;
362
363 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
364 /// sequence
365 ImplicitConversionSequence *ICS;
366 };
367
368 void Destroy();
369 };
370
371private:
372 /// \brief The kind of initialization sequence computed.
373 enum SequenceKind SequenceKind;
374
375 /// \brief Steps taken by this initialization.
376 llvm::SmallVector<Step, 4> Steps;
377
378public:
379 /// \brief Describes why initialization failed.
380 enum FailureKind {
381 /// \brief Too many initializers provided for a reference.
382 FK_TooManyInitsForReference,
383 /// \brief Array must be initialized with an initializer list.
384 FK_ArrayNeedsInitList,
385 /// \brief Array must be initialized with an initializer list or a
386 /// string literal.
387 FK_ArrayNeedsInitListOrStringLiteral,
388 /// \brief Cannot resolve the address of an overloaded function.
389 FK_AddressOfOverloadFailed,
390 /// \brief Overloading due to reference initialization failed.
391 FK_ReferenceInitOverloadFailed,
392 /// \brief Non-const lvalue reference binding to a temporary.
393 FK_NonConstLValueReferenceBindingToTemporary,
394 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
395 /// type.
396 FK_NonConstLValueReferenceBindingToUnrelated,
397 /// \brief Rvalue reference binding to an lvalue.
398 FK_RValueReferenceBindingToLValue,
399 /// \brief Reference binding drops qualifiers.
400 FK_ReferenceInitDropsQualifiers,
401 /// \brief Reference binding failed.
402 FK_ReferenceInitFailed,
403 /// \brief Implicit conversion failed.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000404 FK_ConversionFailed,
405 /// \brief Too many initializers for scalar
406 FK_TooManyInitsForScalar,
407 /// \brief Reference initialization from an initializer list
408 FK_ReferenceBindingToInitList,
409 /// \brief Initialization of some unused destination type with an
410 /// initializer list.
Douglas Gregor4a520a22009-12-14 17:27:33 +0000411 FK_InitListBadDestinationType,
412 /// \brief Overloading for a user-defined conversion failed.
Douglas Gregor51c56d62009-12-14 20:49:26 +0000413 FK_UserConversionOverloadFailed,
414 /// \brief Overloaded for initialization by constructor failed.
415 FK_ConstructorOverloadFailed
Douglas Gregor20093b42009-12-09 23:02:17 +0000416 };
417
418private:
419 /// \brief The reason why initialization failued.
420 FailureKind Failure;
421
422 /// \brief The failed result of overload resolution.
423 OverloadingResult FailedOverloadResult;
424
425 /// \brief The candidate set created when initialization failed.
426 OverloadCandidateSet FailedCandidateSet;
427
428public:
429 /// \brief Try to perform initialization of the given entity, creating a
430 /// record of the steps required to perform the initialization.
431 ///
432 /// The generated initialization sequence will either contain enough
433 /// information to diagnose
434 ///
435 /// \param S the semantic analysis object.
436 ///
437 /// \param Entity the entity being initialized.
438 ///
439 /// \param Kind the kind of initialization being performed.
440 ///
441 /// \param Args the argument(s) provided for initialization.
442 ///
443 /// \param NumArgs the number of arguments provided for initialization.
444 InitializationSequence(Sema &S,
445 const InitializedEntity &Entity,
446 const InitializationKind &Kind,
447 Expr **Args,
448 unsigned NumArgs);
449
450 ~InitializationSequence();
451
452 /// \brief Perform the actual initialization of the given entity based on
453 /// the computed initialization sequence.
454 ///
455 /// \param S the semantic analysis object.
456 ///
457 /// \param Entity the entity being initialized.
458 ///
459 /// \param Kind the kind of initialization being performed.
460 ///
461 /// \param Args the argument(s) provided for initialization, ownership of
462 /// which is transfered into the routine.
463 ///
Douglas Gregord87b61f2009-12-10 17:56:55 +0000464 /// \param ResultType if non-NULL, will be set to the type of the
465 /// initialized object, which is the type of the declaration in most
466 /// cases. However, when the initialized object is a variable of
467 /// incomplete array type and the initializer is an initializer
468 /// list, this type will be set to the completed array type.
469 ///
Douglas Gregor20093b42009-12-09 23:02:17 +0000470 /// \returns an expression that performs the actual object initialization, if
471 /// the initialization is well-formed. Otherwise, emits diagnostics
472 /// and returns an invalid expression.
473 Action::OwningExprResult Perform(Sema &S,
474 const InitializedEntity &Entity,
475 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +0000476 Action::MultiExprArg Args,
477 QualType *ResultType = 0);
Douglas Gregor20093b42009-12-09 23:02:17 +0000478
479 /// \brief Diagnose an potentially-invalid initialization sequence.
480 ///
481 /// \returns true if the initialization sequence was ill-formed,
482 /// false otherwise.
483 bool Diagnose(Sema &S,
484 const InitializedEntity &Entity,
485 const InitializationKind &Kind,
486 Expr **Args, unsigned NumArgs);
487
488 /// \brief Determine the kind of initialization sequence computed.
489 enum SequenceKind getKind() const { return SequenceKind; }
490
491 /// \brief Set the kind of sequence computed.
492 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
493
494 /// \brief Determine whether the initialization sequence is valid.
495 operator bool() const { return SequenceKind != FailedSequence; }
496
497 typedef llvm::SmallVector<Step, 4>::const_iterator step_iterator;
498 step_iterator step_begin() const { return Steps.begin(); }
499 step_iterator step_end() const { return Steps.end(); }
500
501 /// \brief Add a new step in the initialization that resolves the address
502 /// of an overloaded function to a specific function declaration.
503 ///
504 /// \param Function the function to which the overloaded function reference
505 /// resolves.
506 void AddAddressOverloadResolutionStep(FunctionDecl *Function);
507
508 /// \brief Add a new step in the initialization that performs a derived-to-
509 /// base cast.
510 ///
511 /// \param BaseType the base type to which we will be casting.
512 ///
513 /// \param IsLValue true if the result of this cast will be treated as
514 /// an lvalue.
515 void AddDerivedToBaseCastStep(QualType BaseType, bool IsLValue);
516
517 /// \brief Add a new step binding a reference to an object.
518 ///
519 /// \param BindingTemporary true if we are binding a reference to a temporary
520 /// object (thereby extending its lifetime); false if we are binding to an
521 /// lvalue or an lvalue treated as an rvalue.
522 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
523
524 /// \brief Add a new step invoking a conversion function, which is either
525 /// a constructor or a conversion function.
Eli Friedman03981012009-12-11 02:42:07 +0000526 void AddUserConversionStep(FunctionDecl *Function, QualType T);
Douglas Gregor20093b42009-12-09 23:02:17 +0000527
528 /// \brief Add a new step that performs a qualification conversion to the
529 /// given type.
530 void AddQualificationConversionStep(QualType Ty, bool IsLValue);
531
532 /// \brief Add a new step that applies an implicit conversion sequence.
533 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
534 QualType T);
Douglas Gregord87b61f2009-12-10 17:56:55 +0000535
536 /// \brief Add a list-initialiation step
537 void AddListInitializationStep(QualType T);
538
Douglas Gregor51c56d62009-12-14 20:49:26 +0000539 /// \brief Add a a constructor-initialization step.
540 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
541 QualType T);
542
Douglas Gregor20093b42009-12-09 23:02:17 +0000543 /// \brief Note that this initialization sequence failed.
544 void SetFailed(FailureKind Failure) {
545 SequenceKind = FailedSequence;
546 this->Failure = Failure;
547 }
548
549 /// \brief Note that this initialization sequence failed due to failed
550 /// overload resolution.
551 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
552
553 /// \brief Retrieve a reference to the candidate set when overload
554 /// resolution fails.
555 OverloadCandidateSet &getFailedCandidateSet() {
556 return FailedCandidateSet;
557 }
558
559 /// \brief Determine why initialization failed.
560 FailureKind getFailureKind() const {
561 assert(getKind() == FailedSequence && "Not an initialization failure!");
562 return Failure;
563 }
564};
565
566} // end namespace clang
567
568#endif // LLVM_CLANG_SEMA_INIT_H