blob: e1269a7e12975aae15f213e48dd36cea915e1cb1 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattnerd8b741c82009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman893abe42009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattnera9196812009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnera9196812009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000058
Eli Friedman42a84652009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000065 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattner0cb78032009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattnerd8b741c82009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000086 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000087 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Eli Friedman893abe42009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000090
Eli Friedman893abe42009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000098
Eli Friedman893abe42009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000104}
105
Chris Lattner0cb78032009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregorcde232f2009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000137namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson6cabf312010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000214
Douglas Gregor2bb07652009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner9ececce2009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000230
Douglas Gregor2bb07652009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
266 Sema::OwningExprResult MemberInit
267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000319
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000321 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor723796a2009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000354 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor723796a2009-12-16 06:35:08 +0000357
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 Sema::OwningExprResult ElementInit
377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000394 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000403
Douglas Gregor723796a2009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000408
Eli Friedman23a9e312008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000416
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000449}
450
Anders Carlsson6cabf312010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Steve Narofff8ecff22008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
461 else if (T->isStructureType() || T->isUnionType())
462 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000467
Eli Friedmane0f832b2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000483
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregor5741efb2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000507 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508 "{")
509 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000510 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000511 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000512 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000513}
514
Anders Carlsson6cabf312010-01-23 23:23:01 +0000515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000516 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000524 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor34c0a902010-02-09 00:50:06 +0000526 IList->setType(T.getNonReferenceType());
527 StructuredList->setType(T.getNonReferenceType());
Eli Friedman85f54972008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000530
Eli Friedman85f54972008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000540 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman425038c2009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000563
Chris Lattnerb0912a52009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000566 }
567 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000568
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000574}
575
Anders Carlsson6cabf312010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000608 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000627 } else {
628 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000629 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000630 assert(0 && "Unsupported initializer type");
631 }
632}
633
Anders Carlsson6cabf312010-01-23 23:23:01 +0000634void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000635 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000636 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000640 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000641 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
642 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000644 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000645 = getStructuredSubobjectInit(IList, Index, ElemType,
646 StructuredList, StructuredIndex,
647 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000648 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 newStructuredList, newStructuredIndex);
650 ++StructuredIndex;
651 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000652 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
653 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000654 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000656 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, ElemType, Index,
658 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000659 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000660 CheckReferenceType(Entity, IList, ElemType, Index,
661 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000662 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000664 // C++ [dcl.init.aggr]p12:
665 // All implicit type conversions (clause 4) are considered when
666 // initializing the aggregate member with an ini- tializer from
667 // an initializer-list. If the initializer can initialize a
668 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000669
Anders Carlsson0bd52402010-01-24 00:19:41 +0000670 // FIXME: Better EqualLoc?
671 InitializationKind Kind =
672 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
673 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
674
675 if (Seq) {
676 Sema::OwningExprResult Result =
677 Seq.Perform(SemaRef, Entity, Kind,
678 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
679 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000680 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000681
682 UpdateStructuredListElement(StructuredList, StructuredIndex,
683 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000684 ++Index;
685 return;
686 }
687
688 // Fall through for subaggregate initialization
689 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000690 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000691 //
692 // The initializer for a structure or union object that has
693 // automatic storage duration shall be either an initializer
694 // list as described below, or a single expression that has
695 // compatible structure or union type. In the latter case, the
696 // initial value of the object, including unnamed members, is
697 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000698 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000699 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000700 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
701 ++Index;
702 return;
703 }
704
705 // Fall through for subaggregate initialization
706 }
707
708 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000709 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000710 // [...] Otherwise, if the member is itself a non-empty
711 // subaggregate, brace elision is assumed and the initializer is
712 // considered for the initialization of the first member of
713 // the subaggregate.
714 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000715 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 StructuredIndex);
717 ++StructuredIndex;
718 } else {
719 // We cannot initialize this element, so let
720 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000721 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
722 SemaRef.Owned(expr));
723 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000724 hadError = true;
725 ++Index;
726 ++StructuredIndex;
727 }
728 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000729}
730
Anders Carlsson6cabf312010-01-23 23:23:01 +0000731void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000732 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000733 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000734 InitListExpr *StructuredList,
735 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000736 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000737 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000738 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000739 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000740 diag::err_many_braces_around_scalar_init)
741 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000742 hadError = true;
743 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000744 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000745 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000746 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000747 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000748 diag::err_designator_for_scalar_init)
749 << DeclType << expr->getSourceRange();
750 hadError = true;
751 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000752 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000753 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000754 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000755
Anders Carlsson26d05642010-01-23 18:35:41 +0000756 Sema::OwningExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000757 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
758 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000759
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000760 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000761
762 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000763 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000764 else {
765 ResultExpr = Result.takeAs<Expr>();
766
767 if (ResultExpr != expr) {
768 // The type was promoted, update initializer list.
769 IList->setInit(Index, ResultExpr);
770 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000771 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000772 if (hadError)
773 ++StructuredIndex;
774 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000775 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000776 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000777 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000778 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000779 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000780 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000781 ++Index;
782 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000784 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000785}
786
Anders Carlsson6cabf312010-01-23 23:23:01 +0000787void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
788 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000789 unsigned &Index,
790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
792 if (Index < IList->getNumInits()) {
793 Expr *expr = IList->getInit(Index);
794 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000795 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000796 << DeclType << IList->getSourceRange();
797 hadError = true;
798 ++Index;
799 ++StructuredIndex;
800 return;
Mike Stump11289f42009-09-09 15:08:12 +0000801 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000802
Anders Carlssona91be642010-01-29 02:47:33 +0000803 Sema::OwningExprResult Result =
804 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
805 SemaRef.Owned(expr));
806
807 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000808 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000809
810 expr = Result.takeAs<Expr>();
811 IList->setInit(Index, expr);
812
Douglas Gregord14247a2009-01-30 22:09:00 +0000813 if (hadError)
814 ++StructuredIndex;
815 else
816 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
817 ++Index;
818 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000819 // FIXME: It would be wonderful if we could point at the actual member. In
820 // general, it would be useful to pass location information down the stack,
821 // so that we know the location (or decl) of the "current object" being
822 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000823 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000824 diag::err_init_reference_member_uninitialized)
825 << DeclType
826 << IList->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832}
833
Anders Carlsson6cabf312010-01-23 23:23:01 +0000834void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000835 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000836 unsigned &Index,
837 InitListExpr *StructuredList,
838 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000839 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000840 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000841 unsigned maxElements = VT->getNumElements();
842 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000843 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000844
Nate Begeman5ec4b312009-08-10 23:49:36 +0000845 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000846 InitializedEntity ElementEntity =
847 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000848
Anders Carlsson6cabf312010-01-23 23:23:01 +0000849 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
850 // Don't attempt to go past the end of the init list
851 if (Index >= IList->getNumInits())
852 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000853
Anders Carlsson6cabf312010-01-23 23:23:01 +0000854 ElementEntity.setElementIndex(Index);
855 CheckSubElementType(ElementEntity, IList, elementType, Index,
856 StructuredList, StructuredIndex);
857 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000858 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000859 InitializedEntity ElementEntity =
860 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
861
Nate Begeman5ec4b312009-08-10 23:49:36 +0000862 // OpenCL initializers allows vectors to be constructed from vectors.
863 for (unsigned i = 0; i < maxElements; ++i) {
864 // Don't attempt to go past the end of the init list
865 if (Index >= IList->getNumInits())
866 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000867
868 ElementEntity.setElementIndex(Index);
869
Nate Begeman5ec4b312009-08-10 23:49:36 +0000870 QualType IType = IList->getInit(Index)->getType();
871 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000872 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000873 StructuredList, StructuredIndex);
874 ++numEltsInit;
875 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000876 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000877 unsigned numIElts = IVT->getNumElements();
878 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
879 numIElts);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000880 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000881 StructuredList, StructuredIndex);
882 numEltsInit += numIElts;
883 }
884 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
John Thompson7bc797b2010-04-20 23:21:17 +0000887 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000888 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000889 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000890 SemaRef.Diag(IList->getSourceRange().getBegin(),
891 diag::err_vector_incorrect_num_initializers)
892 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000893 }
894}
895
Anders Carlsson6cabf312010-01-23 23:23:01 +0000896void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000897 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000898 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000899 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000900 unsigned &Index,
901 InitListExpr *StructuredList,
902 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000903 // Check for the special-case of initializing an array with a string.
904 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000905 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
906 SemaRef.Context)) {
907 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000908 // We place the string literal directly into the resulting
909 // initializer list. This is the only place where the structure
910 // of the structured initializer list doesn't match exactly,
911 // because doing so would involve allocating one character
912 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000913 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000914 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000915 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000916 return;
917 }
918 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000919 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000920 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000921 // Check for VLAs; in standard C it would be possible to check this
922 // earlier, but I don't know where clang accepts VLAs (gcc accepts
923 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000924 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000925 diag::err_variable_object_no_init)
926 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000927 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000928 ++Index;
929 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000930 return;
931 }
932
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000933 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000934 llvm::APSInt maxElements(elementIndex.getBitWidth(),
935 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000936 bool maxElementsKnown = false;
937 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000938 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000939 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000940 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000941 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000942 maxElementsKnown = true;
943 }
944
Chris Lattnerb0912a52009-02-24 22:50:46 +0000945 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000946 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000947 while (Index < IList->getNumInits()) {
948 Expr *Init = IList->getInit(Index);
949 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000950 // If we're not the subobject that matches up with the '{' for
951 // the designator, we shouldn't be handling the
952 // designator. Return immediately.
953 if (!SubobjectIsDesignatorContext)
954 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000955
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000956 // Handle this designated initializer. elementIndex will be
957 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000958 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000959 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000960 StructuredList, StructuredIndex, true,
961 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000962 hadError = true;
963 continue;
964 }
965
Douglas Gregor033d1252009-01-23 16:54:12 +0000966 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
967 maxElements.extend(elementIndex.getBitWidth());
968 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
969 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000970 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000971
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000972 // If the array is of incomplete type, keep track of the number of
973 // elements in the initializer.
974 if (!maxElementsKnown && elementIndex > maxElements)
975 maxElements = elementIndex;
976
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000977 continue;
978 }
979
980 // If we know the maximum number of elements, and we've already
981 // hit it, stop consuming elements in the initializer list.
982 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000983 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000984
Anders Carlsson6cabf312010-01-23 23:23:01 +0000985 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000986 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000987 Entity);
988 // Check this element.
989 CheckSubElementType(ElementEntity, IList, elementType, Index,
990 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000991 ++elementIndex;
992
993 // If the array is of incomplete type, keep track of the number of
994 // elements in the initializer.
995 if (!maxElementsKnown && elementIndex > maxElements)
996 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000997 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000998 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000999 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001000 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001001 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001002 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001003 // Sizing an array implicitly to zero is not allowed by ISO C,
1004 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001005 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001006 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001008
Mike Stump11289f42009-09-09 15:08:12 +00001009 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001010 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001011 }
1012}
1013
Anders Carlsson6cabf312010-01-23 23:23:01 +00001014void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001015 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001016 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001017 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001018 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001019 unsigned &Index,
1020 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001021 unsigned &StructuredIndex,
1022 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001024
Eli Friedman23a9e312008-05-19 19:16:24 +00001025 // If the record is invalid, some of it's members are invalid. To avoid
1026 // confusion, we forgo checking the intializer for the entire record.
1027 if (structDecl->isInvalidDecl()) {
1028 hadError = true;
1029 return;
Mike Stump11289f42009-09-09 15:08:12 +00001030 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001031
1032 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1033 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001035 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001036 Field != FieldEnd; ++Field) {
1037 if (Field->getDeclName()) {
1038 StructuredList->setInitializedFieldInUnion(*Field);
1039 break;
1040 }
1041 }
1042 return;
1043 }
1044
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001045 // If structDecl is a forward declaration, this loop won't do
1046 // anything except look at designated initializers; That's okay,
1047 // because an error should get printed out elsewhere. It might be
1048 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001049 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001050 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001051 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001052 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001053 while (Index < IList->getNumInits()) {
1054 Expr *Init = IList->getInit(Index);
1055
1056 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001057 // If we're not the subobject that matches up with the '{' for
1058 // the designator, we shouldn't be handling the
1059 // designator. Return immediately.
1060 if (!SubobjectIsDesignatorContext)
1061 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001062
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001063 // Handle this designated initializer. Field will be updated to
1064 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001065 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001066 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001067 StructuredList, StructuredIndex,
1068 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001069 hadError = true;
1070
Douglas Gregora9add4e2009-02-12 19:00:39 +00001071 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001072
1073 // Disable check for missing fields when designators are used.
1074 // This matches gcc behaviour.
1075 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001076 continue;
1077 }
1078
1079 if (Field == FieldEnd) {
1080 // We've run out of fields. We're done.
1081 break;
1082 }
1083
Douglas Gregora9add4e2009-02-12 19:00:39 +00001084 // We've already initialized a member of a union. We're done.
1085 if (InitializedSomething && DeclType->isUnionType())
1086 break;
1087
Douglas Gregor91f84212008-12-11 16:49:14 +00001088 // If we've hit the flexible array member at the end, we're done.
1089 if (Field->getType()->isIncompleteArrayType())
1090 break;
1091
Douglas Gregor51695702009-01-29 16:53:55 +00001092 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001093 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001094 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001095 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001096 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001097
Anders Carlsson6cabf312010-01-23 23:23:01 +00001098 InitializedEntity MemberEntity =
1099 InitializedEntity::InitializeMember(*Field, &Entity);
1100 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1101 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001102 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001103
1104 if (DeclType->isUnionType()) {
1105 // Initialize the first field within the union.
1106 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001107 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001108
1109 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001110 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001111
John McCalle40b58e2010-03-11 19:32:38 +00001112 // Emit warnings for missing struct field initializers.
1113 if (CheckForMissingFields && Field != FieldEnd &&
1114 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1115 // It is possible we have one or more unnamed bitfields remaining.
1116 // Find first (if any) named field and emit warning.
1117 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1118 it != end; ++it) {
1119 if (!it->isUnnamedBitfield()) {
1120 SemaRef.Diag(IList->getSourceRange().getEnd(),
1121 diag::warn_missing_field_initializers) << it->getName();
1122 break;
1123 }
1124 }
1125 }
1126
Mike Stump11289f42009-09-09 15:08:12 +00001127 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001128 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001129 return;
1130
1131 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001132 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001133 (!isa<InitListExpr>(IList->getInit(Index)) ||
1134 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001135 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001136 diag::err_flexible_array_init_nonempty)
1137 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001138 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001139 << *Field;
1140 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001141 ++Index;
1142 return;
1143 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001144 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001145 diag::ext_flexible_array_init)
1146 << IList->getInit(Index)->getSourceRange().getBegin();
1147 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1148 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001149 }
1150
Anders Carlsson6cabf312010-01-23 23:23:01 +00001151 InitializedEntity MemberEntity =
1152 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001153
Anders Carlsson6cabf312010-01-23 23:23:01 +00001154 if (isa<InitListExpr>(IList->getInit(Index)))
1155 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1156 StructuredList, StructuredIndex);
1157 else
1158 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001159 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001160}
Steve Narofff8ecff22008-05-01 22:18:59 +00001161
Douglas Gregord5846a12009-04-15 06:41:24 +00001162/// \brief Expand a field designator that refers to a member of an
1163/// anonymous struct or union into a series of field designators that
1164/// refers to the field within the appropriate subobject.
1165///
1166/// Field/FieldIndex will be updated to point to the (new)
1167/// currently-designated field.
1168static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001169 DesignatedInitExpr *DIE,
1170 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001171 FieldDecl *Field,
1172 RecordDecl::field_iterator &FieldIter,
1173 unsigned &FieldIndex) {
1174 typedef DesignatedInitExpr::Designator Designator;
1175
1176 // Build the path from the current object to the member of the
1177 // anonymous struct/union (backwards).
1178 llvm::SmallVector<FieldDecl *, 4> Path;
1179 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001180
Douglas Gregord5846a12009-04-15 06:41:24 +00001181 // Build the replacement designators.
1182 llvm::SmallVector<Designator, 4> Replacements;
1183 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1184 FI = Path.rbegin(), FIEnd = Path.rend();
1185 FI != FIEnd; ++FI) {
1186 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001187 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001188 DIE->getDesignator(DesigIdx)->getDotLoc(),
1189 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1190 else
1191 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1192 SourceLocation()));
1193 Replacements.back().setField(*FI);
1194 }
1195
1196 // Expand the current designator into the set of replacement
1197 // designators, so we have a full subobject path down to where the
1198 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001199 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001200 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001201
Douglas Gregord5846a12009-04-15 06:41:24 +00001202 // Update FieldIter/FieldIndex;
1203 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001204 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001205 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001207 FieldIter != FEnd; ++FieldIter) {
1208 if (FieldIter->isUnnamedBitfield())
1209 continue;
1210
1211 if (*FieldIter == Path.back())
1212 return;
1213
1214 ++FieldIndex;
1215 }
1216
1217 assert(false && "Unable to find anonymous struct/union field");
1218}
1219
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001220/// @brief Check the well-formedness of a C99 designated initializer.
1221///
1222/// Determines whether the designated initializer @p DIE, which
1223/// resides at the given @p Index within the initializer list @p
1224/// IList, is well-formed for a current object of type @p DeclType
1225/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001226/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001227/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001228///
1229/// @param IList The initializer list in which this designated
1230/// initializer occurs.
1231///
Douglas Gregora5324162009-04-15 04:56:10 +00001232/// @param DIE The designated initializer expression.
1233///
1234/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001235///
1236/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1237/// into which the designation in @p DIE should refer.
1238///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001239/// @param NextField If non-NULL and the first designator in @p DIE is
1240/// a field, this will be set to the field declaration corresponding
1241/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001242///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001243/// @param NextElementIndex If non-NULL and the first designator in @p
1244/// DIE is an array designator or GNU array-range designator, this
1245/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001246///
1247/// @param Index Index into @p IList where the designated initializer
1248/// @p DIE occurs.
1249///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001250/// @param StructuredList The initializer list expression that
1251/// describes all of the subobject initializers in the order they'll
1252/// actually be initialized.
1253///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001254/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001255bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001256InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001257 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001258 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001259 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001260 QualType &CurrentObjectType,
1261 RecordDecl::field_iterator *NextField,
1262 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001263 unsigned &Index,
1264 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001265 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001266 bool FinishSubobjectInit,
1267 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001268 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001269 // Check the actual initialization for the designated object type.
1270 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001271
1272 // Temporarily remove the designator expression from the
1273 // initializer list that the child calls see, so that we don't try
1274 // to re-process the designator.
1275 unsigned OldIndex = Index;
1276 IList->setInit(OldIndex, DIE->getInit());
1277
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001278 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001279 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001280
1281 // Restore the designated initializer expression in the syntactic
1282 // form of the initializer list.
1283 if (IList->getInit(OldIndex) != DIE->getInit())
1284 DIE->setInit(IList->getInit(OldIndex));
1285 IList->setInit(OldIndex, DIE);
1286
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001287 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001288 }
1289
Douglas Gregora5324162009-04-15 04:56:10 +00001290 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001291 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001292 "Need a non-designated initializer list to start from");
1293
Douglas Gregora5324162009-04-15 04:56:10 +00001294 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001295 // Determine the structural initializer list that corresponds to the
1296 // current subobject.
1297 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001298 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001299 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001300 SourceRange(D->getStartLocation(),
1301 DIE->getSourceRange().getEnd()));
1302 assert(StructuredList && "Expected a structured initializer list");
1303
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001304 if (D->isFieldDesignator()) {
1305 // C99 6.7.8p7:
1306 //
1307 // If a designator has the form
1308 //
1309 // . identifier
1310 //
1311 // then the current object (defined below) shall have
1312 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001313 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001314 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001315 if (!RT) {
1316 SourceLocation Loc = D->getDotLoc();
1317 if (Loc.isInvalid())
1318 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001319 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1320 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001321 ++Index;
1322 return true;
1323 }
1324
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001325 // Note: we perform a linear search of the fields here, despite
1326 // the fact that we have a faster lookup method, because we always
1327 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001328 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001329 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001330 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001331 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001332 Field = RT->getDecl()->field_begin(),
1333 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001334 for (; Field != FieldEnd; ++Field) {
1335 if (Field->isUnnamedBitfield())
1336 continue;
1337
Douglas Gregord5846a12009-04-15 06:41:24 +00001338 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001339 break;
1340
1341 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001342 }
1343
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001344 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001345 // There was no normal field in the struct with the designated
1346 // name. Perform another lookup for this name, which may find
1347 // something that we can't designate (e.g., a member function),
1348 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001349 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001350 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001351 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001352 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001353 // Name lookup didn't find anything. Determine whether this
1354 // was a typo for another field name.
1355 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1356 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001357 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1358 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001359 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1360 ReplacementField->getDeclContext()->getLookupContext()
1361 ->Equals(RT->getDecl())) {
1362 SemaRef.Diag(D->getFieldLoc(),
1363 diag::err_field_designator_unknown_suggest)
1364 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001365 << FixItHint::CreateReplacement(D->getFieldLoc(),
1366 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001367 SemaRef.Diag(ReplacementField->getLocation(),
1368 diag::note_previous_decl)
1369 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001370 } else {
1371 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1372 << FieldName << CurrentObjectType;
1373 ++Index;
1374 return true;
1375 }
1376 } else if (!KnownField) {
1377 // Determine whether we found a field at all.
1378 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1379 }
1380
1381 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001383 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001385 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001386 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001387 ++Index;
1388 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001389 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001390
1391 if (!KnownField &&
1392 cast<RecordDecl>((ReplacementField)->getDeclContext())
1393 ->isAnonymousStructOrUnion()) {
1394 // Handle an field designator that refers to a member of an
1395 // anonymous struct or union.
1396 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1397 ReplacementField,
1398 Field, FieldIndex);
1399 D = DIE->getDesignator(DesigIdx);
1400 } else if (!KnownField) {
1401 // The replacement field comes from typo correction; find it
1402 // in the list of fields.
1403 FieldIndex = 0;
1404 Field = RT->getDecl()->field_begin();
1405 for (; Field != FieldEnd; ++Field) {
1406 if (Field->isUnnamedBitfield())
1407 continue;
1408
1409 if (ReplacementField == *Field ||
1410 Field->getIdentifier() == ReplacementField->getIdentifier())
1411 break;
1412
1413 ++FieldIndex;
1414 }
1415 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001416 } else if (!KnownField &&
1417 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001418 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001419 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1420 Field, FieldIndex);
1421 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001422 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001423
1424 // All of the fields of a union are located at the same place in
1425 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001426 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001427 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001428 StructuredList->setInitializedFieldInUnion(*Field);
1429 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001430
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001431 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001432 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001433
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434 // Make sure that our non-designated initializer list has space
1435 // for a subobject corresponding to this field.
1436 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001437 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001439 // This designator names a flexible array member.
1440 if (Field->getType()->isIncompleteArrayType()) {
1441 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001442 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001443 // We can't designate an object within the flexible array
1444 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001445 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001446 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001447 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001448 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001449 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001450 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001451 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001452 << *Field;
1453 Invalid = true;
1454 }
1455
1456 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1457 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001458 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 diag::err_flexible_array_init_needs_braces)
1460 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001461 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001462 << *Field;
1463 Invalid = true;
1464 }
1465
1466 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001467 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001468 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001469 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001470 diag::err_flexible_array_init_nonempty)
1471 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 if (Invalid) {
1478 ++Index;
1479 return true;
1480 }
1481
1482 // Initialize the array.
1483 bool prevHadError = hadError;
1484 unsigned newStructuredIndex = FieldIndex;
1485 unsigned OldIndex = Index;
1486 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001487
1488 InitializedEntity MemberEntity =
1489 InitializedEntity::InitializeMember(*Field, &Entity);
1490 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001492
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 IList->setInit(OldIndex, DIE);
1494 if (hadError && !prevHadError) {
1495 ++Field;
1496 ++FieldIndex;
1497 if (NextField)
1498 *NextField = Field;
1499 StructuredIndex = FieldIndex;
1500 return true;
1501 }
1502 } else {
1503 // Recurse to check later designated subobjects.
1504 QualType FieldType = (*Field)->getType();
1505 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001506
1507 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001508 InitializedEntity::InitializeMember(*Field, &Entity);
1509 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001510 FieldType, 0, 0, Index,
1511 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001512 true, false))
1513 return true;
1514 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001515
1516 // Find the position of the next field to be initialized in this
1517 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001518 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001519 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001520
1521 // If this the first designator, our caller will continue checking
1522 // the rest of this struct/class/union subobject.
1523 if (IsFirstDesignator) {
1524 if (NextField)
1525 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001526 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527 return false;
1528 }
1529
Douglas Gregor17bd0942009-01-28 23:36:17 +00001530 if (!FinishSubobjectInit)
1531 return false;
1532
Douglas Gregord5846a12009-04-15 06:41:24 +00001533 // We've already initialized something in the union; we're done.
1534 if (RT->getDecl()->isUnion())
1535 return hadError;
1536
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001537 // Check the remaining fields within this class/struct/union subobject.
1538 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001539
Anders Carlsson6cabf312010-01-23 23:23:01 +00001540 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001541 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001542 return hadError && !prevHadError;
1543 }
1544
1545 // C99 6.7.8p6:
1546 //
1547 // If a designator has the form
1548 //
1549 // [ constant-expression ]
1550 //
1551 // then the current object (defined below) shall have array
1552 // type and the expression shall be an integer constant
1553 // expression. If the array is of unknown size, any
1554 // nonnegative value is valid.
1555 //
1556 // Additionally, cope with the GNU extension that permits
1557 // designators of the form
1558 //
1559 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001560 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001562 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001563 << CurrentObjectType;
1564 ++Index;
1565 return true;
1566 }
1567
1568 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001569 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1570 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001572 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001573 DesignatedEndIndex = DesignatedStartIndex;
1574 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001576
Mike Stump11289f42009-09-09 15:08:12 +00001577
1578 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001579 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001580 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001581 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001582 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001583
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001584 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001585 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586 }
1587
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001588 if (isa<ConstantArrayType>(AT)) {
1589 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001590 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1591 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1592 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1593 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1594 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001595 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001597 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001598 << IndexExpr->getSourceRange();
1599 ++Index;
1600 return true;
1601 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001602 } else {
1603 // Make sure the bit-widths and signedness match.
1604 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1605 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001606 else if (DesignatedStartIndex.getBitWidth() <
1607 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001608 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1609 DesignatedStartIndex.setIsUnsigned(true);
1610 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613 // Make sure that our non-designated initializer list has space
1614 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001615 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001616 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001617 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001618
Douglas Gregor17bd0942009-01-28 23:36:17 +00001619 // Repeatedly perform subobject initializations in the range
1620 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621
Douglas Gregor17bd0942009-01-28 23:36:17 +00001622 // Move to the next designator
1623 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1624 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001625
1626 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001627 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001628
Douglas Gregor17bd0942009-01-28 23:36:17 +00001629 while (DesignatedStartIndex <= DesignatedEndIndex) {
1630 // Recurse to check later designated subobjects.
1631 QualType ElementType = AT->getElementType();
1632 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001633
1634 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001635 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001636 ElementType, 0, 0, Index,
1637 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001638 (DesignatedStartIndex == DesignatedEndIndex),
1639 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001640 return true;
1641
1642 // Move to the next index in the array that we'll be initializing.
1643 ++DesignatedStartIndex;
1644 ElementIndex = DesignatedStartIndex.getZExtValue();
1645 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001646
1647 // If this the first designator, our caller will continue checking
1648 // the rest of this array subobject.
1649 if (IsFirstDesignator) {
1650 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001652 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001653 return false;
1654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregor17bd0942009-01-28 23:36:17 +00001656 if (!FinishSubobjectInit)
1657 return false;
1658
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001659 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001660 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001661 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001662 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001664 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001665}
1666
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667// Get the structured initializer list for a subobject of type
1668// @p CurrentObjectType.
1669InitListExpr *
1670InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1671 QualType CurrentObjectType,
1672 InitListExpr *StructuredList,
1673 unsigned StructuredIndex,
1674 SourceRange InitRange) {
1675 Expr *ExistingInit = 0;
1676 if (!StructuredList)
1677 ExistingInit = SyntacticToSemantic[IList];
1678 else if (StructuredIndex < StructuredList->getNumInits())
1679 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001681 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1682 return Result;
1683
1684 if (ExistingInit) {
1685 // We are creating an initializer list that initializes the
1686 // subobjects of the current object, but there was already an
1687 // initialization that completely initialized the current
1688 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001689 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690 // struct X { int a, b; };
1691 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001692 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1694 // designated initializer re-initializes the whole
1695 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001696 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001697 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001699 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001700 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001701 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001702 << ExistingInit->getSourceRange();
1703 }
1704
Mike Stump11289f42009-09-09 15:08:12 +00001705 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001706 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1707 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001708 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001709
Douglas Gregor34c0a902010-02-09 00:50:06 +00001710 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711
Douglas Gregor6d00c992009-03-20 23:58:33 +00001712 // Pre-allocate storage for the structured initializer list.
1713 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001714 unsigned NumInits = 0;
1715 if (!StructuredList)
1716 NumInits = IList->getNumInits();
1717 else if (Index < IList->getNumInits()) {
1718 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1719 NumInits = SubList->getNumInits();
1720 }
1721
Mike Stump11289f42009-09-09 15:08:12 +00001722 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001723 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1724 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1725 NumElements = CAType->getSize().getZExtValue();
1726 // Simple heuristic so that we don't allocate a very large
1727 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001728 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001729 NumElements = 0;
1730 }
John McCall9dd450b2009-09-21 23:43:11 +00001731 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001732 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001733 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001734 RecordDecl *RDecl = RType->getDecl();
1735 if (RDecl->isUnion())
1736 NumElements = 1;
1737 else
Mike Stump11289f42009-09-09 15:08:12 +00001738 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001739 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001740 }
1741
Douglas Gregor221c9a52009-03-21 18:13:52 +00001742 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001743 NumElements = IList->getNumInits();
1744
Ted Kremenekac034612010-04-13 23:39:13 +00001745 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001746
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001747 // Link this new initializer list into the structured initializer
1748 // lists.
1749 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001750 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001751 else {
1752 Result->setSyntacticForm(IList);
1753 SyntacticToSemantic[IList] = Result;
1754 }
1755
1756 return Result;
1757}
1758
1759/// Update the initializer at index @p StructuredIndex within the
1760/// structured initializer list to the value @p expr.
1761void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1762 unsigned &StructuredIndex,
1763 Expr *expr) {
1764 // No structured initializer list to update
1765 if (!StructuredList)
1766 return;
1767
Ted Kremenekac034612010-04-13 23:39:13 +00001768 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1769 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001770 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001771 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772 diag::warn_initializer_overrides)
1773 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001774 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001775 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001776 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001777 << PrevInit->getSourceRange();
1778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 ++StructuredIndex;
1781}
1782
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001783/// Check that the given Index expression is a valid array designator
1784/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001785/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001786/// and produces a reasonable diagnostic if there is a
1787/// failure. Returns true if there was an error, false otherwise. If
1788/// everything went okay, Value will receive the value of the constant
1789/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001790static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001791CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001792 SourceLocation Loc = Index->getSourceRange().getBegin();
1793
1794 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001795 if (S.VerifyIntegerConstantExpression(Index, &Value))
1796 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001798 if (Value.isSigned() && Value.isNegative())
1799 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001800 << Value.toString(10) << Index->getSourceRange();
1801
Douglas Gregor51650d32009-01-23 21:04:18 +00001802 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803 return false;
1804}
1805
1806Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1807 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001808 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001809 OwningExprResult Init) {
1810 typedef DesignatedInitExpr::Designator ASTDesignator;
1811
1812 bool Invalid = false;
1813 llvm::SmallVector<ASTDesignator, 32> Designators;
1814 llvm::SmallVector<Expr *, 32> InitExpressions;
1815
1816 // Build designators and check array designator expressions.
1817 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1818 const Designator &D = Desig.getDesignator(Idx);
1819 switch (D.getKind()) {
1820 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001821 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001822 D.getFieldLoc()));
1823 break;
1824
1825 case Designator::ArrayDesignator: {
1826 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1827 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001828 if (!Index->isTypeDependent() &&
1829 !Index->isValueDependent() &&
1830 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001831 Invalid = true;
1832 else {
1833 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001834 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001835 D.getRBracketLoc()));
1836 InitExpressions.push_back(Index);
1837 }
1838 break;
1839 }
1840
1841 case Designator::ArrayRangeDesignator: {
1842 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1843 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1844 llvm::APSInt StartValue;
1845 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001846 bool StartDependent = StartIndex->isTypeDependent() ||
1847 StartIndex->isValueDependent();
1848 bool EndDependent = EndIndex->isTypeDependent() ||
1849 EndIndex->isValueDependent();
1850 if ((!StartDependent &&
1851 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1852 (!EndDependent &&
1853 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001855 else {
1856 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001857 if (StartDependent || EndDependent) {
1858 // Nothing to compute.
1859 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001860 EndValue.extend(StartValue.getBitWidth());
1861 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1862 StartValue.extend(EndValue.getBitWidth());
1863
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001864 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001865 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001866 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001867 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1868 Invalid = true;
1869 } else {
1870 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001871 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001872 D.getEllipsisLoc(),
1873 D.getRBracketLoc()));
1874 InitExpressions.push_back(StartIndex);
1875 InitExpressions.push_back(EndIndex);
1876 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001877 }
1878 break;
1879 }
1880 }
1881 }
1882
1883 if (Invalid || Init.isInvalid())
1884 return ExprError();
1885
1886 // Clear out the expressions within the designation.
1887 Desig.ClearExprs(*this);
1888
1889 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001890 = DesignatedInitExpr::Create(Context,
1891 Designators.data(), Designators.size(),
1892 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001893 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001894 return Owned(DIE);
1895}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001896
Douglas Gregor723796a2009-12-16 06:35:08 +00001897bool Sema::CheckInitList(const InitializedEntity &Entity,
1898 InitListExpr *&InitList, QualType &DeclType) {
1899 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001900 if (!CheckInitList.HadError())
1901 InitList = CheckInitList.getFullyStructuredList();
1902
1903 return CheckInitList.HadError();
1904}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001905
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001906//===----------------------------------------------------------------------===//
1907// Initialization entity
1908//===----------------------------------------------------------------------===//
1909
Douglas Gregor723796a2009-12-16 06:35:08 +00001910InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1911 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001912 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001913{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001914 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1915 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001916 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001917 } else {
1918 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001919 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001920 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001921}
1922
1923InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001924 CXXBaseSpecifier *Base,
1925 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001926{
1927 InitializedEntity Result;
1928 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001929 Result.Base = reinterpret_cast<uintptr_t>(Base);
1930 if (IsInheritedVirtualBase)
1931 Result.Base |= 0x01;
1932
Douglas Gregor1b303932009-12-22 15:35:07 +00001933 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001934 return Result;
1935}
1936
Douglas Gregor85dabae2009-12-16 01:38:02 +00001937DeclarationName InitializedEntity::getName() const {
1938 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001939 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001940 if (!VariableOrMember)
1941 return DeclarationName();
1942 // Fall through
1943
1944 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001945 case EK_Member:
1946 return VariableOrMember->getDeclName();
1947
1948 case EK_Result:
1949 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001950 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001951 case EK_Temporary:
1952 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001953 case EK_ArrayElement:
1954 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001955 return DeclarationName();
1956 }
1957
1958 // Silence GCC warning
1959 return DeclarationName();
1960}
1961
Douglas Gregora4b592a2009-12-19 03:01:41 +00001962DeclaratorDecl *InitializedEntity::getDecl() const {
1963 switch (getKind()) {
1964 case EK_Variable:
1965 case EK_Parameter:
1966 case EK_Member:
1967 return VariableOrMember;
1968
1969 case EK_Result:
1970 case EK_Exception:
1971 case EK_New:
1972 case EK_Temporary:
1973 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001974 case EK_ArrayElement:
1975 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001976 return 0;
1977 }
1978
1979 // Silence GCC warning
1980 return 0;
1981}
1982
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001983//===----------------------------------------------------------------------===//
1984// Initialization sequence
1985//===----------------------------------------------------------------------===//
1986
1987void InitializationSequence::Step::Destroy() {
1988 switch (Kind) {
1989 case SK_ResolveAddressOfOverloadedFunction:
1990 case SK_CastDerivedToBaseRValue:
1991 case SK_CastDerivedToBaseLValue:
1992 case SK_BindReference:
1993 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00001994 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001995 case SK_UserConversion:
1996 case SK_QualificationConversionRValue:
1997 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001998 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001999 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002000 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002001 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002002 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002003 break;
2004
2005 case SK_ConversionSequence:
2006 delete ICS;
2007 }
2008}
2009
Douglas Gregor838fcc32010-03-26 20:14:36 +00002010bool InitializationSequence::isDirectReferenceBinding() const {
2011 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2012}
2013
2014bool InitializationSequence::isAmbiguous() const {
2015 if (getKind() != FailedSequence)
2016 return false;
2017
2018 switch (getFailureKind()) {
2019 case FK_TooManyInitsForReference:
2020 case FK_ArrayNeedsInitList:
2021 case FK_ArrayNeedsInitListOrStringLiteral:
2022 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2023 case FK_NonConstLValueReferenceBindingToTemporary:
2024 case FK_NonConstLValueReferenceBindingToUnrelated:
2025 case FK_RValueReferenceBindingToLValue:
2026 case FK_ReferenceInitDropsQualifiers:
2027 case FK_ReferenceInitFailed:
2028 case FK_ConversionFailed:
2029 case FK_TooManyInitsForScalar:
2030 case FK_ReferenceBindingToInitList:
2031 case FK_InitListBadDestinationType:
2032 case FK_DefaultInitOfConst:
2033 return false;
2034
2035 case FK_ReferenceInitOverloadFailed:
2036 case FK_UserConversionOverloadFailed:
2037 case FK_ConstructorOverloadFailed:
2038 return FailedOverloadResult == OR_Ambiguous;
2039 }
2040
2041 return false;
2042}
2043
Douglas Gregorb33eed02010-04-16 22:09:46 +00002044bool InitializationSequence::isConstructorInitialization() const {
2045 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2046}
2047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002048void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002049 FunctionDecl *Function,
2050 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002051 Step S;
2052 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2053 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002054 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002055 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002056 Steps.push_back(S);
2057}
2058
2059void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2060 bool IsLValue) {
2061 Step S;
2062 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2063 S.Type = BaseType;
2064 Steps.push_back(S);
2065}
2066
2067void InitializationSequence::AddReferenceBindingStep(QualType T,
2068 bool BindingTemporary) {
2069 Step S;
2070 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2071 S.Type = T;
2072 Steps.push_back(S);
2073}
2074
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002075void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2076 Step S;
2077 S.Kind = SK_ExtraneousCopyToTemporary;
2078 S.Type = T;
2079 Steps.push_back(S);
2080}
2081
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002082void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002083 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002084 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002085 Step S;
2086 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002087 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002088 S.Function.Function = Function;
2089 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002090 Steps.push_back(S);
2091}
2092
2093void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2094 bool IsLValue) {
2095 Step S;
2096 S.Kind = IsLValue? SK_QualificationConversionLValue
2097 : SK_QualificationConversionRValue;
2098 S.Type = Ty;
2099 Steps.push_back(S);
2100}
2101
2102void InitializationSequence::AddConversionSequenceStep(
2103 const ImplicitConversionSequence &ICS,
2104 QualType T) {
2105 Step S;
2106 S.Kind = SK_ConversionSequence;
2107 S.Type = T;
2108 S.ICS = new ImplicitConversionSequence(ICS);
2109 Steps.push_back(S);
2110}
2111
Douglas Gregor51e77d52009-12-10 17:56:55 +00002112void InitializationSequence::AddListInitializationStep(QualType T) {
2113 Step S;
2114 S.Kind = SK_ListInitialization;
2115 S.Type = T;
2116 Steps.push_back(S);
2117}
2118
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002119void
2120InitializationSequence::AddConstructorInitializationStep(
2121 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002122 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002123 QualType T) {
2124 Step S;
2125 S.Kind = SK_ConstructorInitialization;
2126 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002127 S.Function.Function = Constructor;
2128 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002129 Steps.push_back(S);
2130}
2131
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002132void InitializationSequence::AddZeroInitializationStep(QualType T) {
2133 Step S;
2134 S.Kind = SK_ZeroInitialization;
2135 S.Type = T;
2136 Steps.push_back(S);
2137}
2138
Douglas Gregore1314a62009-12-18 05:02:21 +00002139void InitializationSequence::AddCAssignmentStep(QualType T) {
2140 Step S;
2141 S.Kind = SK_CAssignment;
2142 S.Type = T;
2143 Steps.push_back(S);
2144}
2145
Eli Friedman78275202009-12-19 08:11:05 +00002146void InitializationSequence::AddStringInitStep(QualType T) {
2147 Step S;
2148 S.Kind = SK_StringInit;
2149 S.Type = T;
2150 Steps.push_back(S);
2151}
2152
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002153void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2154 OverloadingResult Result) {
2155 SequenceKind = FailedSequence;
2156 this->Failure = Failure;
2157 this->FailedOverloadResult = Result;
2158}
2159
2160//===----------------------------------------------------------------------===//
2161// Attempt initialization
2162//===----------------------------------------------------------------------===//
2163
2164/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002165static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002166 const InitializedEntity &Entity,
2167 const InitializationKind &Kind,
2168 InitListExpr *InitList,
2169 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002170 // FIXME: We only perform rudimentary checking of list
2171 // initializations at this point, then assume that any list
2172 // initialization of an array, aggregate, or scalar will be
2173 // well-formed. We we actually "perform" list initialization, we'll
2174 // do all of the necessary checking. C++0x initializer lists will
2175 // force us to perform more checking here.
2176 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2177
Douglas Gregor1b303932009-12-22 15:35:07 +00002178 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002179
2180 // C++ [dcl.init]p13:
2181 // If T is a scalar type, then a declaration of the form
2182 //
2183 // T x = { a };
2184 //
2185 // is equivalent to
2186 //
2187 // T x = a;
2188 if (DestType->isScalarType()) {
2189 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2190 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2191 return;
2192 }
2193
2194 // Assume scalar initialization from a single value works.
2195 } else if (DestType->isAggregateType()) {
2196 // Assume aggregate initialization works.
2197 } else if (DestType->isVectorType()) {
2198 // Assume vector initialization works.
2199 } else if (DestType->isReferenceType()) {
2200 // FIXME: C++0x defines behavior for this.
2201 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2202 return;
2203 } else if (DestType->isRecordType()) {
2204 // FIXME: C++0x defines behavior for this
2205 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2206 }
2207
2208 // Add a general "list initialization" step.
2209 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002210}
2211
2212/// \brief Try a reference initialization that involves calling a conversion
2213/// function.
2214///
2215/// FIXME: look intos DRs 656, 896
2216static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2217 const InitializedEntity &Entity,
2218 const InitializationKind &Kind,
2219 Expr *Initializer,
2220 bool AllowRValues,
2221 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002222 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2224 QualType T1 = cv1T1.getUnqualifiedType();
2225 QualType cv2T2 = Initializer->getType();
2226 QualType T2 = cv2T2.getUnqualifiedType();
2227
2228 bool DerivedToBase;
2229 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2230 T1, T2, DerivedToBase) &&
2231 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002232 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002233
2234 // Build the candidate set directly in the initialization sequence
2235 // structure, so that it will persist if we fail.
2236 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2237 CandidateSet.clear();
2238
2239 // Determine whether we are allowed to call explicit constructors or
2240 // explicit conversion operators.
2241 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2242
2243 const RecordType *T1RecordType = 0;
2244 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2245 // The type we're converting to is a class type. Enumerate its constructors
2246 // to see if there is a suitable conversion.
2247 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2248
2249 DeclarationName ConstructorName
2250 = S.Context.DeclarationNames.getCXXConstructorName(
2251 S.Context.getCanonicalType(T1).getUnqualifiedType());
2252 DeclContext::lookup_iterator Con, ConEnd;
2253 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2254 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002255 NamedDecl *D = *Con;
2256 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2257
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002258 // Find the constructor (which may be a template).
2259 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002260 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002261 if (ConstructorTmpl)
2262 Constructor = cast<CXXConstructorDecl>(
2263 ConstructorTmpl->getTemplatedDecl());
2264 else
John McCalla0296f72010-03-19 07:35:19 +00002265 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002266
2267 if (!Constructor->isInvalidDecl() &&
2268 Constructor->isConvertingConstructor(AllowExplicit)) {
2269 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002270 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002271 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002272 &Initializer, 1, CandidateSet);
2273 else
John McCalla0296f72010-03-19 07:35:19 +00002274 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002275 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276 }
2277 }
2278 }
2279
2280 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2281 // The type we're converting from is a class type, enumerate its conversion
2282 // functions.
2283 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2284
2285 // Determine the type we are converting to. If we are allowed to
2286 // convert to an rvalue, take the type that the destination type
2287 // refers to.
2288 QualType ToType = AllowRValues? cv1T1 : DestType;
2289
John McCallad371252010-01-20 00:46:10 +00002290 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002292 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2293 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002294 NamedDecl *D = *I;
2295 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2296 if (isa<UsingShadowDecl>(D))
2297 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2298
2299 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2300 CXXConversionDecl *Conv;
2301 if (ConvTemplate)
2302 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2303 else
2304 Conv = cast<CXXConversionDecl>(*I);
2305
2306 // If the conversion function doesn't return a reference type,
2307 // it can't be considered for this conversion unless we're allowed to
2308 // consider rvalues.
2309 // FIXME: Do we need to make sure that we only consider conversion
2310 // candidates with reference-compatible results? That might be needed to
2311 // break recursion.
2312 if ((AllowExplicit || !Conv->isExplicit()) &&
2313 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2314 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002316 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 ToType, CandidateSet);
2318 else
John McCalla0296f72010-03-19 07:35:19 +00002319 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002320 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002321 }
2322 }
2323 }
2324
2325 SourceLocation DeclLoc = Initializer->getLocStart();
2326
2327 // Perform overload resolution. If it fails, return the failed result.
2328 OverloadCandidateSet::iterator Best;
2329 if (OverloadingResult Result
2330 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2331 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002333 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002334
2335 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002336 if (isa<CXXConversionDecl>(Function))
2337 T2 = Function->getResultType();
2338 else
2339 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002340
2341 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002342 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCall760af172010-02-01 03:16:54 +00002343 T2.getNonReferenceType());
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002344
2345 // Determine whether we need to perform derived-to-base or
2346 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002347 bool NewDerivedToBase = false;
2348 Sema::ReferenceCompareResult NewRefRelationship
2349 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2350 NewDerivedToBase);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002351 if (NewRefRelationship == Sema::Ref_Incompatible) {
2352 // If the type we've converted to is not reference-related to the
2353 // type we're looking for, then there is another conversion step
2354 // we need to perform to produce a temporary of the right type
2355 // that we'll be binding to.
2356 ImplicitConversionSequence ICS;
2357 ICS.setStandard();
2358 ICS.Standard = Best->FinalConversion;
2359 T2 = ICS.Standard.getToType(2);
2360 Sequence.AddConversionSequenceStep(ICS, T2);
2361 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002362 Sequence.AddDerivedToBaseCastStep(
2363 S.Context.getQualifiedType(T1,
2364 T2.getNonReferenceType().getQualifiers()),
2365 /*isLValue=*/true);
2366
2367 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2368 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2369
2370 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2371 return OR_Success;
2372}
2373
2374/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2375static void TryReferenceInitialization(Sema &S,
2376 const InitializedEntity &Entity,
2377 const InitializationKind &Kind,
2378 Expr *Initializer,
2379 InitializationSequence &Sequence) {
2380 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2381
Douglas Gregor1b303932009-12-22 15:35:07 +00002382 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002384 Qualifiers T1Quals;
2385 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002387 Qualifiers T2Quals;
2388 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002389 SourceLocation DeclLoc = Initializer->getLocStart();
2390
2391 // If the initializer is the address of an overloaded function, try
2392 // to resolve the overloaded function. If all goes well, T2 is the
2393 // type of the resulting function.
2394 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002395 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2397 T1,
John McCall16df1e52010-03-30 21:47:33 +00002398 false,
2399 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 if (!Fn) {
2401 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2402 return;
2403 }
2404
John McCall16df1e52010-03-30 21:47:33 +00002405 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 cv2T2 = Fn->getType();
2407 T2 = cv2T2.getUnqualifiedType();
2408 }
2409
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410 // Compute some basic properties of the types and the initializer.
2411 bool isLValueRef = DestType->isLValueReferenceType();
2412 bool isRValueRef = !isLValueRef;
2413 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002414 Expr::isLvalueResult InitLvalue = Initializer->isLvalue(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002415 Sema::ReferenceCompareResult RefRelationship
2416 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2417
2418 // C++0x [dcl.init.ref]p5:
2419 // A reference to type "cv1 T1" is initialized by an expression of type
2420 // "cv2 T2" as follows:
2421 //
2422 // - If the reference is an lvalue reference and the initializer
2423 // expression
2424 OverloadingResult ConvOvlResult = OR_Success;
2425 if (isLValueRef) {
2426 if (InitLvalue == Expr::LV_Valid &&
2427 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2428 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2429 // reference-compatible with "cv2 T2," or
2430 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002431 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002433 // can occur. However, we do pay attention to whether it is a bit-field
2434 // to decide whether we're actually binding to a temporary created from
2435 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002436 if (DerivedToBase)
2437 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002438 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002439 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002440 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002441 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002442 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002443 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002444 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 return;
2446 }
2447
2448 // - has a class type (i.e., T2 is a class type), where T1 is not
2449 // reference-related to T2, and can be implicitly converted to an
2450 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2451 // with "cv3 T3" (this conversion is selected by enumerating the
2452 // applicable conversion functions (13.3.1.6) and choosing the best
2453 // one through overload resolution (13.3)),
2454 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2455 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2456 Initializer,
2457 /*AllowRValues=*/false,
2458 Sequence);
2459 if (ConvOvlResult == OR_Success)
2460 return;
John McCall0d1da222010-01-12 00:44:57 +00002461 if (ConvOvlResult != OR_No_Viable_Function) {
2462 Sequence.SetOverloadFailure(
2463 InitializationSequence::FK_ReferenceInitOverloadFailed,
2464 ConvOvlResult);
2465 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002466 }
2467 }
2468
2469 // - Otherwise, the reference shall be an lvalue reference to a
2470 // non-volatile const type (i.e., cv1 shall be const), or the reference
2471 // shall be an rvalue reference and the initializer expression shall
2472 // be an rvalue.
Douglas Gregord1e08642010-01-29 19:39:15 +00002473 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002474 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2475 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2476 Sequence.SetOverloadFailure(
2477 InitializationSequence::FK_ReferenceInitOverloadFailed,
2478 ConvOvlResult);
2479 else if (isLValueRef)
2480 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2481 ? (RefRelationship == Sema::Ref_Related
2482 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2483 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2484 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2485 else
2486 Sequence.SetFailed(
2487 InitializationSequence::FK_RValueReferenceBindingToLValue);
2488
2489 return;
2490 }
2491
2492 // - If T1 and T2 are class types and
2493 if (T1->isRecordType() && T2->isRecordType()) {
2494 // - the initializer expression is an rvalue and "cv1 T1" is
2495 // reference-compatible with "cv2 T2", or
2496 if (InitLvalue != Expr::LV_Valid &&
2497 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002498 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2499 // compiler the freedom to perform a copy here or bind to the
2500 // object, while C++0x requires that we bind directly to the
2501 // object. Hence, we always bind to the object without making an
2502 // extra copy. However, in C++03 requires that we check for the
2503 // presence of a suitable copy constructor:
2504 //
2505 // The constructor that would be used to make the copy shall
2506 // be callable whether or not the copy is actually done.
2507 if (!S.getLangOptions().CPlusPlus0x)
2508 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2509
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 if (DerivedToBase)
2511 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002512 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002513 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002514 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002515 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2516 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2517 return;
2518 }
2519
2520 // - T1 is not reference-related to T2 and the initializer expression
2521 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2522 // conversion is selected by enumerating the applicable conversion
2523 // functions (13.3.1.6) and choosing the best one through overload
2524 // resolution (13.3)),
2525 if (RefRelationship == Sema::Ref_Incompatible) {
2526 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2527 Kind, Initializer,
2528 /*AllowRValues=*/true,
2529 Sequence);
2530 if (ConvOvlResult)
2531 Sequence.SetOverloadFailure(
2532 InitializationSequence::FK_ReferenceInitOverloadFailed,
2533 ConvOvlResult);
2534
2535 return;
2536 }
2537
2538 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2539 return;
2540 }
2541
2542 // - If the initializer expression is an rvalue, with T2 an array type,
2543 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2544 // is bound to the object represented by the rvalue (see 3.10).
2545 // FIXME: How can an array type be reference-compatible with anything?
2546 // Don't we mean the element types of T1 and T2?
2547
2548 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2549 // from the initializer expression using the rules for a non-reference
2550 // copy initialization (8.5). The reference is then bound to the
2551 // temporary. [...]
2552 // Determine whether we are allowed to call explicit constructors or
2553 // explicit conversion operators.
2554 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2555 ImplicitConversionSequence ICS
2556 = S.TryImplicitConversion(Initializer, cv1T1,
2557 /*SuppressUserConversions=*/false, AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002558 /*FIXME:InOverloadResolution=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559
John McCall0d1da222010-01-12 00:44:57 +00002560 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 // FIXME: Use the conversion function set stored in ICS to turn
2562 // this into an overloading ambiguity diagnostic. However, we need
2563 // to keep that set as an OverloadCandidateSet rather than as some
2564 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002565 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2566 Sequence.SetOverloadFailure(
2567 InitializationSequence::FK_ReferenceInitOverloadFailed,
2568 ConvOvlResult);
2569 else
2570 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002571 return;
2572 }
2573
2574 // [...] If T1 is reference-related to T2, cv1 must be the
2575 // same cv-qualification as, or greater cv-qualification
2576 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002577 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2578 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002579 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002580 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002581 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2582 return;
2583 }
2584
2585 // Perform the actual conversion.
2586 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2587 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2588 return;
2589}
2590
2591/// \brief Attempt character array initialization from a string literal
2592/// (C++ [dcl.init.string], C99 6.7.8).
2593static void TryStringLiteralInitialization(Sema &S,
2594 const InitializedEntity &Entity,
2595 const InitializationKind &Kind,
2596 Expr *Initializer,
2597 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002598 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002599 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002600}
2601
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002602/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2603/// enumerates the constructors of the initialized entity and performs overload
2604/// resolution to select the best.
2605static void TryConstructorInitialization(Sema &S,
2606 const InitializedEntity &Entity,
2607 const InitializationKind &Kind,
2608 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002609 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002610 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002611 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002612
2613 // Build the candidate set directly in the initialization sequence
2614 // structure, so that it will persist if we fail.
2615 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2616 CandidateSet.clear();
2617
2618 // Determine whether we are allowed to call explicit constructors or
2619 // explicit conversion operators.
2620 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2621 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002622 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002623
2624 // The type we're converting to is a class type. Enumerate its constructors
2625 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002626 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2627 assert(DestRecordType && "Constructor initialization requires record type");
2628 CXXRecordDecl *DestRecordDecl
2629 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2630
2631 DeclarationName ConstructorName
2632 = S.Context.DeclarationNames.getCXXConstructorName(
2633 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2634 DeclContext::lookup_iterator Con, ConEnd;
2635 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2636 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002637 NamedDecl *D = *Con;
2638 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002639 bool SuppressUserConversions = false;
2640
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002641 // Find the constructor (which may be a template).
2642 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002643 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002644 if (ConstructorTmpl)
2645 Constructor = cast<CXXConstructorDecl>(
2646 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002647 else {
John McCalla0296f72010-03-19 07:35:19 +00002648 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002649
2650 // If we're performing copy initialization using a copy constructor, we
2651 // suppress user-defined conversions on the arguments.
2652 // FIXME: Move constructors?
2653 if (Kind.getKind() == InitializationKind::IK_Copy &&
2654 Constructor->isCopyConstructor())
2655 SuppressUserConversions = true;
2656 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002657
2658 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002659 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002660 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002661 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002662 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002663 Args, NumArgs, CandidateSet,
2664 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002665 else
John McCalla0296f72010-03-19 07:35:19 +00002666 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002667 Args, NumArgs, CandidateSet,
2668 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002669 }
2670 }
2671
2672 SourceLocation DeclLoc = Kind.getLocation();
2673
2674 // Perform overload resolution. If it fails, return the failed result.
2675 OverloadCandidateSet::iterator Best;
2676 if (OverloadingResult Result
2677 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2678 Sequence.SetOverloadFailure(
2679 InitializationSequence::FK_ConstructorOverloadFailed,
2680 Result);
2681 return;
2682 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002683
2684 // C++0x [dcl.init]p6:
2685 // If a program calls for the default initialization of an object
2686 // of a const-qualified type T, T shall be a class type with a
2687 // user-provided default constructor.
2688 if (Kind.getKind() == InitializationKind::IK_Default &&
2689 Entity.getType().isConstQualified() &&
2690 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2691 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2692 return;
2693 }
2694
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002695 // Add the constructor initialization step. Any cv-qualification conversion is
2696 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002697 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002698 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002699 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002700 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002701}
2702
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002703/// \brief Attempt value initialization (C++ [dcl.init]p7).
2704static void TryValueInitialization(Sema &S,
2705 const InitializedEntity &Entity,
2706 const InitializationKind &Kind,
2707 InitializationSequence &Sequence) {
2708 // C++ [dcl.init]p5:
2709 //
2710 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002711 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002712
2713 // -- if T is an array type, then each element is value-initialized;
2714 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2715 T = AT->getElementType();
2716
2717 if (const RecordType *RT = T->getAs<RecordType>()) {
2718 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2719 // -- if T is a class type (clause 9) with a user-declared
2720 // constructor (12.1), then the default constructor for T is
2721 // called (and the initialization is ill-formed if T has no
2722 // accessible default constructor);
2723 //
2724 // FIXME: we really want to refer to a single subobject of the array,
2725 // but Entity doesn't have a way to capture that (yet).
2726 if (ClassDecl->hasUserDeclaredConstructor())
2727 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2728
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002729 // -- if T is a (possibly cv-qualified) non-union class type
2730 // without a user-provided constructor, then the object is
2731 // zero-initialized and, if T’s implicitly-declared default
2732 // constructor is non-trivial, that constructor is called.
2733 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2734 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2735 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002736 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002737 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2738 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002739 }
2740 }
2741
Douglas Gregor1b303932009-12-22 15:35:07 +00002742 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002743 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2744}
2745
Douglas Gregor85dabae2009-12-16 01:38:02 +00002746/// \brief Attempt default initialization (C++ [dcl.init]p6).
2747static void TryDefaultInitialization(Sema &S,
2748 const InitializedEntity &Entity,
2749 const InitializationKind &Kind,
2750 InitializationSequence &Sequence) {
2751 assert(Kind.getKind() == InitializationKind::IK_Default);
2752
2753 // C++ [dcl.init]p6:
2754 // To default-initialize an object of type T means:
2755 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002756 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002757 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2758 DestType = Array->getElementType();
2759
2760 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2761 // constructor for T is called (and the initialization is ill-formed if
2762 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002763 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00002764 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2765 Sequence);
2766 }
2767
2768 // - otherwise, no initialization is performed.
2769 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2770
2771 // If a program calls for the default initialization of an object of
2772 // a const-qualified type T, T shall be a class type with a user-provided
2773 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002774 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002775 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2776}
2777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002778/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2779/// which enumerates all conversion functions and performs overload resolution
2780/// to select the best.
2781static void TryUserDefinedConversion(Sema &S,
2782 const InitializedEntity &Entity,
2783 const InitializationKind &Kind,
2784 Expr *Initializer,
2785 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002786 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2787
Douglas Gregor1b303932009-12-22 15:35:07 +00002788 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002789 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2790 QualType SourceType = Initializer->getType();
2791 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2792 "Must have a class type to perform a user-defined conversion");
2793
2794 // Build the candidate set directly in the initialization sequence
2795 // structure, so that it will persist if we fail.
2796 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2797 CandidateSet.clear();
2798
2799 // Determine whether we are allowed to call explicit constructors or
2800 // explicit conversion operators.
2801 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2802
2803 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2804 // The type we're converting to is a class type. Enumerate its constructors
2805 // to see if there is a suitable conversion.
2806 CXXRecordDecl *DestRecordDecl
2807 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2808
2809 DeclarationName ConstructorName
2810 = S.Context.DeclarationNames.getCXXConstructorName(
2811 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2812 DeclContext::lookup_iterator Con, ConEnd;
2813 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2814 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002815 NamedDecl *D = *Con;
2816 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002817 bool SuppressUserConversions = false;
2818
Douglas Gregor540c3b02009-12-14 17:27:33 +00002819 // Find the constructor (which may be a template).
2820 CXXConstructorDecl *Constructor = 0;
2821 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002822 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002823 if (ConstructorTmpl)
2824 Constructor = cast<CXXConstructorDecl>(
2825 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002826 else {
John McCalla0296f72010-03-19 07:35:19 +00002827 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002828
2829 // If we're performing copy initialization using a copy constructor, we
2830 // suppress user-defined conversions on the arguments.
2831 // FIXME: Move constructors?
2832 if (Kind.getKind() == InitializationKind::IK_Copy &&
2833 Constructor->isCopyConstructor())
2834 SuppressUserConversions = true;
2835
2836 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002837
2838 if (!Constructor->isInvalidDecl() &&
2839 Constructor->isConvertingConstructor(AllowExplicit)) {
2840 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002841 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002842 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002843 &Initializer, 1, CandidateSet,
2844 SuppressUserConversions);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002845 else
John McCalla0296f72010-03-19 07:35:19 +00002846 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002847 &Initializer, 1, CandidateSet,
2848 SuppressUserConversions);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002849 }
2850 }
2851 }
Eli Friedman78275202009-12-19 08:11:05 +00002852
2853 SourceLocation DeclLoc = Initializer->getLocStart();
2854
Douglas Gregor540c3b02009-12-14 17:27:33 +00002855 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2856 // The type we're converting from is a class type, enumerate its conversion
2857 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002858
Eli Friedman4afe9a32009-12-20 22:12:03 +00002859 // We can only enumerate the conversion functions for a complete type; if
2860 // the type isn't complete, simply skip this step.
2861 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2862 CXXRecordDecl *SourceRecordDecl
2863 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002864
John McCallad371252010-01-20 00:46:10 +00002865 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002866 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002867 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002868 E = Conversions->end();
2869 I != E; ++I) {
2870 NamedDecl *D = *I;
2871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2872 if (isa<UsingShadowDecl>(D))
2873 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2874
2875 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2876 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002877 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002878 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002879 else
John McCallda4458e2010-03-31 01:36:47 +00002880 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002881
2882 if (AllowExplicit || !Conv->isExplicit()) {
2883 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002884 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002885 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002886 CandidateSet);
2887 else
John McCalla0296f72010-03-19 07:35:19 +00002888 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002889 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002890 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002891 }
2892 }
2893 }
2894
Douglas Gregor540c3b02009-12-14 17:27:33 +00002895 // Perform overload resolution. If it fails, return the failed result.
2896 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002897 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002898 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2899 Sequence.SetOverloadFailure(
2900 InitializationSequence::FK_UserConversionOverloadFailed,
2901 Result);
2902 return;
2903 }
John McCall0d1da222010-01-12 00:44:57 +00002904
Douglas Gregor540c3b02009-12-14 17:27:33 +00002905 FunctionDecl *Function = Best->Function;
2906
2907 if (isa<CXXConstructorDecl>(Function)) {
2908 // Add the user-defined conversion step. Any cv-qualification conversion is
2909 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00002910 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002911 return;
2912 }
2913
2914 // Add the user-defined conversion step that calls the conversion function.
2915 QualType ConvType = Function->getResultType().getNonReferenceType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00002916 if (ConvType->getAs<RecordType>()) {
2917 // If we're converting to a class type, there may be an copy if
2918 // the resulting temporary object (possible to create an object of
2919 // a base class type). That copy is not a separate conversion, so
2920 // we just make a note of the actual destination type (possibly a
2921 // base class of the type returned by the conversion function) and
2922 // let the user-defined conversion step handle the conversion.
2923 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2924 return;
2925 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002926
Douglas Gregor5ab11652010-04-17 22:01:05 +00002927 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2928
2929 // If the conversion following the call to the conversion function
2930 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00002931 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2932 Best->FinalConversion.Third) {
2933 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002934 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002935 ICS.Standard = Best->FinalConversion;
2936 Sequence.AddConversionSequenceStep(ICS, DestType);
2937 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002938}
2939
2940/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2941/// non-class type to another.
2942static void TryImplicitConversion(Sema &S,
2943 const InitializedEntity &Entity,
2944 const InitializationKind &Kind,
2945 Expr *Initializer,
2946 InitializationSequence &Sequence) {
2947 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002948 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002949 /*SuppressUserConversions=*/true,
2950 /*AllowExplicit=*/false,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002951 /*InOverloadResolution=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002952
John McCall0d1da222010-01-12 00:44:57 +00002953 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002954 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2955 return;
2956 }
2957
Douglas Gregor1b303932009-12-22 15:35:07 +00002958 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002959}
2960
2961InitializationSequence::InitializationSequence(Sema &S,
2962 const InitializedEntity &Entity,
2963 const InitializationKind &Kind,
2964 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00002965 unsigned NumArgs)
2966 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002967 ASTContext &Context = S.Context;
2968
2969 // C++0x [dcl.init]p16:
2970 // The semantics of initializers are as follows. The destination type is
2971 // the type of the object or reference being initialized and the source
2972 // type is the type of the initializer expression. The source type is not
2973 // defined when the initializer is a braced-init-list or when it is a
2974 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002975 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002976
2977 if (DestType->isDependentType() ||
2978 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2979 SequenceKind = DependentSequence;
2980 return;
2981 }
2982
2983 QualType SourceType;
2984 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002985 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002986 Initializer = Args[0];
2987 if (!isa<InitListExpr>(Initializer))
2988 SourceType = Initializer->getType();
2989 }
2990
2991 // - If the initializer is a braced-init-list, the object is
2992 // list-initialized (8.5.4).
2993 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2994 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002995 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002996 }
2997
2998 // - If the destination type is a reference type, see 8.5.3.
2999 if (DestType->isReferenceType()) {
3000 // C++0x [dcl.init.ref]p1:
3001 // A variable declared to be a T& or T&&, that is, "reference to type T"
3002 // (8.3.2), shall be initialized by an object, or function, of type T or
3003 // by an object that can be converted into a T.
3004 // (Therefore, multiple arguments are not permitted.)
3005 if (NumArgs != 1)
3006 SetFailed(FK_TooManyInitsForReference);
3007 else
3008 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3009 return;
3010 }
3011
3012 // - If the destination type is an array of characters, an array of
3013 // char16_t, an array of char32_t, or an array of wchar_t, and the
3014 // initializer is a string literal, see 8.5.2.
3015 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3016 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3017 return;
3018 }
3019
3020 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003021 if (Kind.getKind() == InitializationKind::IK_Value ||
3022 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003023 TryValueInitialization(S, Entity, Kind, *this);
3024 return;
3025 }
3026
Douglas Gregor85dabae2009-12-16 01:38:02 +00003027 // Handle default initialization.
3028 if (Kind.getKind() == InitializationKind::IK_Default){
3029 TryDefaultInitialization(S, Entity, Kind, *this);
3030 return;
3031 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033 // - Otherwise, if the destination type is an array, the program is
3034 // ill-formed.
3035 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3036 if (AT->getElementType()->isAnyCharacterType())
3037 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3038 else
3039 SetFailed(FK_ArrayNeedsInitList);
3040
3041 return;
3042 }
Eli Friedman78275202009-12-19 08:11:05 +00003043
3044 // Handle initialization in C
3045 if (!S.getLangOptions().CPlusPlus) {
3046 setSequenceKind(CAssignment);
3047 AddCAssignmentStep(DestType);
3048 return;
3049 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003050
3051 // - If the destination type is a (possibly cv-qualified) class type:
3052 if (DestType->isRecordType()) {
3053 // - If the initialization is direct-initialization, or if it is
3054 // copy-initialization where the cv-unqualified version of the
3055 // source type is the same class as, or a derived class of, the
3056 // class of the destination, constructors are considered. [...]
3057 if (Kind.getKind() == InitializationKind::IK_Direct ||
3058 (Kind.getKind() == InitializationKind::IK_Copy &&
3059 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3060 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003061 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003062 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003063 // - Otherwise (i.e., for the remaining copy-initialization cases),
3064 // user-defined conversion sequences that can convert from the source
3065 // type to the destination type or (when a conversion function is
3066 // used) to a derived class thereof are enumerated as described in
3067 // 13.3.1.4, and the best one is chosen through overload resolution
3068 // (13.3).
3069 else
3070 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3071 return;
3072 }
3073
Douglas Gregor85dabae2009-12-16 01:38:02 +00003074 if (NumArgs > 1) {
3075 SetFailed(FK_TooManyInitsForScalar);
3076 return;
3077 }
3078 assert(NumArgs == 1 && "Zero-argument case handled above");
3079
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003080 // - Otherwise, if the source type is a (possibly cv-qualified) class
3081 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003082 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003083 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3084 return;
3085 }
3086
3087 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003088 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003089 // conversions (Clause 4) will be used, if necessary, to convert the
3090 // initializer expression to the cv-unqualified version of the
3091 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003092 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003093 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3094}
3095
3096InitializationSequence::~InitializationSequence() {
3097 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3098 StepEnd = Steps.end();
3099 Step != StepEnd; ++Step)
3100 Step->Destroy();
3101}
3102
3103//===----------------------------------------------------------------------===//
3104// Perform initialization
3105//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003106static Sema::AssignmentAction
3107getAssignmentAction(const InitializedEntity &Entity) {
3108 switch(Entity.getKind()) {
3109 case InitializedEntity::EK_Variable:
3110 case InitializedEntity::EK_New:
3111 return Sema::AA_Initializing;
3112
3113 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003114 if (Entity.getDecl() &&
3115 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3116 return Sema::AA_Sending;
3117
Douglas Gregore1314a62009-12-18 05:02:21 +00003118 return Sema::AA_Passing;
3119
3120 case InitializedEntity::EK_Result:
3121 return Sema::AA_Returning;
3122
3123 case InitializedEntity::EK_Exception:
3124 case InitializedEntity::EK_Base:
3125 llvm_unreachable("No assignment action for C++-specific initialization");
3126 break;
3127
3128 case InitializedEntity::EK_Temporary:
3129 // FIXME: Can we tell apart casting vs. converting?
3130 return Sema::AA_Casting;
3131
3132 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003133 case InitializedEntity::EK_ArrayElement:
3134 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003135 return Sema::AA_Initializing;
3136 }
3137
3138 return Sema::AA_Converting;
3139}
3140
Douglas Gregor95562572010-04-24 23:45:46 +00003141/// \brief Whether we should binding a created object as a temporary when
3142/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003143static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003144 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003145 case InitializedEntity::EK_ArrayElement:
3146 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003147 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003148 case InitializedEntity::EK_New:
3149 case InitializedEntity::EK_Variable:
3150 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003151 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003152 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003153 return false;
3154
3155 case InitializedEntity::EK_Parameter:
3156 case InitializedEntity::EK_Temporary:
3157 return true;
3158 }
3159
3160 llvm_unreachable("missed an InitializedEntity kind?");
3161}
3162
Douglas Gregor95562572010-04-24 23:45:46 +00003163/// \brief Whether the given entity, when initialized with an object
3164/// created for that initialization, requires destruction.
3165static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3166 switch (Entity.getKind()) {
3167 case InitializedEntity::EK_Member:
3168 case InitializedEntity::EK_Result:
3169 case InitializedEntity::EK_New:
3170 case InitializedEntity::EK_Base:
3171 case InitializedEntity::EK_VectorElement:
3172 return false;
3173
3174 case InitializedEntity::EK_Variable:
3175 case InitializedEntity::EK_Parameter:
3176 case InitializedEntity::EK_Temporary:
3177 case InitializedEntity::EK_ArrayElement:
3178 case InitializedEntity::EK_Exception:
3179 return true;
3180 }
3181
3182 llvm_unreachable("missed an InitializedEntity kind?");
3183}
3184
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003185/// \brief Make a (potentially elidable) temporary copy of the object
3186/// provided by the given initializer by calling the appropriate copy
3187/// constructor.
3188///
3189/// \param S The Sema object used for type-checking.
3190///
3191/// \param T The type of the temporary object, which must either by
3192/// the type of the initializer expression or a superclass thereof.
3193///
3194/// \param Enter The entity being initialized.
3195///
3196/// \param CurInit The initializer expression.
3197///
3198/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3199/// is permitted in C++03 (but not C++0x) when binding a reference to
3200/// an rvalue.
3201///
3202/// \returns An expression that copies the initializer expression into
3203/// a temporary object, or an error expression if a copy could not be
3204/// created.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003205static Sema::OwningExprResult CopyObject(Sema &S,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003206 QualType T,
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003207 const InitializedEntity &Entity,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003208 Sema::OwningExprResult CurInit,
3209 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003210 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003211 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003212 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003213 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003214 Class = cast<CXXRecordDecl>(Record->getDecl());
3215 if (!Class)
3216 return move(CurInit);
3217
3218 // C++0x [class.copy]p34:
3219 // When certain criteria are met, an implementation is allowed to
3220 // omit the copy/move construction of a class object, even if the
3221 // copy/move constructor and/or destructor for the object have
3222 // side effects. [...]
3223 // - when a temporary class object that has not been bound to a
3224 // reference (12.2) would be copied/moved to a class object
3225 // with the same cv-unqualified type, the copy/move operation
3226 // can be omitted by constructing the temporary object
3227 // directly into the target of the omitted copy/move
3228 //
3229 // Note that the other three bullets are handled elsewhere. Copy
3230 // elision for return statements and throw expressions are (FIXME:
3231 // not yet) handled as part of constructor initialization, while
3232 // copy elision for exception handlers is handled by the run-time.
3233 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003234 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregore1314a62009-12-18 05:02:21 +00003235 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003236 switch (Entity.getKind()) {
3237 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003238 Loc = Entity.getReturnLoc();
3239 break;
3240
3241 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003242 Loc = Entity.getThrowLoc();
3243 break;
3244
3245 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003246 Loc = Entity.getDecl()->getLocation();
3247 break;
3248
Anders Carlsson0bd52402010-01-24 00:19:41 +00003249 case InitializedEntity::EK_ArrayElement:
3250 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003251 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003252 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003253 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003254 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003255 case InitializedEntity::EK_VectorElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003256 Loc = CurInitExpr->getLocStart();
3257 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003258 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003259
3260 // Make sure that the type we are copying is complete.
3261 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3262 return move(CurInit);
3263
Douglas Gregore1314a62009-12-18 05:02:21 +00003264 // Perform overload resolution using the class's copy constructors.
3265 DeclarationName ConstructorName
3266 = S.Context.DeclarationNames.getCXXConstructorName(
3267 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3268 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003269 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003270 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3271 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003272 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003273 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3274 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003275 !Constructor->isCopyConstructor() ||
3276 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003277 continue;
John McCalla0296f72010-03-19 07:35:19 +00003278
3279 DeclAccessPair FoundDecl
3280 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3281 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003282 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003283 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003284
3285 OverloadCandidateSet::iterator Best;
3286 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3287 case OR_Success:
3288 break;
3289
3290 case OR_No_Viable_Function:
3291 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003292 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003293 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003294 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3295 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003296 return S.ExprError();
3297
3298 case OR_Ambiguous:
3299 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003300 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003301 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003302 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3303 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003304 return S.ExprError();
3305
3306 case OR_Deleted:
3307 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003308 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003309 << CurInitExpr->getSourceRange();
3310 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3311 << Best->Function->isDeleted();
3312 return S.ExprError();
3313 }
3314
Douglas Gregor5ab11652010-04-17 22:01:05 +00003315 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3316 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3317 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003318
Anders Carlssona01874b2010-04-21 18:47:17 +00003319 S.CheckConstructorAccess(Loc, Constructor, Entity,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003320 Best->FoundDecl.getAccess());
3321
3322 if (IsExtraneousCopy) {
3323 // If this is a totally extraneous copy for C++03 reference
3324 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003325 // expression. We don't generate an (elided) copy operation here
3326 // because doing so would require us to pass down a flag to avoid
3327 // infinite recursion, where each step adds another extraneous,
3328 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003329
Douglas Gregor30b52772010-04-18 07:57:34 +00003330 // Instantiate the default arguments of any extra parameters in
3331 // the selected copy constructor, as if we were going to create a
3332 // proper call to the copy constructor.
3333 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3334 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3335 if (S.RequireCompleteType(Loc, Parm->getType(),
3336 S.PDiag(diag::err_call_incomplete_argument)))
3337 break;
3338
3339 // Build the default argument expression; we don't actually care
3340 // if this succeeds or not, because this routine will complain
3341 // if there was a problem.
3342 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3343 }
3344
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003345 return S.Owned(CurInitExpr);
3346 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003347
3348 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003349 // constructor call (we might have derived-to-base conversions, or
3350 // the copy constructor may have default arguments).
Douglas Gregor5ab11652010-04-17 22:01:05 +00003351 if (S.CompleteConstructorCall(Constructor,
3352 Sema::MultiExprArg(S,
3353 (void **)&CurInitExpr,
3354 1),
3355 Loc, ConstructorArgs))
3356 return S.ExprError();
3357
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003358 return S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003359 move_arg(ConstructorArgs));
Douglas Gregore1314a62009-12-18 05:02:21 +00003360}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003361
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003362void InitializationSequence::PrintInitLocationNote(Sema &S,
3363 const InitializedEntity &Entity) {
3364 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3365 if (Entity.getDecl()->getLocation().isInvalid())
3366 return;
3367
3368 if (Entity.getDecl()->getDeclName())
3369 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3370 << Entity.getDecl()->getDeclName();
3371 else
3372 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3373 }
3374}
3375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003376Action::OwningExprResult
3377InitializationSequence::Perform(Sema &S,
3378 const InitializedEntity &Entity,
3379 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003380 Action::MultiExprArg Args,
3381 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003382 if (SequenceKind == FailedSequence) {
3383 unsigned NumArgs = Args.size();
3384 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3385 return S.ExprError();
3386 }
3387
3388 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003389 // If the declaration is a non-dependent, incomplete array type
3390 // that has an initializer, then its type will be completed once
3391 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003392 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003393 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003394 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003395 if (const IncompleteArrayType *ArrayT
3396 = S.Context.getAsIncompleteArrayType(DeclType)) {
3397 // FIXME: We don't currently have the ability to accurately
3398 // compute the length of an initializer list without
3399 // performing full type-checking of the initializer list
3400 // (since we have to determine where braces are implicitly
3401 // introduced and such). So, we fall back to making the array
3402 // type a dependently-sized array type with no specified
3403 // bound.
3404 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3405 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003406
Douglas Gregor51e77d52009-12-10 17:56:55 +00003407 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003408 if (DeclaratorDecl *DD = Entity.getDecl()) {
3409 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3410 TypeLoc TL = TInfo->getTypeLoc();
3411 if (IncompleteArrayTypeLoc *ArrayLoc
3412 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3413 Brackets = ArrayLoc->getBracketsRange();
3414 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003415 }
3416
3417 *ResultType
3418 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3419 /*NumElts=*/0,
3420 ArrayT->getSizeModifier(),
3421 ArrayT->getIndexTypeCVRQualifiers(),
3422 Brackets);
3423 }
3424
3425 }
3426 }
3427
Eli Friedmana553d4a2009-12-22 02:35:53 +00003428 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003429 return Sema::OwningExprResult(S, Args.release()[0]);
3430
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003431 if (Args.size() == 0)
3432 return S.Owned((Expr *)0);
3433
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003434 unsigned NumArgs = Args.size();
3435 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3436 SourceLocation(),
3437 (Expr **)Args.release(),
3438 NumArgs,
3439 SourceLocation()));
3440 }
3441
Douglas Gregor85dabae2009-12-16 01:38:02 +00003442 if (SequenceKind == NoInitialization)
3443 return S.Owned((Expr *)0);
3444
Douglas Gregor1b303932009-12-22 15:35:07 +00003445 QualType DestType = Entity.getType().getNonReferenceType();
3446 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003447 // the same as Entity.getDecl()->getType() in cases involving type merging,
3448 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003449 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003450 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003451 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003452
Douglas Gregor85dabae2009-12-16 01:38:02 +00003453 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3454
3455 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3456
3457 // For initialization steps that start with a single initializer,
3458 // grab the only argument out the Args and place it into the "current"
3459 // initializer.
3460 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003461 case SK_ResolveAddressOfOverloadedFunction:
3462 case SK_CastDerivedToBaseRValue:
3463 case SK_CastDerivedToBaseLValue:
3464 case SK_BindReference:
3465 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003466 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003467 case SK_UserConversion:
3468 case SK_QualificationConversionLValue:
3469 case SK_QualificationConversionRValue:
3470 case SK_ConversionSequence:
3471 case SK_ListInitialization:
3472 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003473 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003474 assert(Args.size() == 1);
3475 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3476 if (CurInit.isInvalid())
3477 return S.ExprError();
3478 break;
3479
3480 case SK_ConstructorInitialization:
3481 case SK_ZeroInitialization:
3482 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003483 }
3484
3485 // Walk through the computed steps for the initialization sequence,
3486 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003487 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003488 for (step_iterator Step = step_begin(), StepEnd = step_end();
3489 Step != StepEnd; ++Step) {
3490 if (CurInit.isInvalid())
3491 return S.ExprError();
3492
3493 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003494 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003495
3496 switch (Step->Kind) {
3497 case SK_ResolveAddressOfOverloadedFunction:
3498 // Overload resolution determined which function invoke; update the
3499 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003500 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall760af172010-02-01 03:16:54 +00003501 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003502 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003503 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003504 break;
3505
3506 case SK_CastDerivedToBaseRValue:
3507 case SK_CastDerivedToBaseLValue: {
3508 // We have a derived-to-base cast that produces either an rvalue or an
3509 // lvalue. Perform that cast.
3510
Anders Carlssona70cff62010-04-24 19:06:50 +00003511 CXXBaseSpecifierArray BasePath;
3512
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003513 // Casts to inaccessible base classes are allowed with C-style casts.
3514 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3515 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3516 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003517 CurInitExpr->getSourceRange(),
3518 &BasePath, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003519 return S.ExprError();
3520
3521 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3522 CastExpr::CK_DerivedToBase,
Anders Carlsson975979382010-04-23 22:18:37 +00003523 (Expr*)CurInit.release(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003524 BasePath,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 Step->Kind == SK_CastDerivedToBaseLValue));
3526 break;
3527 }
3528
3529 case SK_BindReference:
3530 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3531 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3532 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003533 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534 << BitField->getDeclName()
3535 << CurInitExpr->getSourceRange();
3536 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3537 return S.ExprError();
3538 }
Anders Carlssona91be642010-01-29 02:47:33 +00003539
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003540 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003541 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003542 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3543 << Entity.getType().isVolatileQualified()
3544 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003545 PrintInitLocationNote(S, Entity);
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003546 return S.ExprError();
3547 }
3548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 // Reference binding does not have any corresponding ASTs.
3550
3551 // Check exception specifications
3552 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3553 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003554
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003555 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003556
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003557 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003558 // Reference binding does not have any corresponding ASTs.
3559
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 // Check exception specifications
3561 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3562 return S.ExprError();
3563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 break;
3565
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003566 case SK_ExtraneousCopyToTemporary:
3567 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3568 /*IsExtraneousCopy=*/true);
3569 break;
3570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571 case SK_UserConversion: {
3572 // We have a user-defined conversion that invokes either a constructor
3573 // or a conversion function.
3574 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003575 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003576 FunctionDecl *Fn = Step->Function.Function;
3577 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003578 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003579 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003580 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003581 // Build a call to the selected constructor.
3582 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3583 SourceLocation Loc = CurInitExpr->getLocStart();
3584 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003586 // Determine the arguments required to actually perform the constructor
3587 // call.
3588 if (S.CompleteConstructorCall(Constructor,
3589 Sema::MultiExprArg(S,
3590 (void **)&CurInitExpr,
3591 1),
3592 Loc, ConstructorArgs))
3593 return S.ExprError();
3594
3595 // Build the an expression that constructs a temporary.
3596 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3597 move_arg(ConstructorArgs));
3598 if (CurInit.isInvalid())
3599 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003600
Anders Carlssona01874b2010-04-21 18:47:17 +00003601 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003602 FoundFn.getAccess());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003603
3604 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003605 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3606 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3607 S.IsDerivedFrom(SourceType, Class))
3608 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003609
3610 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 } else {
3612 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003613 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003614 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003615 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003616 FoundFn);
John McCall760af172010-02-01 03:16:54 +00003617
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 // FIXME: Should we move this initialization into a separate
3619 // derived-to-base conversion? I believe the answer is "no", because
3620 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003621 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003622 FoundFn, Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 return S.ExprError();
3624
3625 // Do a little dance to make sure that CurInit has the proper
3626 // pointer.
3627 CurInit.release();
3628
3629 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003630 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3631 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003632 if (CurInit.isInvalid() || !CurInit.get())
3633 return S.ExprError();
3634
3635 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003636
3637 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003638 }
3639
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003640 bool RequiresCopy = !IsCopy &&
3641 getKind() != InitializationSequence::ReferenceBinding;
3642 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003643 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003644 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3645 CurInitExpr = static_cast<Expr *>(CurInit.get());
3646 QualType T = CurInitExpr->getType();
3647 if (const RecordType *Record = T->getAs<RecordType>()) {
3648 CXXDestructorDecl *Destructor
3649 = cast<CXXRecordDecl>(Record->getDecl())->getDestructor(S.Context);
3650 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3651 S.PDiag(diag::err_access_dtor_temp) << T);
3652 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3653 }
3654 }
3655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 CurInitExpr = CurInit.takeAs<Expr>();
3657 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
Douglas Gregor95562572010-04-24 23:45:46 +00003658 CastKind,
3659 CurInitExpr,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003660 CXXBaseSpecifierArray(),
Douglas Gregor95562572010-04-24 23:45:46 +00003661 IsLvalue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003662
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003663 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003664 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3665 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor95562572010-04-24 23:45:46 +00003666
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003667 break;
3668 }
3669
3670 case SK_QualificationConversionLValue:
3671 case SK_QualificationConversionRValue:
3672 // Perform a qualification conversion; these can never go wrong.
3673 S.ImpCastExprToType(CurInitExpr, Step->Type,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003674 CastExpr::CK_NoOp,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675 Step->Kind == SK_QualificationConversionLValue);
3676 CurInit.release();
3677 CurInit = S.Owned(CurInitExpr);
3678 break;
3679
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003680 case SK_ConversionSequence: {
3681 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3682
3683 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3684 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 return S.ExprError();
3686
3687 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003688 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003689 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003690 }
3691
Douglas Gregor51e77d52009-12-10 17:56:55 +00003692 case SK_ListInitialization: {
3693 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3694 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003695 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003696 return S.ExprError();
3697
3698 CurInit.release();
3699 CurInit = S.Owned(InitList);
3700 break;
3701 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003702
3703 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003704 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003705 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003706 = cast<CXXConstructorDecl>(Step->Function.Function);
John McCall760af172010-02-01 03:16:54 +00003707
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003708 // Build a call to the selected constructor.
3709 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3710 SourceLocation Loc = Kind.getLocation();
3711
3712 // Determine the arguments required to actually perform the constructor
3713 // call.
3714 if (S.CompleteConstructorCall(Constructor, move(Args),
3715 Loc, ConstructorArgs))
3716 return S.ExprError();
3717
Douglas Gregorb33eed02010-04-16 22:09:46 +00003718 // Build the expression that constructs a temporary.
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003719 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003720 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003721 (Kind.getKind() == InitializationKind::IK_Direct ||
3722 Kind.getKind() == InitializationKind::IK_Value)) {
3723 // An explicitly-constructed temporary, e.g., X(1, 2).
3724 unsigned NumExprs = ConstructorArgs.size();
3725 Expr **Exprs = (Expr **)ConstructorArgs.take();
3726 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3727 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3728 Constructor,
3729 Entity.getType(),
3730 Kind.getLocation(),
3731 Exprs,
3732 NumExprs,
3733 Kind.getParenRange().getEnd()));
3734 } else
3735 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3736 Constructor,
3737 move_arg(ConstructorArgs),
3738 ConstructorInitRequiresZeroInit,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003739 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003740 if (CurInit.isInvalid())
3741 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003742
3743 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003744 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003745 Step->Function.FoundDecl.getAccess());
Douglas Gregore1314a62009-12-18 05:02:21 +00003746
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003747 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003748 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003749
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003750 break;
3751 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003752
3753 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003754 step_iterator NextStep = Step;
3755 ++NextStep;
3756 if (NextStep != StepEnd &&
3757 NextStep->Kind == SK_ConstructorInitialization) {
3758 // The need for zero-initialization is recorded directly into
3759 // the call to the object's constructor within the next step.
3760 ConstructorInitRequiresZeroInit = true;
3761 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3762 S.getLangOptions().CPlusPlus &&
3763 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003764 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3765 Kind.getRange().getBegin(),
3766 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003767 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003768 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003769 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003770 break;
3771 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003772
3773 case SK_CAssignment: {
3774 QualType SourceType = CurInitExpr->getType();
3775 Sema::AssignConvertType ConvTy =
3776 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003777
3778 // If this is a call, allow conversion to a transparent union.
3779 if (ConvTy != Sema::Compatible &&
3780 Entity.getKind() == InitializedEntity::EK_Parameter &&
3781 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3782 == Sema::Compatible)
3783 ConvTy = Sema::Compatible;
3784
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003785 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003786 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3787 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003788 CurInitExpr,
3789 getAssignmentAction(Entity),
3790 &Complained)) {
3791 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003792 return S.ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003793 } else if (Complained)
3794 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003795
3796 CurInit.release();
3797 CurInit = S.Owned(CurInitExpr);
3798 break;
3799 }
Eli Friedman78275202009-12-19 08:11:05 +00003800
3801 case SK_StringInit: {
3802 QualType Ty = Step->Type;
3803 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3804 break;
3805 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003806 }
3807 }
3808
3809 return move(CurInit);
3810}
3811
3812//===----------------------------------------------------------------------===//
3813// Diagnose initialization failures
3814//===----------------------------------------------------------------------===//
3815bool InitializationSequence::Diagnose(Sema &S,
3816 const InitializedEntity &Entity,
3817 const InitializationKind &Kind,
3818 Expr **Args, unsigned NumArgs) {
3819 if (SequenceKind != FailedSequence)
3820 return false;
3821
Douglas Gregor1b303932009-12-22 15:35:07 +00003822 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003823 switch (Failure) {
3824 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003825 // FIXME: Customize for the initialized entity?
3826 if (NumArgs == 0)
3827 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3828 << DestType.getNonReferenceType();
3829 else // FIXME: diagnostic below could be better!
3830 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3831 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 break;
3833
3834 case FK_ArrayNeedsInitList:
3835 case FK_ArrayNeedsInitListOrStringLiteral:
3836 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3837 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3838 break;
3839
John McCall16df1e52010-03-30 21:47:33 +00003840 case FK_AddressOfOverloadFailed: {
3841 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003842 S.ResolveAddressOfOverloadedFunction(Args[0],
3843 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00003844 true,
3845 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846 break;
John McCall16df1e52010-03-30 21:47:33 +00003847 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848
3849 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003850 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003851 switch (FailedOverloadResult) {
3852 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003853 if (Failure == FK_UserConversionOverloadFailed)
3854 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3855 << Args[0]->getType() << DestType
3856 << Args[0]->getSourceRange();
3857 else
3858 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3859 << DestType << Args[0]->getType()
3860 << Args[0]->getSourceRange();
3861
John McCallad907772010-01-12 07:18:19 +00003862 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3863 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003864 break;
3865
3866 case OR_No_Viable_Function:
3867 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3868 << Args[0]->getType() << DestType.getNonReferenceType()
3869 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003870 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3871 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003872 break;
3873
3874 case OR_Deleted: {
3875 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3876 << Args[0]->getType() << DestType.getNonReferenceType()
3877 << Args[0]->getSourceRange();
3878 OverloadCandidateSet::iterator Best;
3879 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3880 Kind.getLocation(),
3881 Best);
3882 if (Ovl == OR_Deleted) {
3883 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3884 << Best->Function->isDeleted();
3885 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003886 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003887 }
3888 break;
3889 }
3890
3891 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003892 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003893 break;
3894 }
3895 break;
3896
3897 case FK_NonConstLValueReferenceBindingToTemporary:
3898 case FK_NonConstLValueReferenceBindingToUnrelated:
3899 S.Diag(Kind.getLocation(),
3900 Failure == FK_NonConstLValueReferenceBindingToTemporary
3901 ? diag::err_lvalue_reference_bind_to_temporary
3902 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00003903 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003904 << DestType.getNonReferenceType()
3905 << Args[0]->getType()
3906 << Args[0]->getSourceRange();
3907 break;
3908
3909 case FK_RValueReferenceBindingToLValue:
3910 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3911 << Args[0]->getSourceRange();
3912 break;
3913
3914 case FK_ReferenceInitDropsQualifiers:
3915 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3916 << DestType.getNonReferenceType()
3917 << Args[0]->getType()
3918 << Args[0]->getSourceRange();
3919 break;
3920
3921 case FK_ReferenceInitFailed:
3922 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3923 << DestType.getNonReferenceType()
3924 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3925 << Args[0]->getType()
3926 << Args[0]->getSourceRange();
3927 break;
3928
3929 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003930 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3931 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003932 << DestType
3933 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3934 << Args[0]->getType()
3935 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003936 break;
3937
3938 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003939 SourceRange R;
3940
3941 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3942 R = SourceRange(InitList->getInit(1)->getLocStart(),
3943 InitList->getLocEnd());
3944 else
3945 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003946
3947 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003948 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003949 break;
3950 }
3951
3952 case FK_ReferenceBindingToInitList:
3953 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3954 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3955 break;
3956
3957 case FK_InitListBadDestinationType:
3958 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3959 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3960 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003961
3962 case FK_ConstructorOverloadFailed: {
3963 SourceRange ArgsRange;
3964 if (NumArgs)
3965 ArgsRange = SourceRange(Args[0]->getLocStart(),
3966 Args[NumArgs - 1]->getLocEnd());
3967
3968 // FIXME: Using "DestType" for the entity we're printing is probably
3969 // bad.
3970 switch (FailedOverloadResult) {
3971 case OR_Ambiguous:
3972 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3973 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003974 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003975 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003976 break;
3977
3978 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003979 if (Kind.getKind() == InitializationKind::IK_Default &&
3980 (Entity.getKind() == InitializedEntity::EK_Base ||
3981 Entity.getKind() == InitializedEntity::EK_Member) &&
3982 isa<CXXConstructorDecl>(S.CurContext)) {
3983 // This is implicit default initialization of a member or
3984 // base within a constructor. If no viable function was
3985 // found, notify the user that she needs to explicitly
3986 // initialize this base/member.
3987 CXXConstructorDecl *Constructor
3988 = cast<CXXConstructorDecl>(S.CurContext);
3989 if (Entity.getKind() == InitializedEntity::EK_Base) {
3990 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3991 << Constructor->isImplicit()
3992 << S.Context.getTypeDeclType(Constructor->getParent())
3993 << /*base=*/0
3994 << Entity.getType();
3995
3996 RecordDecl *BaseDecl
3997 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3998 ->getDecl();
3999 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4000 << S.Context.getTagDeclType(BaseDecl);
4001 } else {
4002 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4003 << Constructor->isImplicit()
4004 << S.Context.getTypeDeclType(Constructor->getParent())
4005 << /*member=*/1
4006 << Entity.getName();
4007 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4008
4009 if (const RecordType *Record
4010 = Entity.getType()->getAs<RecordType>())
4011 S.Diag(Record->getDecl()->getLocation(),
4012 diag::note_previous_decl)
4013 << S.Context.getTagDeclType(Record->getDecl());
4014 }
4015 break;
4016 }
4017
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004018 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4019 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00004020 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4021 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004022 break;
4023
4024 case OR_Deleted: {
4025 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4026 << true << DestType << ArgsRange;
4027 OverloadCandidateSet::iterator Best;
4028 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4029 Kind.getLocation(),
4030 Best);
4031 if (Ovl == OR_Deleted) {
4032 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4033 << Best->Function->isDeleted();
4034 } else {
4035 llvm_unreachable("Inconsistent overload resolution?");
4036 }
4037 break;
4038 }
4039
4040 case OR_Success:
4041 llvm_unreachable("Conversion did not fail!");
4042 break;
4043 }
4044 break;
4045 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004046
4047 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004048 if (Entity.getKind() == InitializedEntity::EK_Member &&
4049 isa<CXXConstructorDecl>(S.CurContext)) {
4050 // This is implicit default-initialization of a const member in
4051 // a constructor. Complain that it needs to be explicitly
4052 // initialized.
4053 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4054 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4055 << Constructor->isImplicit()
4056 << S.Context.getTypeDeclType(Constructor->getParent())
4057 << /*const=*/1
4058 << Entity.getName();
4059 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4060 << Entity.getName();
4061 } else {
4062 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4063 << DestType << (bool)DestType->getAs<RecordType>();
4064 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004065 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066 }
4067
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004068 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004069 return true;
4070}
Douglas Gregore1314a62009-12-18 05:02:21 +00004071
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004072void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4073 switch (SequenceKind) {
4074 case FailedSequence: {
4075 OS << "Failed sequence: ";
4076 switch (Failure) {
4077 case FK_TooManyInitsForReference:
4078 OS << "too many initializers for reference";
4079 break;
4080
4081 case FK_ArrayNeedsInitList:
4082 OS << "array requires initializer list";
4083 break;
4084
4085 case FK_ArrayNeedsInitListOrStringLiteral:
4086 OS << "array requires initializer list or string literal";
4087 break;
4088
4089 case FK_AddressOfOverloadFailed:
4090 OS << "address of overloaded function failed";
4091 break;
4092
4093 case FK_ReferenceInitOverloadFailed:
4094 OS << "overload resolution for reference initialization failed";
4095 break;
4096
4097 case FK_NonConstLValueReferenceBindingToTemporary:
4098 OS << "non-const lvalue reference bound to temporary";
4099 break;
4100
4101 case FK_NonConstLValueReferenceBindingToUnrelated:
4102 OS << "non-const lvalue reference bound to unrelated type";
4103 break;
4104
4105 case FK_RValueReferenceBindingToLValue:
4106 OS << "rvalue reference bound to an lvalue";
4107 break;
4108
4109 case FK_ReferenceInitDropsQualifiers:
4110 OS << "reference initialization drops qualifiers";
4111 break;
4112
4113 case FK_ReferenceInitFailed:
4114 OS << "reference initialization failed";
4115 break;
4116
4117 case FK_ConversionFailed:
4118 OS << "conversion failed";
4119 break;
4120
4121 case FK_TooManyInitsForScalar:
4122 OS << "too many initializers for scalar";
4123 break;
4124
4125 case FK_ReferenceBindingToInitList:
4126 OS << "referencing binding to initializer list";
4127 break;
4128
4129 case FK_InitListBadDestinationType:
4130 OS << "initializer list for non-aggregate, non-scalar type";
4131 break;
4132
4133 case FK_UserConversionOverloadFailed:
4134 OS << "overloading failed for user-defined conversion";
4135 break;
4136
4137 case FK_ConstructorOverloadFailed:
4138 OS << "constructor overloading failed";
4139 break;
4140
4141 case FK_DefaultInitOfConst:
4142 OS << "default initialization of a const variable";
4143 break;
4144 }
4145 OS << '\n';
4146 return;
4147 }
4148
4149 case DependentSequence:
4150 OS << "Dependent sequence: ";
4151 return;
4152
4153 case UserDefinedConversion:
4154 OS << "User-defined conversion sequence: ";
4155 break;
4156
4157 case ConstructorInitialization:
4158 OS << "Constructor initialization sequence: ";
4159 break;
4160
4161 case ReferenceBinding:
4162 OS << "Reference binding: ";
4163 break;
4164
4165 case ListInitialization:
4166 OS << "List initialization: ";
4167 break;
4168
4169 case ZeroInitialization:
4170 OS << "Zero initialization\n";
4171 return;
4172
4173 case NoInitialization:
4174 OS << "No initialization\n";
4175 return;
4176
4177 case StandardConversion:
4178 OS << "Standard conversion: ";
4179 break;
4180
4181 case CAssignment:
4182 OS << "C assignment: ";
4183 break;
4184
4185 case StringInit:
4186 OS << "String initialization: ";
4187 break;
4188 }
4189
4190 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4191 if (S != step_begin()) {
4192 OS << " -> ";
4193 }
4194
4195 switch (S->Kind) {
4196 case SK_ResolveAddressOfOverloadedFunction:
4197 OS << "resolve address of overloaded function";
4198 break;
4199
4200 case SK_CastDerivedToBaseRValue:
4201 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4202 break;
4203
4204 case SK_CastDerivedToBaseLValue:
4205 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4206 break;
4207
4208 case SK_BindReference:
4209 OS << "bind reference to lvalue";
4210 break;
4211
4212 case SK_BindReferenceToTemporary:
4213 OS << "bind reference to a temporary";
4214 break;
4215
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004216 case SK_ExtraneousCopyToTemporary:
4217 OS << "extraneous C++03 copy to temporary";
4218 break;
4219
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004220 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004221 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004222 break;
4223
4224 case SK_QualificationConversionRValue:
4225 OS << "qualification conversion (rvalue)";
4226
4227 case SK_QualificationConversionLValue:
4228 OS << "qualification conversion (lvalue)";
4229 break;
4230
4231 case SK_ConversionSequence:
4232 OS << "implicit conversion sequence (";
4233 S->ICS->DebugPrint(); // FIXME: use OS
4234 OS << ")";
4235 break;
4236
4237 case SK_ListInitialization:
4238 OS << "list initialization";
4239 break;
4240
4241 case SK_ConstructorInitialization:
4242 OS << "constructor initialization";
4243 break;
4244
4245 case SK_ZeroInitialization:
4246 OS << "zero initialization";
4247 break;
4248
4249 case SK_CAssignment:
4250 OS << "C assignment";
4251 break;
4252
4253 case SK_StringInit:
4254 OS << "string initialization";
4255 break;
4256 }
4257 }
4258}
4259
4260void InitializationSequence::dump() const {
4261 dump(llvm::errs());
4262}
4263
Douglas Gregore1314a62009-12-18 05:02:21 +00004264//===----------------------------------------------------------------------===//
4265// Initialization helper functions
4266//===----------------------------------------------------------------------===//
4267Sema::OwningExprResult
4268Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4269 SourceLocation EqualLoc,
4270 OwningExprResult Init) {
4271 if (Init.isInvalid())
4272 return ExprError();
4273
4274 Expr *InitE = (Expr *)Init.get();
4275 assert(InitE && "No initialization expression?");
4276
4277 if (EqualLoc.isInvalid())
4278 EqualLoc = InitE->getLocStart();
4279
4280 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4281 EqualLoc);
4282 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4283 Init.release();
4284 return Seq.Perform(*this, Entity, Kind,
4285 MultiExprArg(*this, (void**)&InitE, 1));
4286}