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