blob: b72fede8bb27965fa4b9f0336d36401f4c76ce0d [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"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000026#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000027using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000028
Chris Lattner0cb78032009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
Chris Lattnerd8b741c82009-02-24 23:10:27 +000033static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000034 const ArrayType *AT = Context.getAsArrayType(DeclType);
35 if (!AT) return 0;
36
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000052 // char array can be initialized with a narrow string.
53 // Only allow char x[] = "foo"; not char x[] = L"foo";
54 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000055 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000056
Eli Friedman42a84652009-05-31 10:54:53 +000057 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
58 // correction from DR343): "An array with element type compatible with a
59 // qualified or unqualified version of wchar_t may be initialized by a wide
60 // string literal, optionally enclosed in braces."
61 if (Context.typesAreCompatible(Context.getWCharType(),
62 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000063 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner0cb78032009-02-24 22:27:37 +000065 return 0;
66}
67
Mike Stump11289f42009-09-09 15:08:12 +000068static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner94d2f682009-02-24 22:46:58 +000069 bool DirectInit, Sema &S) {
Chris Lattner0cb78032009-02-24 22:27:37 +000070 // Get the type before calling CheckSingleAssignmentConstraints(), since
71 // it can promote the expression.
Mike Stump11289f42009-09-09 15:08:12 +000072 QualType InitType = Init->getType();
73
Chris Lattner94d2f682009-02-24 22:46:58 +000074 if (S.getLangOptions().CPlusPlus) {
Chris Lattner0cb78032009-02-24 22:27:37 +000075 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000076 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000077 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000078 ImplicitConversionSequence ICS;
79 OverloadCandidateSet CandidateSet;
80 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
81 CandidateSet,
Douglas Gregor3e1e5272009-12-09 23:02:17 +000082 true, false, false) != OR_Ambiguous)
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000083 return S.Diag(Init->getSourceRange().getBegin(),
84 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000085 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000086 << Init->getSourceRange();
87 S.Diag(Init->getSourceRange().getBegin(),
88 diag::err_typecheck_convert_ambiguous)
89 << DeclType << Init->getType() << Init->getSourceRange();
90 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
91 return true;
92 }
Chris Lattner0cb78032009-02-24 22:27:37 +000093 return false;
94 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattner94d2f682009-02-24 22:46:58 +000096 Sema::AssignConvertType ConvTy =
97 S.CheckSingleAssignmentConstraints(DeclType, Init);
98 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000099 InitType, Init, Sema::AA_Initializing);
Chris Lattner0cb78032009-02-24 22:27:37 +0000100}
101
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000102static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
103 // Get the length of the string as parsed.
104 uint64_t StrLength =
105 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
106
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000108 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000109 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000110 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000111 // being initialized to a string literal.
112 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000113 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000114 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
116 ConstVal,
117 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000118 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000122
Eli Friedman893abe42009-05-29 18:22:49 +0000123 // C99 6.7.8p14. We have an array of character type with known size. However,
124 // the size may be smaller or larger than the string we are initializing.
125 // FIXME: Avoid truncation for 64-bit length strings.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000130
Eli Friedman893abe42009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000136}
137
Chris Lattner0cb78032009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregorcde232f2009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
156/// arguments, which contains the current the "structured" (semantic)
157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000169namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000172 bool hadError;
173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000175
176 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000178 unsigned &StructuredIndex,
179 bool TopLevelObject = false);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000180 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000182 unsigned &StructuredIndex,
183 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000184 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
185 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000186 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000187 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000188 unsigned &StructuredIndex,
189 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000190 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000194 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000198 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000202 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000205 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
206 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000209 unsigned &StructuredIndex,
210 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000211 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
212 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000213 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000216 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000236
Douglas Gregor2bb07652009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner9ececce2009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE,
256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
259 InitializedEntity MemberEntity
260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
278
279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
287
288 Sema::OwningExprResult MemberInit
289 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
290 Sema::MultiExprArg(SemaRef, 0, 0));
291 if (MemberInit.isInvalid()) {
292 hadError = true;
293 return;
294 }
295
296 if (hadError) {
297 // Do nothing
298 } else if (Init < NumInits) {
299 ILE->setInit(Init, MemberInit.takeAs<Expr>());
300 } else if (InitSeq.getKind()
301 == InitializationSequence::ConstructorInitialization) {
302 // Value-initialization requires a constructor call, so
303 // extend the initializer list to include the constructor
304 // call and make a note that we'll need to take another pass
305 // through the initializer list.
306 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
307 RequiresSecondPass = true;
308 }
309 } else if (InitListExpr *InnerILE
310 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
311 FillInValueInitializations(MemberEntity, InnerILE,
312 RequiresSecondPass);
313}
314
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000315/// Recursively replaces NULL values within the given initializer list
316/// with expressions that perform value-initialization of the
317/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000318void
319InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
320 InitListExpr *ILE,
321 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000322 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000323 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000324 SourceLocation Loc = ILE->getSourceRange().getBegin();
325 if (ILE->getSyntacticForm())
326 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000327
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000328 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 if (RType->getDecl()->isUnion() &&
330 ILE->getInitializedFieldInUnion())
331 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
332 Entity, ILE, RequiresSecondPass);
333 else {
334 unsigned Init = 0;
335 for (RecordDecl::field_iterator
336 Field = RType->getDecl()->field_begin(),
337 FieldEnd = RType->getDecl()->field_end();
338 Field != FieldEnd; ++Field) {
339 if (Field->isUnnamedBitfield())
340 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000341
Douglas Gregor2bb07652009-12-22 00:05:34 +0000342 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000343 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000344
345 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
346 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000347 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000348
Douglas Gregor2bb07652009-12-22 00:05:34 +0000349 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000350
Douglas Gregor2bb07652009-12-22 00:05:34 +0000351 // Only look at the first initialization of a union.
352 if (RType->getDecl()->isUnion())
353 break;
354 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 }
356
357 return;
Mike Stump11289f42009-09-09 15:08:12 +0000358 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000359
360 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Douglas Gregor723796a2009-12-16 06:35:08 +0000362 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000363 unsigned NumInits = ILE->getNumInits();
364 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000365 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000366 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000367 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
368 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000369 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
370 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000371 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000372 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000373 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000374 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
375 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000376 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000377 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000378
Douglas Gregor723796a2009-12-16 06:35:08 +0000379
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000381 if (hadError)
382 return;
383
Douglas Gregor723796a2009-12-16 06:35:08 +0000384 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
385 ElementEntity.setElementIndex(Init);
386
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 Sema::OwningExprResult ElementInit
398 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
399 Sema::MultiExprArg(SemaRef, 0, 0));
400 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000401 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000402 return;
403 }
404
405 if (hadError) {
406 // Do nothing
407 } else if (Init < NumInits) {
408 ILE->setInit(Init, ElementInit.takeAs<Expr>());
409 } else if (InitSeq.getKind()
410 == InitializationSequence::ConstructorInitialization) {
411 // Value-initialization requires a constructor call, so
412 // extend the initializer list to include the constructor
413 // call and make a note that we'll need to take another pass
414 // through the initializer list.
415 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
416 RequiresSecondPass = true;
417 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000418 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
420 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000421 }
422}
423
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000424
Douglas Gregor723796a2009-12-16 06:35:08 +0000425InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
426 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000427 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000428 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000429
Eli Friedman23a9e312008-05-19 19:16:24 +0000430 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000431 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000432 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000433 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000434 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
435 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000436
Douglas Gregor723796a2009-12-16 06:35:08 +0000437 if (!hadError) {
438 bool RequiresSecondPass = false;
439 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000440 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000441 FillInValueInitializations(Entity, FullyStructuredList,
442 RequiresSecondPass);
443 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000444}
445
446int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000447 // FIXME: use a proper constant
448 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000449 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000450 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000451 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
452 }
453 return maxElements;
454}
455
456int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000457 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000458 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000459 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000460 Field = structDecl->field_begin(),
461 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000462 Field != FieldEnd; ++Field) {
463 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
464 ++InitializableMembers;
465 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000466 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000467 return std::min(InitializableMembers, 1);
468 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472 QualType T, unsigned &Index,
473 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000474 unsigned &StructuredIndex,
475 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000477
Steve Narofff8ecff22008-05-01 22:18:59 +0000478 if (T->isArrayType())
479 maxElements = numArrayElements(T);
480 else if (T->isStructureType() || T->isUnionType())
481 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000482 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000483 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000484 else
485 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000486
Eli Friedmane0f832b2008-05-25 13:49:22 +0000487 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000488 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000489 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000490 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000491 hadError = true;
492 return;
493 }
494
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495 // Build a structured initializer list corresponding to this subobject.
496 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000497 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
498 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000499 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
500 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000501 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000502
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000503 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000504 unsigned StartIndex = Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000505 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000506 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000507 StructuredSubobjectInitIndex,
508 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000509 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000510 StructuredSubobjectInitList->setType(T);
511
Douglas Gregor5741efb2009-03-01 17:12:46 +0000512 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000513 // range corresponds with the end of the last initializer it used.
514 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000515 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000516 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
517 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
518 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000519}
520
Steve Naroff125d73d2008-05-06 00:23:44 +0000521void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 unsigned &Index,
523 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000524 unsigned &StructuredIndex,
525 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000526 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000527 SyntacticToSemantic[IList] = StructuredList;
528 StructuredList->setSyntacticForm(IList);
Mike Stump11289f42009-09-09 15:08:12 +0000529 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000530 StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000531 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000532 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000533 if (hadError)
534 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000535
Eli Friedman85f54972008-05-25 13:22:35 +0000536 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000537 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 if (StructuredIndex == 1 &&
539 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000540 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000541 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000542 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000543 hadError = true;
544 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000545 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000546 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000547 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000548 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000549 // Don't complain for incomplete types, since we'll get an error
550 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000551 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000552 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000553 CurrentObjectType->isArrayType()? 0 :
554 CurrentObjectType->isVectorType()? 1 :
555 CurrentObjectType->isScalarType()? 2 :
556 CurrentObjectType->isUnionType()? 3 :
557 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000558
559 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000560 if (SemaRef.getLangOptions().CPlusPlus) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Nate Begeman425038c2009-07-07 21:53:06 +0000564 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
565 DK = diag::err_excess_initializers;
566 hadError = true;
567 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000568
Chris Lattnerb0912a52009-02-24 22:50:46 +0000569 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000570 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000571 }
572 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000573
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000574 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000575 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000576 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000577 << CodeModificationHint::CreateRemoval(IList->getLocStart())
578 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000579}
580
Eli Friedman23a9e312008-05-19 19:16:24 +0000581void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000582 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000583 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000584 unsigned &Index,
585 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000586 unsigned &StructuredIndex,
587 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000588 if (DeclType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000589 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000590 } else if (DeclType->isVectorType()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000591 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000595 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000602 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
604 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000609 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
626 CheckReferenceType(IList, DeclType, Index, 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
Eli Friedman23a9e312008-05-19 19:16:24 +0000634void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000635 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 unsigned &Index,
637 InitListExpr *StructuredList,
638 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000639 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000640 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
641 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000643 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000644 = getStructuredSubobjectInit(IList, Index, ElemType,
645 StructuredList, StructuredIndex,
646 SubInitList->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +0000647 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000648 newStructuredList, newStructuredIndex);
649 ++StructuredIndex;
650 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000651 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
652 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000653 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000654 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000655 } else if (ElemType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000656 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000657 } else if (ElemType->isReferenceType()) {
658 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000659 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000660 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000661 // C++ [dcl.init.aggr]p12:
662 // All implicit type conversions (clause 4) are considered when
663 // initializing the aggregate member with an ini- tializer from
664 // an initializer-list. If the initializer can initialize a
665 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000666 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000667 = SemaRef.TryCopyInitialization(expr, ElemType,
668 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000669 /*ForceRValue=*/false,
670 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000671
Douglas Gregord14247a2009-01-30 22:09:00 +0000672 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000674 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000675 hadError = true;
676 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
677 ++Index;
678 return;
679 }
680
681 // Fall through for subaggregate initialization
682 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000683 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000684 //
685 // The initializer for a structure or union object that has
686 // automatic storage duration shall be either an initializer
687 // list as described below, or a single expression that has
688 // compatible structure or union type. In the latter case, the
689 // initial value of the object, including unnamed members, is
690 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000691 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000692 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000693 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
694 ++Index;
695 return;
696 }
697
698 // Fall through for subaggregate initialization
699 }
700
701 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000702 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 // [...] Otherwise, if the member is itself a non-empty
704 // subaggregate, brace elision is assumed and the initializer is
705 // considered for the initialization of the first member of
706 // the subaggregate.
707 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000708 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 StructuredIndex);
710 ++StructuredIndex;
711 } else {
712 // We cannot initialize this element, so let
713 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000714 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000715 hadError = true;
716 ++Index;
717 ++StructuredIndex;
718 }
719 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000720}
721
Douglas Gregord14247a2009-01-30 22:09:00 +0000722void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000723 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000724 InitListExpr *StructuredList,
725 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000726 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000727 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000728 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000729 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000730 diag::err_many_braces_around_scalar_init)
731 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000732 hadError = true;
733 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000734 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000735 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000736 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000737 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000738 diag::err_designator_for_scalar_init)
739 << DeclType << expr->getSourceRange();
740 hadError = true;
741 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000742 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000743 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000744 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000745
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000746 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000747 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000749 else if (savExpr != expr) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000750 // The type was promoted, update initializer list.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000751 IList->setInit(Index, expr);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000752 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000753 if (hadError)
754 ++StructuredIndex;
755 else
756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000757 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000758 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000759 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000760 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000761 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000762 ++Index;
763 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000764 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000765 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000766}
767
Douglas Gregord14247a2009-01-30 22:09:00 +0000768void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
769 unsigned &Index,
770 InitListExpr *StructuredList,
771 unsigned &StructuredIndex) {
772 if (Index < IList->getNumInits()) {
773 Expr *expr = IList->getInit(Index);
774 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000775 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000776 << DeclType << IList->getSourceRange();
777 hadError = true;
778 ++Index;
779 ++StructuredIndex;
780 return;
Mike Stump11289f42009-09-09 15:08:12 +0000781 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000782
783 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000784 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000785 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000786 /*SuppressUserConversions=*/false,
787 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000788 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000789 hadError = true;
790 else if (savExpr != expr) {
791 // The type was promoted, update initializer list.
792 IList->setInit(Index, expr);
793 }
794 if (hadError)
795 ++StructuredIndex;
796 else
797 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
798 ++Index;
799 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000800 // FIXME: It would be wonderful if we could point at the actual member. In
801 // general, it would be useful to pass location information down the stack,
802 // so that we know the location (or decl) of the "current object" being
803 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000804 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000805 diag::err_init_reference_member_uninitialized)
806 << DeclType
807 << IList->getSourceRange();
808 hadError = true;
809 ++Index;
810 ++StructuredIndex;
811 return;
812 }
813}
814
Mike Stump11289f42009-09-09 15:08:12 +0000815void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000816 unsigned &Index,
817 InitListExpr *StructuredList,
818 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000819 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000820 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000821 unsigned maxElements = VT->getNumElements();
822 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000823 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000824
Nate Begeman5ec4b312009-08-10 23:49:36 +0000825 if (!SemaRef.getLangOptions().OpenCL) {
826 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
827 // Don't attempt to go past the end of the init list
828 if (Index >= IList->getNumInits())
829 break;
830 CheckSubElementType(IList, elementType, Index,
831 StructuredList, StructuredIndex);
832 }
833 } else {
834 // OpenCL initializers allows vectors to be constructed from vectors.
835 for (unsigned i = 0; i < maxElements; ++i) {
836 // Don't attempt to go past the end of the init list
837 if (Index >= IList->getNumInits())
838 break;
839 QualType IType = IList->getInit(Index)->getType();
840 if (!IType->isVectorType()) {
841 CheckSubElementType(IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 ++numEltsInit;
844 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000845 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000846 unsigned numIElts = IVT->getNumElements();
847 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
848 numIElts);
849 CheckSubElementType(IList, VecType, Index,
850 StructuredList, StructuredIndex);
851 numEltsInit += numIElts;
852 }
853 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000854 }
Mike Stump11289f42009-09-09 15:08:12 +0000855
Nate Begeman5ec4b312009-08-10 23:49:36 +0000856 // OpenCL & AltiVec require all elements to be initialized.
857 if (numEltsInit != maxElements)
858 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
859 SemaRef.Diag(IList->getSourceRange().getBegin(),
860 diag::err_vector_incorrect_num_initializers)
861 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000862 }
863}
864
Mike Stump11289f42009-09-09 15:08:12 +0000865void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000866 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000867 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000868 unsigned &Index,
869 InitListExpr *StructuredList,
870 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000871 // Check for the special-case of initializing an array with a string.
872 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000873 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
874 SemaRef.Context)) {
875 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000876 // We place the string literal directly into the resulting
877 // initializer list. This is the only place where the structure
878 // of the structured initializer list doesn't match exactly,
879 // because doing so would involve allocating one character
880 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000881 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000882 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000883 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000884 return;
885 }
886 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000887 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000888 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000889 // Check for VLAs; in standard C it would be possible to check this
890 // earlier, but I don't know where clang accepts VLAs (gcc accepts
891 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000892 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000893 diag::err_variable_object_no_init)
894 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000895 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000896 ++Index;
897 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000898 return;
899 }
900
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000901 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000902 llvm::APSInt maxElements(elementIndex.getBitWidth(),
903 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000904 bool maxElementsKnown = false;
905 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000906 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000907 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000908 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000909 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000910 maxElementsKnown = true;
911 }
912
Chris Lattnerb0912a52009-02-24 22:50:46 +0000913 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000914 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000915 while (Index < IList->getNumInits()) {
916 Expr *Init = IList->getInit(Index);
917 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000918 // If we're not the subobject that matches up with the '{' for
919 // the designator, we shouldn't be handling the
920 // designator. Return immediately.
921 if (!SubobjectIsDesignatorContext)
922 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000923
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000924 // Handle this designated initializer. elementIndex will be
925 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000926 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000927 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000928 StructuredList, StructuredIndex, true,
929 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000930 hadError = true;
931 continue;
932 }
933
Douglas Gregor033d1252009-01-23 16:54:12 +0000934 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
935 maxElements.extend(elementIndex.getBitWidth());
936 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
937 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000938 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000939
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000940 // If the array is of incomplete type, keep track of the number of
941 // elements in the initializer.
942 if (!maxElementsKnown && elementIndex > maxElements)
943 maxElements = elementIndex;
944
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000945 continue;
946 }
947
948 // If we know the maximum number of elements, and we've already
949 // hit it, stop consuming elements in the initializer list.
950 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000951 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000952
953 // Check this element.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000954 CheckSubElementType(IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000955 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000956 ++elementIndex;
957
958 // If the array is of incomplete type, keep track of the number of
959 // elements in the initializer.
960 if (!maxElementsKnown && elementIndex > maxElements)
961 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000962 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000963 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000964 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000965 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000966 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000967 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000968 // Sizing an array implicitly to zero is not allowed by ISO C,
969 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000970 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000971 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000972 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000973
Mike Stump11289f42009-09-09 15:08:12 +0000974 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000975 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000976 }
977}
978
Mike Stump11289f42009-09-09 15:08:12 +0000979void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
980 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000981 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +0000982 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000983 unsigned &Index,
984 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000985 unsigned &StructuredIndex,
986 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000987 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000988
Eli Friedman23a9e312008-05-19 19:16:24 +0000989 // If the record is invalid, some of it's members are invalid. To avoid
990 // confusion, we forgo checking the intializer for the entire record.
991 if (structDecl->isInvalidDecl()) {
992 hadError = true;
993 return;
Mike Stump11289f42009-09-09 15:08:12 +0000994 }
Douglas Gregor0202cb42009-01-29 17:44:32 +0000995
996 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
997 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000998 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000999 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001000 Field != FieldEnd; ++Field) {
1001 if (Field->getDeclName()) {
1002 StructuredList->setInitializedFieldInUnion(*Field);
1003 break;
1004 }
1005 }
1006 return;
1007 }
1008
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001009 // If structDecl is a forward declaration, this loop won't do
1010 // anything except look at designated initializers; That's okay,
1011 // because an error should get printed out elsewhere. It might be
1012 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001014 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001015 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001016 while (Index < IList->getNumInits()) {
1017 Expr *Init = IList->getInit(Index);
1018
1019 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001020 // If we're not the subobject that matches up with the '{' for
1021 // the designator, we shouldn't be handling the
1022 // designator. Return immediately.
1023 if (!SubobjectIsDesignatorContext)
1024 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001025
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001026 // Handle this designated initializer. Field will be updated to
1027 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001028 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001029 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001030 StructuredList, StructuredIndex,
1031 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001032 hadError = true;
1033
Douglas Gregora9add4e2009-02-12 19:00:39 +00001034 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001035 continue;
1036 }
1037
1038 if (Field == FieldEnd) {
1039 // We've run out of fields. We're done.
1040 break;
1041 }
1042
Douglas Gregora9add4e2009-02-12 19:00:39 +00001043 // We've already initialized a member of a union. We're done.
1044 if (InitializedSomething && DeclType->isUnionType())
1045 break;
1046
Douglas Gregor91f84212008-12-11 16:49:14 +00001047 // If we've hit the flexible array member at the end, we're done.
1048 if (Field->getType()->isIncompleteArrayType())
1049 break;
1050
Douglas Gregor51695702009-01-29 16:53:55 +00001051 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001052 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001053 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001054 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001055 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001056
Douglas Gregorf6d27522009-01-29 00:39:20 +00001057 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001058 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001059 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001060
1061 if (DeclType->isUnionType()) {
1062 // Initialize the first field within the union.
1063 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001064 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001065
1066 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001067 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001068
Mike Stump11289f42009-09-09 15:08:12 +00001069 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001070 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001071 return;
1072
1073 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001075 (!isa<InitListExpr>(IList->getInit(Index)) ||
1076 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001077 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001078 diag::err_flexible_array_init_nonempty)
1079 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001080 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001081 << *Field;
1082 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001083 ++Index;
1084 return;
1085 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001086 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001087 diag::ext_flexible_array_init)
1088 << IList->getInit(Index)->getSourceRange().getBegin();
1089 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1090 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001091 }
1092
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001093 if (isa<InitListExpr>(IList->getInit(Index)))
1094 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1095 StructuredIndex);
1096 else
1097 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1098 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001099}
Steve Narofff8ecff22008-05-01 22:18:59 +00001100
Douglas Gregord5846a12009-04-15 06:41:24 +00001101/// \brief Expand a field designator that refers to a member of an
1102/// anonymous struct or union into a series of field designators that
1103/// refers to the field within the appropriate subobject.
1104///
1105/// Field/FieldIndex will be updated to point to the (new)
1106/// currently-designated field.
1107static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001108 DesignatedInitExpr *DIE,
1109 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001110 FieldDecl *Field,
1111 RecordDecl::field_iterator &FieldIter,
1112 unsigned &FieldIndex) {
1113 typedef DesignatedInitExpr::Designator Designator;
1114
1115 // Build the path from the current object to the member of the
1116 // anonymous struct/union (backwards).
1117 llvm::SmallVector<FieldDecl *, 4> Path;
1118 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregord5846a12009-04-15 06:41:24 +00001120 // Build the replacement designators.
1121 llvm::SmallVector<Designator, 4> Replacements;
1122 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1123 FI = Path.rbegin(), FIEnd = Path.rend();
1124 FI != FIEnd; ++FI) {
1125 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001126 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001127 DIE->getDesignator(DesigIdx)->getDotLoc(),
1128 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1129 else
1130 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1131 SourceLocation()));
1132 Replacements.back().setField(*FI);
1133 }
1134
1135 // Expand the current designator into the set of replacement
1136 // designators, so we have a full subobject path down to where the
1137 // member of the anonymous struct/union is actually stored.
Mike Stump11289f42009-09-09 15:08:12 +00001138 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001139 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001140
Douglas Gregord5846a12009-04-15 06:41:24 +00001141 // Update FieldIter/FieldIndex;
1142 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001143 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001144 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001145 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001146 FieldIter != FEnd; ++FieldIter) {
1147 if (FieldIter->isUnnamedBitfield())
1148 continue;
1149
1150 if (*FieldIter == Path.back())
1151 return;
1152
1153 ++FieldIndex;
1154 }
1155
1156 assert(false && "Unable to find anonymous struct/union field");
1157}
1158
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001159/// @brief Check the well-formedness of a C99 designated initializer.
1160///
1161/// Determines whether the designated initializer @p DIE, which
1162/// resides at the given @p Index within the initializer list @p
1163/// IList, is well-formed for a current object of type @p DeclType
1164/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001165/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001166/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001167///
1168/// @param IList The initializer list in which this designated
1169/// initializer occurs.
1170///
Douglas Gregora5324162009-04-15 04:56:10 +00001171/// @param DIE The designated initializer expression.
1172///
1173/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001174///
1175/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1176/// into which the designation in @p DIE should refer.
1177///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001178/// @param NextField If non-NULL and the first designator in @p DIE is
1179/// a field, this will be set to the field declaration corresponding
1180/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001181///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001182/// @param NextElementIndex If non-NULL and the first designator in @p
1183/// DIE is an array designator or GNU array-range designator, this
1184/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185///
1186/// @param Index Index into @p IList where the designated initializer
1187/// @p DIE occurs.
1188///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001189/// @param StructuredList The initializer list expression that
1190/// describes all of the subobject initializers in the order they'll
1191/// actually be initialized.
1192///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001194bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001195InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001196 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001197 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001198 QualType &CurrentObjectType,
1199 RecordDecl::field_iterator *NextField,
1200 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001201 unsigned &Index,
1202 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001203 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001204 bool FinishSubobjectInit,
1205 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001206 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001207 // Check the actual initialization for the designated object type.
1208 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001209
1210 // Temporarily remove the designator expression from the
1211 // initializer list that the child calls see, so that we don't try
1212 // to re-process the designator.
1213 unsigned OldIndex = Index;
1214 IList->setInit(OldIndex, DIE->getInit());
1215
1216 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001217 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001218
1219 // Restore the designated initializer expression in the syntactic
1220 // form of the initializer list.
1221 if (IList->getInit(OldIndex) != DIE->getInit())
1222 DIE->setInit(IList->getInit(OldIndex));
1223 IList->setInit(OldIndex, DIE);
1224
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001225 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001226 }
1227
Douglas Gregora5324162009-04-15 04:56:10 +00001228 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001229 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001230 "Need a non-designated initializer list to start from");
1231
Douglas Gregora5324162009-04-15 04:56:10 +00001232 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001233 // Determine the structural initializer list that corresponds to the
1234 // current subobject.
1235 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001236 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001237 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001238 SourceRange(D->getStartLocation(),
1239 DIE->getSourceRange().getEnd()));
1240 assert(StructuredList && "Expected a structured initializer list");
1241
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001242 if (D->isFieldDesignator()) {
1243 // C99 6.7.8p7:
1244 //
1245 // If a designator has the form
1246 //
1247 // . identifier
1248 //
1249 // then the current object (defined below) shall have
1250 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001251 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001252 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001253 if (!RT) {
1254 SourceLocation Loc = D->getDotLoc();
1255 if (Loc.isInvalid())
1256 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001257 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1258 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001259 ++Index;
1260 return true;
1261 }
1262
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001263 // Note: we perform a linear search of the fields here, despite
1264 // the fact that we have a faster lookup method, because we always
1265 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001266 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001267 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001268 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001269 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001270 Field = RT->getDecl()->field_begin(),
1271 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001272 for (; Field != FieldEnd; ++Field) {
1273 if (Field->isUnnamedBitfield())
1274 continue;
1275
Douglas Gregord5846a12009-04-15 06:41:24 +00001276 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001277 break;
1278
1279 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001280 }
1281
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001282 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001283 // There was no normal field in the struct with the designated
1284 // name. Perform another lookup for this name, which may find
1285 // something that we can't designate (e.g., a member function),
1286 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001287 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001288 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001289 if (Lookup.first == Lookup.second) {
1290 // Name lookup didn't find anything.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001291 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001292 << FieldName << CurrentObjectType;
Douglas Gregord5846a12009-04-15 06:41:24 +00001293 ++Index;
1294 return true;
1295 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1296 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1297 ->isAnonymousStructOrUnion()) {
1298 // Handle an field designator that refers to a member of an
1299 // anonymous struct or union.
Mike Stump11289f42009-09-09 15:08:12 +00001300 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001301 cast<FieldDecl>(*Lookup.first),
1302 Field, FieldIndex);
Eli Friedman8d25b092009-04-16 17:49:48 +00001303 D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304 } else {
1305 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001306 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001307 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001308 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001309 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001310 ++Index;
1311 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001312 }
1313 } else if (!KnownField &&
1314 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001315 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001316 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1317 Field, FieldIndex);
1318 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001319 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001320
1321 // All of the fields of a union are located at the same place in
1322 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001323 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001324 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001325 StructuredList->setInitializedFieldInUnion(*Field);
1326 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001327
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001328 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001329 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001331 // Make sure that our non-designated initializer list has space
1332 // for a subobject corresponding to this field.
1333 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001334 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001335
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001336 // This designator names a flexible array member.
1337 if (Field->getType()->isIncompleteArrayType()) {
1338 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001339 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001340 // We can't designate an object within the flexible array
1341 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001342 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001343 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001344 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001345 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001346 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001347 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001348 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001349 << *Field;
1350 Invalid = true;
1351 }
1352
1353 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1354 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001355 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001356 diag::err_flexible_array_init_needs_braces)
1357 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001358 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001359 << *Field;
1360 Invalid = true;
1361 }
1362
1363 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001364 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001365 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001366 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001367 diag::err_flexible_array_init_nonempty)
1368 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001369 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001370 << *Field;
1371 Invalid = true;
1372 }
1373
1374 if (Invalid) {
1375 ++Index;
1376 return true;
1377 }
1378
1379 // Initialize the array.
1380 bool prevHadError = hadError;
1381 unsigned newStructuredIndex = FieldIndex;
1382 unsigned OldIndex = Index;
1383 IList->setInit(Index, DIE->getInit());
Mike Stump11289f42009-09-09 15:08:12 +00001384 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001385 StructuredList, newStructuredIndex);
1386 IList->setInit(OldIndex, DIE);
1387 if (hadError && !prevHadError) {
1388 ++Field;
1389 ++FieldIndex;
1390 if (NextField)
1391 *NextField = Field;
1392 StructuredIndex = FieldIndex;
1393 return true;
1394 }
1395 } else {
1396 // Recurse to check later designated subobjects.
1397 QualType FieldType = (*Field)->getType();
1398 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001399 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1400 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001401 true, false))
1402 return true;
1403 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001404
1405 // Find the position of the next field to be initialized in this
1406 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001407 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001408 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001409
1410 // If this the first designator, our caller will continue checking
1411 // the rest of this struct/class/union subobject.
1412 if (IsFirstDesignator) {
1413 if (NextField)
1414 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001415 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001416 return false;
1417 }
1418
Douglas Gregor17bd0942009-01-28 23:36:17 +00001419 if (!FinishSubobjectInit)
1420 return false;
1421
Douglas Gregord5846a12009-04-15 06:41:24 +00001422 // We've already initialized something in the union; we're done.
1423 if (RT->getDecl()->isUnion())
1424 return hadError;
1425
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001426 // Check the remaining fields within this class/struct/union subobject.
1427 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001428 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1429 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001430 return hadError && !prevHadError;
1431 }
1432
1433 // C99 6.7.8p6:
1434 //
1435 // If a designator has the form
1436 //
1437 // [ constant-expression ]
1438 //
1439 // then the current object (defined below) shall have array
1440 // type and the expression shall be an integer constant
1441 // expression. If the array is of unknown size, any
1442 // nonnegative value is valid.
1443 //
1444 // Additionally, cope with the GNU extension that permits
1445 // designators of the form
1446 //
1447 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001448 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001449 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001450 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001451 << CurrentObjectType;
1452 ++Index;
1453 return true;
1454 }
1455
1456 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001457 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1458 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001459 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001460 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001461 DesignatedEndIndex = DesignatedStartIndex;
1462 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001463 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001464
Mike Stump11289f42009-09-09 15:08:12 +00001465
1466 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001467 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001468 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001469 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001470 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001471
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001472 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001473 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001474 }
1475
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001476 if (isa<ConstantArrayType>(AT)) {
1477 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001478 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1479 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1480 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1481 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1482 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001483 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001484 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001485 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001486 << IndexExpr->getSourceRange();
1487 ++Index;
1488 return true;
1489 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001490 } else {
1491 // Make sure the bit-widths and signedness match.
1492 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1493 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001494 else if (DesignatedStartIndex.getBitWidth() <
1495 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001496 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1497 DesignatedStartIndex.setIsUnsigned(true);
1498 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001501 // Make sure that our non-designated initializer list has space
1502 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001503 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001504 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001505 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001506
Douglas Gregor17bd0942009-01-28 23:36:17 +00001507 // Repeatedly perform subobject initializations in the range
1508 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001509
Douglas Gregor17bd0942009-01-28 23:36:17 +00001510 // Move to the next designator
1511 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1512 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001513 while (DesignatedStartIndex <= DesignatedEndIndex) {
1514 // Recurse to check later designated subobjects.
1515 QualType ElementType = AT->getElementType();
1516 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001517 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1518 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 (DesignatedStartIndex == DesignatedEndIndex),
1520 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001521 return true;
1522
1523 // Move to the next index in the array that we'll be initializing.
1524 ++DesignatedStartIndex;
1525 ElementIndex = DesignatedStartIndex.getZExtValue();
1526 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527
1528 // If this the first designator, our caller will continue checking
1529 // the rest of this array subobject.
1530 if (IsFirstDesignator) {
1531 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001532 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001533 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001534 return false;
1535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregor17bd0942009-01-28 23:36:17 +00001537 if (!FinishSubobjectInit)
1538 return false;
1539
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001540 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001541 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001542 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001543 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001544 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001545}
1546
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001547// Get the structured initializer list for a subobject of type
1548// @p CurrentObjectType.
1549InitListExpr *
1550InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1551 QualType CurrentObjectType,
1552 InitListExpr *StructuredList,
1553 unsigned StructuredIndex,
1554 SourceRange InitRange) {
1555 Expr *ExistingInit = 0;
1556 if (!StructuredList)
1557 ExistingInit = SyntacticToSemantic[IList];
1558 else if (StructuredIndex < StructuredList->getNumInits())
1559 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001560
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1562 return Result;
1563
1564 if (ExistingInit) {
1565 // We are creating an initializer list that initializes the
1566 // subobjects of the current object, but there was already an
1567 // initialization that completely initialized the current
1568 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001569 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001570 // struct X { int a, b; };
1571 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001572 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001573 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1574 // designated initializer re-initializes the whole
1575 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001576 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001577 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001578 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001579 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001580 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001581 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001582 << ExistingInit->getSourceRange();
1583 }
1584
Mike Stump11289f42009-09-09 15:08:12 +00001585 InitListExpr *Result
1586 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001587 InitRange.getEnd());
1588
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001589 Result->setType(CurrentObjectType);
1590
Douglas Gregor6d00c992009-03-20 23:58:33 +00001591 // Pre-allocate storage for the structured initializer list.
1592 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001593 unsigned NumInits = 0;
1594 if (!StructuredList)
1595 NumInits = IList->getNumInits();
1596 else if (Index < IList->getNumInits()) {
1597 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1598 NumInits = SubList->getNumInits();
1599 }
1600
Mike Stump11289f42009-09-09 15:08:12 +00001601 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001602 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1603 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1604 NumElements = CAType->getSize().getZExtValue();
1605 // Simple heuristic so that we don't allocate a very large
1606 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001607 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001608 NumElements = 0;
1609 }
John McCall9dd450b2009-09-21 23:43:11 +00001610 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001611 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001612 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001613 RecordDecl *RDecl = RType->getDecl();
1614 if (RDecl->isUnion())
1615 NumElements = 1;
1616 else
Mike Stump11289f42009-09-09 15:08:12 +00001617 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001618 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001619 }
1620
Douglas Gregor221c9a52009-03-21 18:13:52 +00001621 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001622 NumElements = IList->getNumInits();
1623
1624 Result->reserveInits(NumElements);
1625
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001626 // Link this new initializer list into the structured initializer
1627 // lists.
1628 if (StructuredList)
1629 StructuredList->updateInit(StructuredIndex, Result);
1630 else {
1631 Result->setSyntacticForm(IList);
1632 SyntacticToSemantic[IList] = Result;
1633 }
1634
1635 return Result;
1636}
1637
1638/// Update the initializer at index @p StructuredIndex within the
1639/// structured initializer list to the value @p expr.
1640void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1641 unsigned &StructuredIndex,
1642 Expr *expr) {
1643 // No structured initializer list to update
1644 if (!StructuredList)
1645 return;
1646
1647 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1648 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001649 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001650 diag::warn_initializer_overrides)
1651 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001652 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001653 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001654 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001655 << PrevInit->getSourceRange();
1656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001658 ++StructuredIndex;
1659}
1660
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001661/// Check that the given Index expression is a valid array designator
1662/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001663/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001664/// and produces a reasonable diagnostic if there is a
1665/// failure. Returns true if there was an error, false otherwise. If
1666/// everything went okay, Value will receive the value of the constant
1667/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001668static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001669CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001670 SourceLocation Loc = Index->getSourceRange().getBegin();
1671
1672 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001673 if (S.VerifyIntegerConstantExpression(Index, &Value))
1674 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001675
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001676 if (Value.isSigned() && Value.isNegative())
1677 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001678 << Value.toString(10) << Index->getSourceRange();
1679
Douglas Gregor51650d32009-01-23 21:04:18 +00001680 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001681 return false;
1682}
1683
1684Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1685 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001686 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001687 OwningExprResult Init) {
1688 typedef DesignatedInitExpr::Designator ASTDesignator;
1689
1690 bool Invalid = false;
1691 llvm::SmallVector<ASTDesignator, 32> Designators;
1692 llvm::SmallVector<Expr *, 32> InitExpressions;
1693
1694 // Build designators and check array designator expressions.
1695 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1696 const Designator &D = Desig.getDesignator(Idx);
1697 switch (D.getKind()) {
1698 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001699 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001700 D.getFieldLoc()));
1701 break;
1702
1703 case Designator::ArrayDesignator: {
1704 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1705 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001706 if (!Index->isTypeDependent() &&
1707 !Index->isValueDependent() &&
1708 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001709 Invalid = true;
1710 else {
1711 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001712 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001713 D.getRBracketLoc()));
1714 InitExpressions.push_back(Index);
1715 }
1716 break;
1717 }
1718
1719 case Designator::ArrayRangeDesignator: {
1720 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1721 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1722 llvm::APSInt StartValue;
1723 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001724 bool StartDependent = StartIndex->isTypeDependent() ||
1725 StartIndex->isValueDependent();
1726 bool EndDependent = EndIndex->isTypeDependent() ||
1727 EndIndex->isValueDependent();
1728 if ((!StartDependent &&
1729 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1730 (!EndDependent &&
1731 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001732 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001733 else {
1734 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001735 if (StartDependent || EndDependent) {
1736 // Nothing to compute.
1737 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001738 EndValue.extend(StartValue.getBitWidth());
1739 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1740 StartValue.extend(EndValue.getBitWidth());
1741
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001742 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001743 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001744 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001745 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1746 Invalid = true;
1747 } else {
1748 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001749 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001750 D.getEllipsisLoc(),
1751 D.getRBracketLoc()));
1752 InitExpressions.push_back(StartIndex);
1753 InitExpressions.push_back(EndIndex);
1754 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001755 }
1756 break;
1757 }
1758 }
1759 }
1760
1761 if (Invalid || Init.isInvalid())
1762 return ExprError();
1763
1764 // Clear out the expressions within the designation.
1765 Desig.ClearExprs(*this);
1766
1767 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001768 = DesignatedInitExpr::Create(Context,
1769 Designators.data(), Designators.size(),
1770 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001771 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001772 return Owned(DIE);
1773}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001774
Douglas Gregor723796a2009-12-16 06:35:08 +00001775bool Sema::CheckInitList(const InitializedEntity &Entity,
1776 InitListExpr *&InitList, QualType &DeclType) {
1777 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001778 if (!CheckInitList.HadError())
1779 InitList = CheckInitList.getFullyStructuredList();
1780
1781 return CheckInitList.HadError();
1782}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001783
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001784//===----------------------------------------------------------------------===//
1785// Initialization entity
1786//===----------------------------------------------------------------------===//
1787
Douglas Gregor723796a2009-12-16 06:35:08 +00001788InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1789 const InitializedEntity &Parent)
1790 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1791{
Douglas Gregor1b303932009-12-22 15:35:07 +00001792 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType()))
1793 Type = AT->getElementType();
Douglas Gregor723796a2009-12-16 06:35:08 +00001794 else
Douglas Gregor1b303932009-12-22 15:35:07 +00001795 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001796}
1797
1798InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1799 CXXBaseSpecifier *Base)
1800{
1801 InitializedEntity Result;
1802 Result.Kind = EK_Base;
1803 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001804 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001805 return Result;
1806}
1807
Douglas Gregor85dabae2009-12-16 01:38:02 +00001808DeclarationName InitializedEntity::getName() const {
1809 switch (getKind()) {
1810 case EK_Variable:
1811 case EK_Parameter:
1812 case EK_Member:
1813 return VariableOrMember->getDeclName();
1814
1815 case EK_Result:
1816 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001817 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001818 case EK_Temporary:
1819 case EK_Base:
Douglas Gregor723796a2009-12-16 06:35:08 +00001820 case EK_ArrayOrVectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001821 return DeclarationName();
1822 }
1823
1824 // Silence GCC warning
1825 return DeclarationName();
1826}
1827
Douglas Gregora4b592a2009-12-19 03:01:41 +00001828DeclaratorDecl *InitializedEntity::getDecl() const {
1829 switch (getKind()) {
1830 case EK_Variable:
1831 case EK_Parameter:
1832 case EK_Member:
1833 return VariableOrMember;
1834
1835 case EK_Result:
1836 case EK_Exception:
1837 case EK_New:
1838 case EK_Temporary:
1839 case EK_Base:
1840 case EK_ArrayOrVectorElement:
1841 return 0;
1842 }
1843
1844 // Silence GCC warning
1845 return 0;
1846}
1847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001848//===----------------------------------------------------------------------===//
1849// Initialization sequence
1850//===----------------------------------------------------------------------===//
1851
1852void InitializationSequence::Step::Destroy() {
1853 switch (Kind) {
1854 case SK_ResolveAddressOfOverloadedFunction:
1855 case SK_CastDerivedToBaseRValue:
1856 case SK_CastDerivedToBaseLValue:
1857 case SK_BindReference:
1858 case SK_BindReferenceToTemporary:
1859 case SK_UserConversion:
1860 case SK_QualificationConversionRValue:
1861 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001862 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001863 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001864 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001865 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001866 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001867 break;
1868
1869 case SK_ConversionSequence:
1870 delete ICS;
1871 }
1872}
1873
1874void InitializationSequence::AddAddressOverloadResolutionStep(
1875 FunctionDecl *Function) {
1876 Step S;
1877 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1878 S.Type = Function->getType();
1879 S.Function = Function;
1880 Steps.push_back(S);
1881}
1882
1883void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1884 bool IsLValue) {
1885 Step S;
1886 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1887 S.Type = BaseType;
1888 Steps.push_back(S);
1889}
1890
1891void InitializationSequence::AddReferenceBindingStep(QualType T,
1892 bool BindingTemporary) {
1893 Step S;
1894 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1895 S.Type = T;
1896 Steps.push_back(S);
1897}
1898
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001899void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1900 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001901 Step S;
1902 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001903 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001904 S.Function = Function;
1905 Steps.push_back(S);
1906}
1907
1908void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1909 bool IsLValue) {
1910 Step S;
1911 S.Kind = IsLValue? SK_QualificationConversionLValue
1912 : SK_QualificationConversionRValue;
1913 S.Type = Ty;
1914 Steps.push_back(S);
1915}
1916
1917void InitializationSequence::AddConversionSequenceStep(
1918 const ImplicitConversionSequence &ICS,
1919 QualType T) {
1920 Step S;
1921 S.Kind = SK_ConversionSequence;
1922 S.Type = T;
1923 S.ICS = new ImplicitConversionSequence(ICS);
1924 Steps.push_back(S);
1925}
1926
Douglas Gregor51e77d52009-12-10 17:56:55 +00001927void InitializationSequence::AddListInitializationStep(QualType T) {
1928 Step S;
1929 S.Kind = SK_ListInitialization;
1930 S.Type = T;
1931 Steps.push_back(S);
1932}
1933
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001934void
1935InitializationSequence::AddConstructorInitializationStep(
1936 CXXConstructorDecl *Constructor,
1937 QualType T) {
1938 Step S;
1939 S.Kind = SK_ConstructorInitialization;
1940 S.Type = T;
1941 S.Function = Constructor;
1942 Steps.push_back(S);
1943}
1944
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001945void InitializationSequence::AddZeroInitializationStep(QualType T) {
1946 Step S;
1947 S.Kind = SK_ZeroInitialization;
1948 S.Type = T;
1949 Steps.push_back(S);
1950}
1951
Douglas Gregore1314a62009-12-18 05:02:21 +00001952void InitializationSequence::AddCAssignmentStep(QualType T) {
1953 Step S;
1954 S.Kind = SK_CAssignment;
1955 S.Type = T;
1956 Steps.push_back(S);
1957}
1958
Eli Friedman78275202009-12-19 08:11:05 +00001959void InitializationSequence::AddStringInitStep(QualType T) {
1960 Step S;
1961 S.Kind = SK_StringInit;
1962 S.Type = T;
1963 Steps.push_back(S);
1964}
1965
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001966void InitializationSequence::SetOverloadFailure(FailureKind Failure,
1967 OverloadingResult Result) {
1968 SequenceKind = FailedSequence;
1969 this->Failure = Failure;
1970 this->FailedOverloadResult = Result;
1971}
1972
1973//===----------------------------------------------------------------------===//
1974// Attempt initialization
1975//===----------------------------------------------------------------------===//
1976
1977/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00001978static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001979 const InitializedEntity &Entity,
1980 const InitializationKind &Kind,
1981 InitListExpr *InitList,
1982 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00001983 // FIXME: We only perform rudimentary checking of list
1984 // initializations at this point, then assume that any list
1985 // initialization of an array, aggregate, or scalar will be
1986 // well-formed. We we actually "perform" list initialization, we'll
1987 // do all of the necessary checking. C++0x initializer lists will
1988 // force us to perform more checking here.
1989 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
1990
Douglas Gregor1b303932009-12-22 15:35:07 +00001991 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00001992
1993 // C++ [dcl.init]p13:
1994 // If T is a scalar type, then a declaration of the form
1995 //
1996 // T x = { a };
1997 //
1998 // is equivalent to
1999 //
2000 // T x = a;
2001 if (DestType->isScalarType()) {
2002 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2003 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2004 return;
2005 }
2006
2007 // Assume scalar initialization from a single value works.
2008 } else if (DestType->isAggregateType()) {
2009 // Assume aggregate initialization works.
2010 } else if (DestType->isVectorType()) {
2011 // Assume vector initialization works.
2012 } else if (DestType->isReferenceType()) {
2013 // FIXME: C++0x defines behavior for this.
2014 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2015 return;
2016 } else if (DestType->isRecordType()) {
2017 // FIXME: C++0x defines behavior for this
2018 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2019 }
2020
2021 // Add a general "list initialization" step.
2022 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002023}
2024
2025/// \brief Try a reference initialization that involves calling a conversion
2026/// function.
2027///
2028/// FIXME: look intos DRs 656, 896
2029static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2030 const InitializedEntity &Entity,
2031 const InitializationKind &Kind,
2032 Expr *Initializer,
2033 bool AllowRValues,
2034 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002035 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002036 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2037 QualType T1 = cv1T1.getUnqualifiedType();
2038 QualType cv2T2 = Initializer->getType();
2039 QualType T2 = cv2T2.getUnqualifiedType();
2040
2041 bool DerivedToBase;
2042 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2043 T1, T2, DerivedToBase) &&
2044 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002045 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002046
2047 // Build the candidate set directly in the initialization sequence
2048 // structure, so that it will persist if we fail.
2049 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2050 CandidateSet.clear();
2051
2052 // Determine whether we are allowed to call explicit constructors or
2053 // explicit conversion operators.
2054 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2055
2056 const RecordType *T1RecordType = 0;
2057 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2058 // The type we're converting to is a class type. Enumerate its constructors
2059 // to see if there is a suitable conversion.
2060 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2061
2062 DeclarationName ConstructorName
2063 = S.Context.DeclarationNames.getCXXConstructorName(
2064 S.Context.getCanonicalType(T1).getUnqualifiedType());
2065 DeclContext::lookup_iterator Con, ConEnd;
2066 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2067 Con != ConEnd; ++Con) {
2068 // Find the constructor (which may be a template).
2069 CXXConstructorDecl *Constructor = 0;
2070 FunctionTemplateDecl *ConstructorTmpl
2071 = dyn_cast<FunctionTemplateDecl>(*Con);
2072 if (ConstructorTmpl)
2073 Constructor = cast<CXXConstructorDecl>(
2074 ConstructorTmpl->getTemplatedDecl());
2075 else
2076 Constructor = cast<CXXConstructorDecl>(*Con);
2077
2078 if (!Constructor->isInvalidDecl() &&
2079 Constructor->isConvertingConstructor(AllowExplicit)) {
2080 if (ConstructorTmpl)
2081 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2082 &Initializer, 1, CandidateSet);
2083 else
2084 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2085 }
2086 }
2087 }
2088
2089 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2090 // The type we're converting from is a class type, enumerate its conversion
2091 // functions.
2092 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2093
2094 // Determine the type we are converting to. If we are allowed to
2095 // convert to an rvalue, take the type that the destination type
2096 // refers to.
2097 QualType ToType = AllowRValues? cv1T1 : DestType;
2098
2099 const UnresolvedSet *Conversions
2100 = T2RecordDecl->getVisibleConversionFunctions();
2101 for (UnresolvedSet::iterator I = Conversions->begin(),
2102 E = Conversions->end();
2103 I != E; ++I) {
2104 NamedDecl *D = *I;
2105 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2106 if (isa<UsingShadowDecl>(D))
2107 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2108
2109 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2110 CXXConversionDecl *Conv;
2111 if (ConvTemplate)
2112 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2113 else
2114 Conv = cast<CXXConversionDecl>(*I);
2115
2116 // If the conversion function doesn't return a reference type,
2117 // it can't be considered for this conversion unless we're allowed to
2118 // consider rvalues.
2119 // FIXME: Do we need to make sure that we only consider conversion
2120 // candidates with reference-compatible results? That might be needed to
2121 // break recursion.
2122 if ((AllowExplicit || !Conv->isExplicit()) &&
2123 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2124 if (ConvTemplate)
2125 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2126 ToType, CandidateSet);
2127 else
2128 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2129 CandidateSet);
2130 }
2131 }
2132 }
2133
2134 SourceLocation DeclLoc = Initializer->getLocStart();
2135
2136 // Perform overload resolution. If it fails, return the failed result.
2137 OverloadCandidateSet::iterator Best;
2138 if (OverloadingResult Result
2139 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2140 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002141
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002142 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002143
2144 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 if (isa<CXXConversionDecl>(Function))
2146 T2 = Function->getResultType();
2147 else
2148 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002149
2150 // Add the user-defined conversion step.
2151 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2152
2153 // Determine whether we need to perform derived-to-base or
2154 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002155 bool NewDerivedToBase = false;
2156 Sema::ReferenceCompareResult NewRefRelationship
2157 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2158 NewDerivedToBase);
2159 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2160 "Overload resolution picked a bad conversion function");
2161 (void)NewRefRelationship;
2162 if (NewDerivedToBase)
2163 Sequence.AddDerivedToBaseCastStep(
2164 S.Context.getQualifiedType(T1,
2165 T2.getNonReferenceType().getQualifiers()),
2166 /*isLValue=*/true);
2167
2168 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2169 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2170
2171 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2172 return OR_Success;
2173}
2174
2175/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2176static void TryReferenceInitialization(Sema &S,
2177 const InitializedEntity &Entity,
2178 const InitializationKind &Kind,
2179 Expr *Initializer,
2180 InitializationSequence &Sequence) {
2181 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2182
Douglas Gregor1b303932009-12-22 15:35:07 +00002183 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002184 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2185 QualType T1 = cv1T1.getUnqualifiedType();
2186 QualType cv2T2 = Initializer->getType();
2187 QualType T2 = cv2T2.getUnqualifiedType();
2188 SourceLocation DeclLoc = Initializer->getLocStart();
2189
2190 // If the initializer is the address of an overloaded function, try
2191 // to resolve the overloaded function. If all goes well, T2 is the
2192 // type of the resulting function.
2193 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2194 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2195 T1,
2196 false);
2197 if (!Fn) {
2198 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2199 return;
2200 }
2201
2202 Sequence.AddAddressOverloadResolutionStep(Fn);
2203 cv2T2 = Fn->getType();
2204 T2 = cv2T2.getUnqualifiedType();
2205 }
2206
2207 // FIXME: Rvalue references
2208 bool ForceRValue = false;
2209
2210 // Compute some basic properties of the types and the initializer.
2211 bool isLValueRef = DestType->isLValueReferenceType();
2212 bool isRValueRef = !isLValueRef;
2213 bool DerivedToBase = false;
2214 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2215 Initializer->isLvalue(S.Context);
2216 Sema::ReferenceCompareResult RefRelationship
2217 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2218
2219 // C++0x [dcl.init.ref]p5:
2220 // A reference to type "cv1 T1" is initialized by an expression of type
2221 // "cv2 T2" as follows:
2222 //
2223 // - If the reference is an lvalue reference and the initializer
2224 // expression
2225 OverloadingResult ConvOvlResult = OR_Success;
2226 if (isLValueRef) {
2227 if (InitLvalue == Expr::LV_Valid &&
2228 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2229 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2230 // reference-compatible with "cv2 T2," or
2231 //
2232 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2233 // bit-field when we're determining whether the reference initialization
2234 // can occur. This property will be checked by PerformInitialization.
2235 if (DerivedToBase)
2236 Sequence.AddDerivedToBaseCastStep(
2237 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2238 /*isLValue=*/true);
2239 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2240 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2241 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2242 return;
2243 }
2244
2245 // - has a class type (i.e., T2 is a class type), where T1 is not
2246 // reference-related to T2, and can be implicitly converted to an
2247 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2248 // with "cv3 T3" (this conversion is selected by enumerating the
2249 // applicable conversion functions (13.3.1.6) and choosing the best
2250 // one through overload resolution (13.3)),
2251 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2252 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2253 Initializer,
2254 /*AllowRValues=*/false,
2255 Sequence);
2256 if (ConvOvlResult == OR_Success)
2257 return;
2258 }
2259 }
2260
2261 // - Otherwise, the reference shall be an lvalue reference to a
2262 // non-volatile const type (i.e., cv1 shall be const), or the reference
2263 // shall be an rvalue reference and the initializer expression shall
2264 // be an rvalue.
2265 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2266 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2267 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2268 Sequence.SetOverloadFailure(
2269 InitializationSequence::FK_ReferenceInitOverloadFailed,
2270 ConvOvlResult);
2271 else if (isLValueRef)
2272 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2273 ? (RefRelationship == Sema::Ref_Related
2274 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2275 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2276 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2277 else
2278 Sequence.SetFailed(
2279 InitializationSequence::FK_RValueReferenceBindingToLValue);
2280
2281 return;
2282 }
2283
2284 // - If T1 and T2 are class types and
2285 if (T1->isRecordType() && T2->isRecordType()) {
2286 // - the initializer expression is an rvalue and "cv1 T1" is
2287 // reference-compatible with "cv2 T2", or
2288 if (InitLvalue != Expr::LV_Valid &&
2289 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2290 if (DerivedToBase)
2291 Sequence.AddDerivedToBaseCastStep(
2292 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2293 /*isLValue=*/false);
2294 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2295 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2296 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2297 return;
2298 }
2299
2300 // - T1 is not reference-related to T2 and the initializer expression
2301 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2302 // conversion is selected by enumerating the applicable conversion
2303 // functions (13.3.1.6) and choosing the best one through overload
2304 // resolution (13.3)),
2305 if (RefRelationship == Sema::Ref_Incompatible) {
2306 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2307 Kind, Initializer,
2308 /*AllowRValues=*/true,
2309 Sequence);
2310 if (ConvOvlResult)
2311 Sequence.SetOverloadFailure(
2312 InitializationSequence::FK_ReferenceInitOverloadFailed,
2313 ConvOvlResult);
2314
2315 return;
2316 }
2317
2318 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2319 return;
2320 }
2321
2322 // - If the initializer expression is an rvalue, with T2 an array type,
2323 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2324 // is bound to the object represented by the rvalue (see 3.10).
2325 // FIXME: How can an array type be reference-compatible with anything?
2326 // Don't we mean the element types of T1 and T2?
2327
2328 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2329 // from the initializer expression using the rules for a non-reference
2330 // copy initialization (8.5). The reference is then bound to the
2331 // temporary. [...]
2332 // Determine whether we are allowed to call explicit constructors or
2333 // explicit conversion operators.
2334 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2335 ImplicitConversionSequence ICS
2336 = S.TryImplicitConversion(Initializer, cv1T1,
2337 /*SuppressUserConversions=*/false, AllowExplicit,
2338 /*ForceRValue=*/false,
2339 /*FIXME:InOverloadResolution=*/false,
2340 /*UserCast=*/Kind.isExplicitCast());
2341
2342 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2343 // FIXME: Use the conversion function set stored in ICS to turn
2344 // this into an overloading ambiguity diagnostic. However, we need
2345 // to keep that set as an OverloadCandidateSet rather than as some
2346 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002347 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2348 Sequence.SetOverloadFailure(
2349 InitializationSequence::FK_ReferenceInitOverloadFailed,
2350 ConvOvlResult);
2351 else
2352 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 return;
2354 }
2355
2356 // [...] If T1 is reference-related to T2, cv1 must be the
2357 // same cv-qualification as, or greater cv-qualification
2358 // than, cv2; otherwise, the program is ill-formed.
2359 if (RefRelationship == Sema::Ref_Related &&
2360 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2361 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2362 return;
2363 }
2364
2365 // Perform the actual conversion.
2366 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2367 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2368 return;
2369}
2370
2371/// \brief Attempt character array initialization from a string literal
2372/// (C++ [dcl.init.string], C99 6.7.8).
2373static void TryStringLiteralInitialization(Sema &S,
2374 const InitializedEntity &Entity,
2375 const InitializationKind &Kind,
2376 Expr *Initializer,
2377 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002378 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002379 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380}
2381
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002382/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2383/// enumerates the constructors of the initialized entity and performs overload
2384/// resolution to select the best.
2385static void TryConstructorInitialization(Sema &S,
2386 const InitializedEntity &Entity,
2387 const InitializationKind &Kind,
2388 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002389 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002390 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002391 if (Kind.getKind() == InitializationKind::IK_Copy)
2392 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2393 else
2394 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002395
2396 // Build the candidate set directly in the initialization sequence
2397 // structure, so that it will persist if we fail.
2398 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2399 CandidateSet.clear();
2400
2401 // Determine whether we are allowed to call explicit constructors or
2402 // explicit conversion operators.
2403 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2404 Kind.getKind() == InitializationKind::IK_Value ||
2405 Kind.getKind() == InitializationKind::IK_Default);
2406
2407 // The type we're converting to is a class type. Enumerate its constructors
2408 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002409 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2410 assert(DestRecordType && "Constructor initialization requires record type");
2411 CXXRecordDecl *DestRecordDecl
2412 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2413
2414 DeclarationName ConstructorName
2415 = S.Context.DeclarationNames.getCXXConstructorName(
2416 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2417 DeclContext::lookup_iterator Con, ConEnd;
2418 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2419 Con != ConEnd; ++Con) {
2420 // Find the constructor (which may be a template).
2421 CXXConstructorDecl *Constructor = 0;
2422 FunctionTemplateDecl *ConstructorTmpl
2423 = dyn_cast<FunctionTemplateDecl>(*Con);
2424 if (ConstructorTmpl)
2425 Constructor = cast<CXXConstructorDecl>(
2426 ConstructorTmpl->getTemplatedDecl());
2427 else
2428 Constructor = cast<CXXConstructorDecl>(*Con);
2429
2430 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002431 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002432 if (ConstructorTmpl)
2433 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2434 Args, NumArgs, CandidateSet);
2435 else
2436 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2437 }
2438 }
2439
2440 SourceLocation DeclLoc = Kind.getLocation();
2441
2442 // Perform overload resolution. If it fails, return the failed result.
2443 OverloadCandidateSet::iterator Best;
2444 if (OverloadingResult Result
2445 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2446 Sequence.SetOverloadFailure(
2447 InitializationSequence::FK_ConstructorOverloadFailed,
2448 Result);
2449 return;
2450 }
2451
2452 // Add the constructor initialization step. Any cv-qualification conversion is
2453 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002454 if (Kind.getKind() == InitializationKind::IK_Copy) {
2455 Sequence.AddUserConversionStep(Best->Function, DestType);
2456 } else {
2457 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002458 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002459 DestType);
2460 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461}
2462
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002463/// \brief Attempt value initialization (C++ [dcl.init]p7).
2464static void TryValueInitialization(Sema &S,
2465 const InitializedEntity &Entity,
2466 const InitializationKind &Kind,
2467 InitializationSequence &Sequence) {
2468 // C++ [dcl.init]p5:
2469 //
2470 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002471 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002472
2473 // -- if T is an array type, then each element is value-initialized;
2474 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2475 T = AT->getElementType();
2476
2477 if (const RecordType *RT = T->getAs<RecordType>()) {
2478 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2479 // -- if T is a class type (clause 9) with a user-declared
2480 // constructor (12.1), then the default constructor for T is
2481 // called (and the initialization is ill-formed if T has no
2482 // accessible default constructor);
2483 //
2484 // FIXME: we really want to refer to a single subobject of the array,
2485 // but Entity doesn't have a way to capture that (yet).
2486 if (ClassDecl->hasUserDeclaredConstructor())
2487 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2488
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002489 // -- if T is a (possibly cv-qualified) non-union class type
2490 // without a user-provided constructor, then the object is
2491 // zero-initialized and, if T’s implicitly-declared default
2492 // constructor is non-trivial, that constructor is called.
2493 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2494 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2495 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002496 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002497 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2498 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002499 }
2500 }
2501
Douglas Gregor1b303932009-12-22 15:35:07 +00002502 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002503 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2504}
2505
Douglas Gregor85dabae2009-12-16 01:38:02 +00002506/// \brief Attempt default initialization (C++ [dcl.init]p6).
2507static void TryDefaultInitialization(Sema &S,
2508 const InitializedEntity &Entity,
2509 const InitializationKind &Kind,
2510 InitializationSequence &Sequence) {
2511 assert(Kind.getKind() == InitializationKind::IK_Default);
2512
2513 // C++ [dcl.init]p6:
2514 // To default-initialize an object of type T means:
2515 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002516 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002517 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2518 DestType = Array->getElementType();
2519
2520 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2521 // constructor for T is called (and the initialization is ill-formed if
2522 // T has no accessible default constructor);
2523 if (DestType->isRecordType()) {
2524 // FIXME: If a program calls for the default initialization of an object of
2525 // a const-qualified type T, T shall be a class type with a user-provided
2526 // default constructor.
2527 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2528 Sequence);
2529 }
2530
2531 // - otherwise, no initialization is performed.
2532 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2533
2534 // If a program calls for the default initialization of an object of
2535 // a const-qualified type T, T shall be a class type with a user-provided
2536 // default constructor.
2537 if (DestType.isConstQualified())
2538 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2539}
2540
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002541/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2542/// which enumerates all conversion functions and performs overload resolution
2543/// to select the best.
2544static void TryUserDefinedConversion(Sema &S,
2545 const InitializedEntity &Entity,
2546 const InitializationKind &Kind,
2547 Expr *Initializer,
2548 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002549 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2550
Douglas Gregor1b303932009-12-22 15:35:07 +00002551 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002552 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2553 QualType SourceType = Initializer->getType();
2554 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2555 "Must have a class type to perform a user-defined conversion");
2556
2557 // Build the candidate set directly in the initialization sequence
2558 // structure, so that it will persist if we fail.
2559 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2560 CandidateSet.clear();
2561
2562 // Determine whether we are allowed to call explicit constructors or
2563 // explicit conversion operators.
2564 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2565
2566 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2567 // The type we're converting to is a class type. Enumerate its constructors
2568 // to see if there is a suitable conversion.
2569 CXXRecordDecl *DestRecordDecl
2570 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2571
2572 DeclarationName ConstructorName
2573 = S.Context.DeclarationNames.getCXXConstructorName(
2574 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2575 DeclContext::lookup_iterator Con, ConEnd;
2576 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2577 Con != ConEnd; ++Con) {
2578 // Find the constructor (which may be a template).
2579 CXXConstructorDecl *Constructor = 0;
2580 FunctionTemplateDecl *ConstructorTmpl
2581 = dyn_cast<FunctionTemplateDecl>(*Con);
2582 if (ConstructorTmpl)
2583 Constructor = cast<CXXConstructorDecl>(
2584 ConstructorTmpl->getTemplatedDecl());
2585 else
2586 Constructor = cast<CXXConstructorDecl>(*Con);
2587
2588 if (!Constructor->isInvalidDecl() &&
2589 Constructor->isConvertingConstructor(AllowExplicit)) {
2590 if (ConstructorTmpl)
2591 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2592 &Initializer, 1, CandidateSet);
2593 else
2594 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2595 }
2596 }
2597 }
Eli Friedman78275202009-12-19 08:11:05 +00002598
2599 SourceLocation DeclLoc = Initializer->getLocStart();
2600
Douglas Gregor540c3b02009-12-14 17:27:33 +00002601 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2602 // The type we're converting from is a class type, enumerate its conversion
2603 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002604
Eli Friedman4afe9a32009-12-20 22:12:03 +00002605 // We can only enumerate the conversion functions for a complete type; if
2606 // the type isn't complete, simply skip this step.
2607 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2608 CXXRecordDecl *SourceRecordDecl
2609 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002610
Eli Friedman4afe9a32009-12-20 22:12:03 +00002611 const UnresolvedSet *Conversions
2612 = SourceRecordDecl->getVisibleConversionFunctions();
2613 for (UnresolvedSet::iterator I = Conversions->begin(),
2614 E = Conversions->end();
2615 I != E; ++I) {
2616 NamedDecl *D = *I;
2617 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2618 if (isa<UsingShadowDecl>(D))
2619 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2620
2621 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2622 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002623 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002624 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002625 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002626 Conv = cast<CXXConversionDecl>(*I);
2627
2628 if (AllowExplicit || !Conv->isExplicit()) {
2629 if (ConvTemplate)
2630 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2631 Initializer, DestType,
2632 CandidateSet);
2633 else
2634 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2635 CandidateSet);
2636 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002637 }
2638 }
2639 }
2640
Douglas Gregor540c3b02009-12-14 17:27:33 +00002641 // Perform overload resolution. If it fails, return the failed result.
2642 OverloadCandidateSet::iterator Best;
2643 if (OverloadingResult Result
2644 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2645 Sequence.SetOverloadFailure(
2646 InitializationSequence::FK_UserConversionOverloadFailed,
2647 Result);
2648 return;
2649 }
2650
2651 FunctionDecl *Function = Best->Function;
2652
2653 if (isa<CXXConstructorDecl>(Function)) {
2654 // Add the user-defined conversion step. Any cv-qualification conversion is
2655 // subsumed by the initialization.
2656 Sequence.AddUserConversionStep(Function, DestType);
2657 return;
2658 }
2659
2660 // Add the user-defined conversion step that calls the conversion function.
2661 QualType ConvType = Function->getResultType().getNonReferenceType();
2662 Sequence.AddUserConversionStep(Function, ConvType);
2663
2664 // If the conversion following the call to the conversion function is
2665 // interesting, add it as a separate step.
2666 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2667 Best->FinalConversion.Third) {
2668 ImplicitConversionSequence ICS;
2669 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2670 ICS.Standard = Best->FinalConversion;
2671 Sequence.AddConversionSequenceStep(ICS, DestType);
2672 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002673}
2674
2675/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2676/// non-class type to another.
2677static void TryImplicitConversion(Sema &S,
2678 const InitializedEntity &Entity,
2679 const InitializationKind &Kind,
2680 Expr *Initializer,
2681 InitializationSequence &Sequence) {
2682 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002683 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002684 /*SuppressUserConversions=*/true,
2685 /*AllowExplicit=*/false,
2686 /*ForceRValue=*/false,
2687 /*FIXME:InOverloadResolution=*/false,
2688 /*UserCast=*/Kind.isExplicitCast());
2689
2690 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2691 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2692 return;
2693 }
2694
Douglas Gregor1b303932009-12-22 15:35:07 +00002695 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002696}
2697
2698InitializationSequence::InitializationSequence(Sema &S,
2699 const InitializedEntity &Entity,
2700 const InitializationKind &Kind,
2701 Expr **Args,
2702 unsigned NumArgs) {
2703 ASTContext &Context = S.Context;
2704
2705 // C++0x [dcl.init]p16:
2706 // The semantics of initializers are as follows. The destination type is
2707 // the type of the object or reference being initialized and the source
2708 // type is the type of the initializer expression. The source type is not
2709 // defined when the initializer is a braced-init-list or when it is a
2710 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002711 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712
2713 if (DestType->isDependentType() ||
2714 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2715 SequenceKind = DependentSequence;
2716 return;
2717 }
2718
2719 QualType SourceType;
2720 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002721 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 Initializer = Args[0];
2723 if (!isa<InitListExpr>(Initializer))
2724 SourceType = Initializer->getType();
2725 }
2726
2727 // - If the initializer is a braced-init-list, the object is
2728 // list-initialized (8.5.4).
2729 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2730 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002731 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002732 }
2733
2734 // - If the destination type is a reference type, see 8.5.3.
2735 if (DestType->isReferenceType()) {
2736 // C++0x [dcl.init.ref]p1:
2737 // A variable declared to be a T& or T&&, that is, "reference to type T"
2738 // (8.3.2), shall be initialized by an object, or function, of type T or
2739 // by an object that can be converted into a T.
2740 // (Therefore, multiple arguments are not permitted.)
2741 if (NumArgs != 1)
2742 SetFailed(FK_TooManyInitsForReference);
2743 else
2744 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2745 return;
2746 }
2747
2748 // - If the destination type is an array of characters, an array of
2749 // char16_t, an array of char32_t, or an array of wchar_t, and the
2750 // initializer is a string literal, see 8.5.2.
2751 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2752 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2753 return;
2754 }
2755
2756 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002757 if (Kind.getKind() == InitializationKind::IK_Value ||
2758 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002759 TryValueInitialization(S, Entity, Kind, *this);
2760 return;
2761 }
2762
Douglas Gregor85dabae2009-12-16 01:38:02 +00002763 // Handle default initialization.
2764 if (Kind.getKind() == InitializationKind::IK_Default){
2765 TryDefaultInitialization(S, Entity, Kind, *this);
2766 return;
2767 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002768
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 // - Otherwise, if the destination type is an array, the program is
2770 // ill-formed.
2771 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2772 if (AT->getElementType()->isAnyCharacterType())
2773 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2774 else
2775 SetFailed(FK_ArrayNeedsInitList);
2776
2777 return;
2778 }
Eli Friedman78275202009-12-19 08:11:05 +00002779
2780 // Handle initialization in C
2781 if (!S.getLangOptions().CPlusPlus) {
2782 setSequenceKind(CAssignment);
2783 AddCAssignmentStep(DestType);
2784 return;
2785 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002786
2787 // - If the destination type is a (possibly cv-qualified) class type:
2788 if (DestType->isRecordType()) {
2789 // - If the initialization is direct-initialization, or if it is
2790 // copy-initialization where the cv-unqualified version of the
2791 // source type is the same class as, or a derived class of, the
2792 // class of the destination, constructors are considered. [...]
2793 if (Kind.getKind() == InitializationKind::IK_Direct ||
2794 (Kind.getKind() == InitializationKind::IK_Copy &&
2795 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2796 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002797 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002798 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 // - Otherwise (i.e., for the remaining copy-initialization cases),
2800 // user-defined conversion sequences that can convert from the source
2801 // type to the destination type or (when a conversion function is
2802 // used) to a derived class thereof are enumerated as described in
2803 // 13.3.1.4, and the best one is chosen through overload resolution
2804 // (13.3).
2805 else
2806 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2807 return;
2808 }
2809
Douglas Gregor85dabae2009-12-16 01:38:02 +00002810 if (NumArgs > 1) {
2811 SetFailed(FK_TooManyInitsForScalar);
2812 return;
2813 }
2814 assert(NumArgs == 1 && "Zero-argument case handled above");
2815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002816 // - Otherwise, if the source type is a (possibly cv-qualified) class
2817 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002818 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002819 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2820 return;
2821 }
2822
2823 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002824 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002825 // conversions (Clause 4) will be used, if necessary, to convert the
2826 // initializer expression to the cv-unqualified version of the
2827 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002828 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002829 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2830}
2831
2832InitializationSequence::~InitializationSequence() {
2833 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2834 StepEnd = Steps.end();
2835 Step != StepEnd; ++Step)
2836 Step->Destroy();
2837}
2838
2839//===----------------------------------------------------------------------===//
2840// Perform initialization
2841//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002842static Sema::AssignmentAction
2843getAssignmentAction(const InitializedEntity &Entity) {
2844 switch(Entity.getKind()) {
2845 case InitializedEntity::EK_Variable:
2846 case InitializedEntity::EK_New:
2847 return Sema::AA_Initializing;
2848
2849 case InitializedEntity::EK_Parameter:
2850 // FIXME: Can we tell when we're sending vs. passing?
2851 return Sema::AA_Passing;
2852
2853 case InitializedEntity::EK_Result:
2854 return Sema::AA_Returning;
2855
2856 case InitializedEntity::EK_Exception:
2857 case InitializedEntity::EK_Base:
2858 llvm_unreachable("No assignment action for C++-specific initialization");
2859 break;
2860
2861 case InitializedEntity::EK_Temporary:
2862 // FIXME: Can we tell apart casting vs. converting?
2863 return Sema::AA_Casting;
2864
2865 case InitializedEntity::EK_Member:
2866 case InitializedEntity::EK_ArrayOrVectorElement:
2867 return Sema::AA_Initializing;
2868 }
2869
2870 return Sema::AA_Converting;
2871}
2872
2873static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2874 bool IsCopy) {
2875 switch (Entity.getKind()) {
2876 case InitializedEntity::EK_Result:
2877 case InitializedEntity::EK_Exception:
2878 return !IsCopy;
2879
2880 case InitializedEntity::EK_New:
2881 case InitializedEntity::EK_Variable:
2882 case InitializedEntity::EK_Base:
2883 case InitializedEntity::EK_Member:
2884 case InitializedEntity::EK_ArrayOrVectorElement:
2885 return false;
2886
2887 case InitializedEntity::EK_Parameter:
2888 case InitializedEntity::EK_Temporary:
2889 return true;
2890 }
2891
2892 llvm_unreachable("missed an InitializedEntity kind?");
2893}
2894
2895/// \brief If we need to perform an additional copy of the initialized object
2896/// for this kind of entity (e.g., the result of a function or an object being
2897/// thrown), make the copy.
2898static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2899 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00002900 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00002901 Sema::OwningExprResult CurInit) {
2902 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00002903
2904 switch (Entity.getKind()) {
2905 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00002906 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00002907 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00002908 Loc = Entity.getReturnLoc();
2909 break;
2910
2911 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002912 Loc = Entity.getThrowLoc();
2913 break;
2914
2915 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00002916 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00002917 Kind.getKind() != InitializationKind::IK_Copy)
2918 return move(CurInit);
2919 Loc = Entity.getDecl()->getLocation();
2920 break;
2921
Douglas Gregore1314a62009-12-18 05:02:21 +00002922 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002923 // FIXME: Do we need this initialization for a parameter?
2924 return move(CurInit);
2925
Douglas Gregore1314a62009-12-18 05:02:21 +00002926 case InitializedEntity::EK_New:
2927 case InitializedEntity::EK_Temporary:
2928 case InitializedEntity::EK_Base:
2929 case InitializedEntity::EK_Member:
2930 case InitializedEntity::EK_ArrayOrVectorElement:
2931 // We don't need to copy for any of these initialized entities.
2932 return move(CurInit);
2933 }
2934
2935 Expr *CurInitExpr = (Expr *)CurInit.get();
2936 CXXRecordDecl *Class = 0;
2937 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
2938 Class = cast<CXXRecordDecl>(Record->getDecl());
2939 if (!Class)
2940 return move(CurInit);
2941
2942 // Perform overload resolution using the class's copy constructors.
2943 DeclarationName ConstructorName
2944 = S.Context.DeclarationNames.getCXXConstructorName(
2945 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
2946 DeclContext::lookup_iterator Con, ConEnd;
2947 OverloadCandidateSet CandidateSet;
2948 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
2949 Con != ConEnd; ++Con) {
2950 // Find the constructor (which may be a template).
2951 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
2952 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00002953 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00002954 continue;
2955
2956 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
2957 }
2958
2959 OverloadCandidateSet::iterator Best;
2960 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
2961 case OR_Success:
2962 break;
2963
2964 case OR_No_Viable_Function:
2965 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00002966 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00002967 << CurInitExpr->getSourceRange();
2968 S.PrintOverloadCandidates(CandidateSet, false);
2969 return S.ExprError();
2970
2971 case OR_Ambiguous:
2972 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00002973 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00002974 << CurInitExpr->getSourceRange();
2975 S.PrintOverloadCandidates(CandidateSet, true);
2976 return S.ExprError();
2977
2978 case OR_Deleted:
2979 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00002980 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00002981 << CurInitExpr->getSourceRange();
2982 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
2983 << Best->Function->isDeleted();
2984 return S.ExprError();
2985 }
2986
2987 CurInit.release();
2988 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
2989 cast<CXXConstructorDecl>(Best->Function),
2990 /*Elidable=*/true,
2991 Sema::MultiExprArg(S,
2992 (void**)&CurInitExpr, 1));
2993}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002994
2995Action::OwningExprResult
2996InitializationSequence::Perform(Sema &S,
2997 const InitializedEntity &Entity,
2998 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00002999 Action::MultiExprArg Args,
3000 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003001 if (SequenceKind == FailedSequence) {
3002 unsigned NumArgs = Args.size();
3003 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3004 return S.ExprError();
3005 }
3006
3007 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003008 // If the declaration is a non-dependent, incomplete array type
3009 // that has an initializer, then its type will be completed once
3010 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003011 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003012 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003013 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003014 if (const IncompleteArrayType *ArrayT
3015 = S.Context.getAsIncompleteArrayType(DeclType)) {
3016 // FIXME: We don't currently have the ability to accurately
3017 // compute the length of an initializer list without
3018 // performing full type-checking of the initializer list
3019 // (since we have to determine where braces are implicitly
3020 // introduced and such). So, we fall back to making the array
3021 // type a dependently-sized array type with no specified
3022 // bound.
3023 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3024 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003025
Douglas Gregor51e77d52009-12-10 17:56:55 +00003026 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003027 if (DeclaratorDecl *DD = Entity.getDecl()) {
3028 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3029 TypeLoc TL = TInfo->getTypeLoc();
3030 if (IncompleteArrayTypeLoc *ArrayLoc
3031 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3032 Brackets = ArrayLoc->getBracketsRange();
3033 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003034 }
3035
3036 *ResultType
3037 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3038 /*NumElts=*/0,
3039 ArrayT->getSizeModifier(),
3040 ArrayT->getIndexTypeCVRQualifiers(),
3041 Brackets);
3042 }
3043
3044 }
3045 }
3046
Eli Friedmana553d4a2009-12-22 02:35:53 +00003047 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003048 return Sema::OwningExprResult(S, Args.release()[0]);
3049
3050 unsigned NumArgs = Args.size();
3051 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3052 SourceLocation(),
3053 (Expr **)Args.release(),
3054 NumArgs,
3055 SourceLocation()));
3056 }
3057
Douglas Gregor85dabae2009-12-16 01:38:02 +00003058 if (SequenceKind == NoInitialization)
3059 return S.Owned((Expr *)0);
3060
Douglas Gregor1b303932009-12-22 15:35:07 +00003061 QualType DestType = Entity.getType().getNonReferenceType();
3062 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003063 // the same as Entity.getDecl()->getType() in cases involving type merging,
3064 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003065 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003066 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003067 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003068
Douglas Gregor85dabae2009-12-16 01:38:02 +00003069 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3070
3071 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3072
3073 // For initialization steps that start with a single initializer,
3074 // grab the only argument out the Args and place it into the "current"
3075 // initializer.
3076 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003077 case SK_ResolveAddressOfOverloadedFunction:
3078 case SK_CastDerivedToBaseRValue:
3079 case SK_CastDerivedToBaseLValue:
3080 case SK_BindReference:
3081 case SK_BindReferenceToTemporary:
3082 case SK_UserConversion:
3083 case SK_QualificationConversionLValue:
3084 case SK_QualificationConversionRValue:
3085 case SK_ConversionSequence:
3086 case SK_ListInitialization:
3087 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003088 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003089 assert(Args.size() == 1);
3090 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3091 if (CurInit.isInvalid())
3092 return S.ExprError();
3093 break;
3094
3095 case SK_ConstructorInitialization:
3096 case SK_ZeroInitialization:
3097 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003098 }
3099
3100 // Walk through the computed steps for the initialization sequence,
3101 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003102 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 for (step_iterator Step = step_begin(), StepEnd = step_end();
3104 Step != StepEnd; ++Step) {
3105 if (CurInit.isInvalid())
3106 return S.ExprError();
3107
3108 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003109 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003110
3111 switch (Step->Kind) {
3112 case SK_ResolveAddressOfOverloadedFunction:
3113 // Overload resolution determined which function invoke; update the
3114 // initializer to reflect that choice.
3115 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3116 break;
3117
3118 case SK_CastDerivedToBaseRValue:
3119 case SK_CastDerivedToBaseLValue: {
3120 // We have a derived-to-base cast that produces either an rvalue or an
3121 // lvalue. Perform that cast.
3122
3123 // Casts to inaccessible base classes are allowed with C-style casts.
3124 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3125 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3126 CurInitExpr->getLocStart(),
3127 CurInitExpr->getSourceRange(),
3128 IgnoreBaseAccess))
3129 return S.ExprError();
3130
3131 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3132 CastExpr::CK_DerivedToBase,
3133 (Expr*)CurInit.release(),
3134 Step->Kind == SK_CastDerivedToBaseLValue));
3135 break;
3136 }
3137
3138 case SK_BindReference:
3139 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3140 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3141 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003142 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 << BitField->getDeclName()
3144 << CurInitExpr->getSourceRange();
3145 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3146 return S.ExprError();
3147 }
3148
3149 // Reference binding does not have any corresponding ASTs.
3150
3151 // Check exception specifications
3152 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3153 return S.ExprError();
3154 break;
3155
3156 case SK_BindReferenceToTemporary:
3157 // Check exception specifications
3158 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3159 return S.ExprError();
3160
3161 // FIXME: At present, we have no AST to describe when we need to make a
3162 // temporary to bind a reference to. We should.
3163 break;
3164
3165 case SK_UserConversion: {
3166 // We have a user-defined conversion that invokes either a constructor
3167 // or a conversion function.
3168 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003169 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003170 if (CXXConstructorDecl *Constructor
3171 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3172 // Build a call to the selected constructor.
3173 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3174 SourceLocation Loc = CurInitExpr->getLocStart();
3175 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3176
3177 // Determine the arguments required to actually perform the constructor
3178 // call.
3179 if (S.CompleteConstructorCall(Constructor,
3180 Sema::MultiExprArg(S,
3181 (void **)&CurInitExpr,
3182 1),
3183 Loc, ConstructorArgs))
3184 return S.ExprError();
3185
3186 // Build the an expression that constructs a temporary.
3187 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3188 move_arg(ConstructorArgs));
3189 if (CurInit.isInvalid())
3190 return S.ExprError();
3191
3192 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003193 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3194 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3195 S.IsDerivedFrom(SourceType, Class))
3196 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 } else {
3198 // Build a call to the conversion function.
3199 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 // FIXME: Should we move this initialization into a separate
3202 // derived-to-base conversion? I believe the answer is "no", because
3203 // we don't want to turn off access control here for c-style casts.
3204 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3205 return S.ExprError();
3206
3207 // Do a little dance to make sure that CurInit has the proper
3208 // pointer.
3209 CurInit.release();
3210
3211 // Build the actual call to the conversion function.
3212 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3213 if (CurInit.isInvalid() || !CurInit.get())
3214 return S.ExprError();
3215
3216 CastKind = CastExpr::CK_UserDefinedConversion;
3217 }
3218
Douglas Gregore1314a62009-12-18 05:02:21 +00003219 if (shouldBindAsTemporary(Entity, IsCopy))
3220 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003222 CurInitExpr = CurInit.takeAs<Expr>();
3223 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3224 CastKind,
3225 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003226 false));
3227
3228 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003229 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003230 break;
3231 }
3232
3233 case SK_QualificationConversionLValue:
3234 case SK_QualificationConversionRValue:
3235 // Perform a qualification conversion; these can never go wrong.
3236 S.ImpCastExprToType(CurInitExpr, Step->Type,
3237 CastExpr::CK_NoOp,
3238 Step->Kind == SK_QualificationConversionLValue);
3239 CurInit.release();
3240 CurInit = S.Owned(CurInitExpr);
3241 break;
3242
3243 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003244 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 false, false, *Step->ICS))
3246 return S.ExprError();
3247
3248 CurInit.release();
3249 CurInit = S.Owned(CurInitExpr);
3250 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003251
3252 case SK_ListInitialization: {
3253 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3254 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003255 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003256 return S.ExprError();
3257
3258 CurInit.release();
3259 CurInit = S.Owned(InitList);
3260 break;
3261 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003262
3263 case SK_ConstructorInitialization: {
3264 CXXConstructorDecl *Constructor
3265 = cast<CXXConstructorDecl>(Step->Function);
3266
3267 // Build a call to the selected constructor.
3268 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3269 SourceLocation Loc = Kind.getLocation();
3270
3271 // Determine the arguments required to actually perform the constructor
3272 // call.
3273 if (S.CompleteConstructorCall(Constructor, move(Args),
3274 Loc, ConstructorArgs))
3275 return S.ExprError();
3276
3277 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003278 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003279 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003280 move_arg(ConstructorArgs),
3281 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003282 if (CurInit.isInvalid())
3283 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003284
3285 bool Elidable
3286 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3287 if (shouldBindAsTemporary(Entity, Elidable))
3288 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3289
3290 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003291 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003292 break;
3293 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003294
3295 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003296 step_iterator NextStep = Step;
3297 ++NextStep;
3298 if (NextStep != StepEnd &&
3299 NextStep->Kind == SK_ConstructorInitialization) {
3300 // The need for zero-initialization is recorded directly into
3301 // the call to the object's constructor within the next step.
3302 ConstructorInitRequiresZeroInit = true;
3303 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3304 S.getLangOptions().CPlusPlus &&
3305 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003306 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3307 Kind.getRange().getBegin(),
3308 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003309 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003310 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003311 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003312 break;
3313 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003314
3315 case SK_CAssignment: {
3316 QualType SourceType = CurInitExpr->getType();
3317 Sema::AssignConvertType ConvTy =
3318 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003319
3320 // If this is a call, allow conversion to a transparent union.
3321 if (ConvTy != Sema::Compatible &&
3322 Entity.getKind() == InitializedEntity::EK_Parameter &&
3323 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3324 == Sema::Compatible)
3325 ConvTy = Sema::Compatible;
3326
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3328 Step->Type, SourceType,
3329 CurInitExpr, getAssignmentAction(Entity)))
3330 return S.ExprError();
3331
3332 CurInit.release();
3333 CurInit = S.Owned(CurInitExpr);
3334 break;
3335 }
Eli Friedman78275202009-12-19 08:11:05 +00003336
3337 case SK_StringInit: {
3338 QualType Ty = Step->Type;
3339 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3340 break;
3341 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003342 }
3343 }
3344
3345 return move(CurInit);
3346}
3347
3348//===----------------------------------------------------------------------===//
3349// Diagnose initialization failures
3350//===----------------------------------------------------------------------===//
3351bool InitializationSequence::Diagnose(Sema &S,
3352 const InitializedEntity &Entity,
3353 const InitializationKind &Kind,
3354 Expr **Args, unsigned NumArgs) {
3355 if (SequenceKind != FailedSequence)
3356 return false;
3357
Douglas Gregor1b303932009-12-22 15:35:07 +00003358 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003359 switch (Failure) {
3360 case FK_TooManyInitsForReference:
3361 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3362 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3363 break;
3364
3365 case FK_ArrayNeedsInitList:
3366 case FK_ArrayNeedsInitListOrStringLiteral:
3367 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3368 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3369 break;
3370
3371 case FK_AddressOfOverloadFailed:
3372 S.ResolveAddressOfOverloadedFunction(Args[0],
3373 DestType.getNonReferenceType(),
3374 true);
3375 break;
3376
3377 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003378 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003379 switch (FailedOverloadResult) {
3380 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003381 if (Failure == FK_UserConversionOverloadFailed)
3382 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3383 << Args[0]->getType() << DestType
3384 << Args[0]->getSourceRange();
3385 else
3386 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3387 << DestType << Args[0]->getType()
3388 << Args[0]->getSourceRange();
3389
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003390 S.PrintOverloadCandidates(FailedCandidateSet, true);
3391 break;
3392
3393 case OR_No_Viable_Function:
3394 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3395 << Args[0]->getType() << DestType.getNonReferenceType()
3396 << Args[0]->getSourceRange();
3397 S.PrintOverloadCandidates(FailedCandidateSet, false);
3398 break;
3399
3400 case OR_Deleted: {
3401 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3402 << Args[0]->getType() << DestType.getNonReferenceType()
3403 << Args[0]->getSourceRange();
3404 OverloadCandidateSet::iterator Best;
3405 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3406 Kind.getLocation(),
3407 Best);
3408 if (Ovl == OR_Deleted) {
3409 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3410 << Best->Function->isDeleted();
3411 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003412 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003413 }
3414 break;
3415 }
3416
3417 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003418 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 break;
3420 }
3421 break;
3422
3423 case FK_NonConstLValueReferenceBindingToTemporary:
3424 case FK_NonConstLValueReferenceBindingToUnrelated:
3425 S.Diag(Kind.getLocation(),
3426 Failure == FK_NonConstLValueReferenceBindingToTemporary
3427 ? diag::err_lvalue_reference_bind_to_temporary
3428 : diag::err_lvalue_reference_bind_to_unrelated)
3429 << DestType.getNonReferenceType()
3430 << Args[0]->getType()
3431 << Args[0]->getSourceRange();
3432 break;
3433
3434 case FK_RValueReferenceBindingToLValue:
3435 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3436 << Args[0]->getSourceRange();
3437 break;
3438
3439 case FK_ReferenceInitDropsQualifiers:
3440 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3441 << DestType.getNonReferenceType()
3442 << Args[0]->getType()
3443 << Args[0]->getSourceRange();
3444 break;
3445
3446 case FK_ReferenceInitFailed:
3447 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3448 << DestType.getNonReferenceType()
3449 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3450 << Args[0]->getType()
3451 << Args[0]->getSourceRange();
3452 break;
3453
3454 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003455 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3456 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003457 << DestType
3458 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3459 << Args[0]->getType()
3460 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003461 break;
3462
3463 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003464 SourceRange R;
3465
3466 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3467 R = SourceRange(InitList->getInit(1)->getLocStart(),
3468 InitList->getLocEnd());
3469 else
3470 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003471
3472 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003473 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003474 break;
3475 }
3476
3477 case FK_ReferenceBindingToInitList:
3478 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3479 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3480 break;
3481
3482 case FK_InitListBadDestinationType:
3483 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3484 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3485 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003486
3487 case FK_ConstructorOverloadFailed: {
3488 SourceRange ArgsRange;
3489 if (NumArgs)
3490 ArgsRange = SourceRange(Args[0]->getLocStart(),
3491 Args[NumArgs - 1]->getLocEnd());
3492
3493 // FIXME: Using "DestType" for the entity we're printing is probably
3494 // bad.
3495 switch (FailedOverloadResult) {
3496 case OR_Ambiguous:
3497 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3498 << DestType << ArgsRange;
3499 S.PrintOverloadCandidates(FailedCandidateSet, true);
3500 break;
3501
3502 case OR_No_Viable_Function:
3503 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3504 << DestType << ArgsRange;
3505 S.PrintOverloadCandidates(FailedCandidateSet, false);
3506 break;
3507
3508 case OR_Deleted: {
3509 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3510 << true << DestType << ArgsRange;
3511 OverloadCandidateSet::iterator Best;
3512 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3513 Kind.getLocation(),
3514 Best);
3515 if (Ovl == OR_Deleted) {
3516 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3517 << Best->Function->isDeleted();
3518 } else {
3519 llvm_unreachable("Inconsistent overload resolution?");
3520 }
3521 break;
3522 }
3523
3524 case OR_Success:
3525 llvm_unreachable("Conversion did not fail!");
3526 break;
3527 }
3528 break;
3529 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003530
3531 case FK_DefaultInitOfConst:
3532 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3533 << DestType;
3534 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003535 }
3536
3537 return true;
3538}
Douglas Gregore1314a62009-12-18 05:02:21 +00003539
3540//===----------------------------------------------------------------------===//
3541// Initialization helper functions
3542//===----------------------------------------------------------------------===//
3543Sema::OwningExprResult
3544Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3545 SourceLocation EqualLoc,
3546 OwningExprResult Init) {
3547 if (Init.isInvalid())
3548 return ExprError();
3549
3550 Expr *InitE = (Expr *)Init.get();
3551 assert(InitE && "No initialization expression?");
3552
3553 if (EqualLoc.isInvalid())
3554 EqualLoc = InitE->getLocStart();
3555
3556 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3557 EqualLoc);
3558 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3559 Init.release();
3560 return Seq.Perform(*this, Entity, Kind,
3561 MultiExprArg(*this, (void**)&InitE, 1));
3562}