blob: 00e2fba5fe2f790ace632b554c318732d719381a [file] [log] [blame]
Steve Naroff0cca7492008-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 Lattnerdd8e0062009-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 Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattner79e079d2009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman8718a6a2009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner8879e3b2009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000058
Eli Friedmanbb6415c2009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000065 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattnerdd8e0062009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattner79e079d2009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner79e079d2009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000086 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000087 }
Mike Stump1eb44332009-09-09 15:08:12 +000088
Eli Friedman8718a6a2009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Eli Friedman8718a6a2009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000098
Eli Friedman8718a6a2009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000104}
105
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregor9e80f722009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000137namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000214
Douglas Gregord6d37de2009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner8b419b92009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000230
Douglas Gregord6d37de2009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
266 Sema::OwningExprResult MemberInit
267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekba7bc552010-02-19 01:50:18 +0000284 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor4c678342009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Ted Kremenek6217b802009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000319
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000357
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssond3d824d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 Sema::OwningExprResult ElementInit
377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenekba7bc552010-02-19 01:50:18 +0000394 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattner68355a52009-01-29 05:10:57 +0000403
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000408
Eli Friedmanb85f7072008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000449}
450
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
461 else if (T->isStructureType() || T->isUnionType())
462 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000467
Eli Friedman402256f2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000483
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregored8a93d2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
507 << CodeModificationHint::CreateInsertion(
508 StructuredSubobjectInitList->getLocStart(),
Tanya Lattner47f164e2010-03-07 04:40:06 +0000509 "{")
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000510 << CodeModificationHint::CreateInsertion(
511 SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000512 StructuredSubobjectInitList->getLocEnd()),
513 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000514 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000515}
516
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000517void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000518 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 unsigned &Index,
520 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000521 unsigned &StructuredIndex,
522 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000523 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000524 SyntacticToSemantic[IList] = StructuredList;
525 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000526 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
527 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor2c792812010-02-09 00:50:06 +0000528 IList->setType(T.getNonReferenceType());
529 StructuredList->setType(T.getNonReferenceType());
Eli Friedman638e1442008-05-25 13:22:35 +0000530 if (hadError)
531 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532
Eli Friedman638e1442008-05-25 13:22:35 +0000533 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000534 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000535 if (StructuredIndex == 1 &&
536 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000539 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000540 hadError = true;
541 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000542 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000544 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000545 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000546 // Don't complain for incomplete types, since we'll get an error
547 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000548 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000549 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000550 CurrentObjectType->isArrayType()? 0 :
551 CurrentObjectType->isVectorType()? 1 :
552 CurrentObjectType->isScalarType()? 2 :
553 CurrentObjectType->isUnionType()? 3 :
554 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000555
556 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Nate Begeman08634522009-07-07 21:53:06 +0000561 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000565
Chris Lattner08202542009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000567 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000568 }
569 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000570
Eli Friedman759f2522009-05-16 11:45:48 +0000571 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000573 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000574 << CodeModificationHint::CreateRemoval(IList->getLocStart())
575 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000576}
577
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000578void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000579 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000580 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000581 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000582 unsigned &Index,
583 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000584 unsigned &StructuredIndex,
585 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000586 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000587 CheckScalarType(Entity, IList, DeclType, Index,
588 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000590 CheckVectorType(Entity, IList, DeclType, Index,
591 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000595 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000602 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000603 CheckArrayType(Entity, IList, DeclType, Zero,
604 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000606 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000627 CheckReferenceType(Entity, IList, DeclType, Index,
628 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000629 } else {
630 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000631 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000632 assert(0 && "Unsupported initializer type");
633 }
634}
635
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000664 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000671
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000672 // FIXME: Better EqualLoc?
673 InitializationKind Kind =
674 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
675 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
676
677 if (Seq) {
678 Sema::OwningExprResult Result =
679 Seq.Perform(SemaRef, Entity, Kind,
680 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
681 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000682 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000683
684 UpdateStructuredListElement(StructuredList, StructuredIndex,
685 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000686 ++Index;
687 return;
688 }
689
690 // Fall through for subaggregate initialization
691 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000692 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000693 //
694 // The initializer for a structure or union object that has
695 // automatic storage duration shall be either an initializer
696 // list as described below, or a single expression that has
697 // compatible structure or union type. In the latter case, the
698 // initial value of the object, including unnamed members, is
699 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000700 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000701 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000702 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 }
709
710 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000711 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000712 // [...] Otherwise, if the member is itself a non-empty
713 // subaggregate, brace elision is assumed and the initializer is
714 // considered for the initialization of the first member of
715 // the subaggregate.
716 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000717 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000718 StructuredIndex);
719 ++StructuredIndex;
720 } else {
721 // We cannot initialize this element, so let
722 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000723 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
724 SemaRef.Owned(expr));
725 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000726 hadError = true;
727 ++Index;
728 ++StructuredIndex;
729 }
730 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000731}
732
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000733void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000734 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000735 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000736 InitListExpr *StructuredList,
737 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000738 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000739 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000740 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000741 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000742 diag::err_many_braces_around_scalar_init)
743 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000744 hadError = true;
745 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000746 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000747 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000748 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000749 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000750 diag::err_designator_for_scalar_init)
751 << DeclType << expr->getSourceRange();
752 hadError = true;
753 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000755 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000756 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000757
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000758 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000759 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
760 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000761
Chandler Carruthb5719242010-02-13 07:23:01 +0000762 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000763
764 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000765 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000766 else {
767 ResultExpr = Result.takeAs<Expr>();
768
769 if (ResultExpr != expr) {
770 // The type was promoted, update initializer list.
771 IList->setInit(Index, ResultExpr);
772 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000773 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000774 if (hadError)
775 ++StructuredIndex;
776 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000777 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000778 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000779 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000781 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000782 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000783 ++Index;
784 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000785 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000786 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000787}
788
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000789void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
790 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000791 unsigned &Index,
792 InitListExpr *StructuredList,
793 unsigned &StructuredIndex) {
794 if (Index < IList->getNumInits()) {
795 Expr *expr = IList->getInit(Index);
796 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000798 << DeclType << IList->getSourceRange();
799 hadError = true;
800 ++Index;
801 ++StructuredIndex;
802 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000803 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000804
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000805 Sema::OwningExprResult Result =
806 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
807 SemaRef.Owned(expr));
808
809 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000810 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000811
812 expr = Result.takeAs<Expr>();
813 IList->setInit(Index, expr);
814
Douglas Gregor930d8b52009-01-30 22:09:00 +0000815 if (hadError)
816 ++StructuredIndex;
817 else
818 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
819 ++Index;
820 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000821 // FIXME: It would be wonderful if we could point at the actual member. In
822 // general, it would be useful to pass location information down the stack,
823 // so that we know the location (or decl) of the "current object" being
824 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000826 diag::err_init_reference_member_uninitialized)
827 << DeclType
828 << IList->getSourceRange();
829 hadError = true;
830 ++Index;
831 ++StructuredIndex;
832 return;
833 }
834}
835
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000836void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000837 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000838 unsigned &Index,
839 InitListExpr *StructuredList,
840 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000841 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000842 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000843 unsigned maxElements = VT->getNumElements();
844 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000845 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Nate Begeman2ef13e52009-08-10 23:49:36 +0000847 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000848 InitializedEntity ElementEntity =
849 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000850
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000851 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
852 // Don't attempt to go past the end of the init list
853 if (Index >= IList->getNumInits())
854 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000855
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000856 ElementEntity.setElementIndex(Index);
857 CheckSubElementType(ElementEntity, IList, elementType, Index,
858 StructuredList, StructuredIndex);
859 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000860 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000861 InitializedEntity ElementEntity =
862 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
863
Nate Begeman2ef13e52009-08-10 23:49:36 +0000864 // OpenCL initializers allows vectors to be constructed from vectors.
865 for (unsigned i = 0; i < maxElements; ++i) {
866 // Don't attempt to go past the end of the init list
867 if (Index >= IList->getNumInits())
868 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000869
870 ElementEntity.setElementIndex(Index);
871
Nate Begeman2ef13e52009-08-10 23:49:36 +0000872 QualType IType = IList->getInit(Index)->getType();
873 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000874 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000875 StructuredList, StructuredIndex);
876 ++numEltsInit;
877 } else {
John McCall183700f2009-09-21 23:43:11 +0000878 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000879 unsigned numIElts = IVT->getNumElements();
880 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
881 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000882 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000883 StructuredList, StructuredIndex);
884 numEltsInit += numIElts;
885 }
886 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000887 }
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Nate Begeman2ef13e52009-08-10 23:49:36 +0000889 // OpenCL & AltiVec require all elements to be initialized.
890 if (numEltsInit != maxElements)
891 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
892 SemaRef.Diag(IList->getSourceRange().getBegin(),
893 diag::err_vector_incorrect_num_initializers)
894 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 }
896}
897
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000898void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000899 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000900 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000901 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000902 unsigned &Index,
903 InitListExpr *StructuredList,
904 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000905 // Check for the special-case of initializing an array with a string.
906 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000907 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
908 SemaRef.Context)) {
909 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000910 // We place the string literal directly into the resulting
911 // initializer list. This is the only place where the structure
912 // of the structured initializer list doesn't match exactly,
913 // because doing so would involve allocating one character
914 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000915 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000916 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000917 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000918 return;
919 }
920 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000921 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000922 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000923 // Check for VLAs; in standard C it would be possible to check this
924 // earlier, but I don't know where clang accepts VLAs (gcc accepts
925 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000926 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000927 diag::err_variable_object_no_init)
928 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000929 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000930 ++Index;
931 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000932 return;
933 }
934
Douglas Gregor05c13a32009-01-22 00:58:24 +0000935 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000936 llvm::APSInt maxElements(elementIndex.getBitWidth(),
937 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000938 bool maxElementsKnown = false;
939 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000940 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000941 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000942 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000943 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000944 maxElementsKnown = true;
945 }
946
Chris Lattner08202542009-02-24 22:50:46 +0000947 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000948 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000949 while (Index < IList->getNumInits()) {
950 Expr *Init = IList->getInit(Index);
951 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000952 // If we're not the subobject that matches up with the '{' for
953 // the designator, we shouldn't be handling the
954 // designator. Return immediately.
955 if (!SubobjectIsDesignatorContext)
956 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000957
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000958 // Handle this designated initializer. elementIndex will be
959 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000960 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000961 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000962 StructuredList, StructuredIndex, true,
963 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000964 hadError = true;
965 continue;
966 }
967
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000968 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
969 maxElements.extend(elementIndex.getBitWidth());
970 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
971 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000972 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000973
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000974 // If the array is of incomplete type, keep track of the number of
975 // elements in the initializer.
976 if (!maxElementsKnown && elementIndex > maxElements)
977 maxElements = elementIndex;
978
Douglas Gregor05c13a32009-01-22 00:58:24 +0000979 continue;
980 }
981
982 // If we know the maximum number of elements, and we've already
983 // hit it, stop consuming elements in the initializer list.
984 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000985 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000987 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000988 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000989 Entity);
990 // Check this element.
991 CheckSubElementType(ElementEntity, IList, elementType, Index,
992 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000993 ++elementIndex;
994
995 // If the array is of incomplete type, keep track of the number of
996 // elements in the initializer.
997 if (!maxElementsKnown && elementIndex > maxElements)
998 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000999 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001000 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001001 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001002 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001003 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001004 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001005 // Sizing an array implicitly to zero is not allowed by ISO C,
1006 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001007 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001008 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001009 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001010
Mike Stump1eb44332009-09-09 15:08:12 +00001011 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001012 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001013 }
1014}
1015
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001016void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001017 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001018 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001019 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001020 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001021 unsigned &Index,
1022 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001023 unsigned &StructuredIndex,
1024 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Eli Friedmanb85f7072008-05-19 19:16:24 +00001027 // If the record is invalid, some of it's members are invalid. To avoid
1028 // confusion, we forgo checking the intializer for the entire record.
1029 if (structDecl->isInvalidDecl()) {
1030 hadError = true;
1031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001032 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001033
1034 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1035 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001037 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001038 Field != FieldEnd; ++Field) {
1039 if (Field->getDeclName()) {
1040 StructuredList->setInitializedFieldInUnion(*Field);
1041 break;
1042 }
1043 }
1044 return;
1045 }
1046
Douglas Gregor05c13a32009-01-22 00:58:24 +00001047 // If structDecl is a forward declaration, this loop won't do
1048 // anything except look at designated initializers; That's okay,
1049 // because an error should get printed out elsewhere. It might be
1050 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001052 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001053 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001054 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001055 while (Index < IList->getNumInits()) {
1056 Expr *Init = IList->getInit(Index);
1057
1058 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001059 // If we're not the subobject that matches up with the '{' for
1060 // the designator, we shouldn't be handling the
1061 // designator. Return immediately.
1062 if (!SubobjectIsDesignatorContext)
1063 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001064
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001065 // Handle this designated initializer. Field will be updated to
1066 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001067 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001068 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001069 StructuredList, StructuredIndex,
1070 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001071 hadError = true;
1072
Douglas Gregordfb5e592009-02-12 19:00:39 +00001073 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001074
1075 // Disable check for missing fields when designators are used.
1076 // This matches gcc behaviour.
1077 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001078 continue;
1079 }
1080
1081 if (Field == FieldEnd) {
1082 // We've run out of fields. We're done.
1083 break;
1084 }
1085
Douglas Gregordfb5e592009-02-12 19:00:39 +00001086 // We've already initialized a member of a union. We're done.
1087 if (InitializedSomething && DeclType->isUnionType())
1088 break;
1089
Douglas Gregor44b43212008-12-11 16:49:14 +00001090 // If we've hit the flexible array member at the end, we're done.
1091 if (Field->getType()->isIncompleteArrayType())
1092 break;
1093
Douglas Gregor0bb76892009-01-29 16:53:55 +00001094 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001095 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001097 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001098 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001099
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001100 InitializedEntity MemberEntity =
1101 InitializedEntity::InitializeMember(*Field, &Entity);
1102 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1103 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001104 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001105
1106 if (DeclType->isUnionType()) {
1107 // Initialize the first field within the union.
1108 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001109 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001110
1111 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001113
John McCall80639de2010-03-11 19:32:38 +00001114 // Emit warnings for missing struct field initializers.
1115 if (CheckForMissingFields && Field != FieldEnd &&
1116 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1117 // It is possible we have one or more unnamed bitfields remaining.
1118 // Find first (if any) named field and emit warning.
1119 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1120 it != end; ++it) {
1121 if (!it->isUnnamedBitfield()) {
1122 SemaRef.Diag(IList->getSourceRange().getEnd(),
1123 diag::warn_missing_field_initializers) << it->getName();
1124 break;
1125 }
1126 }
1127 }
1128
Mike Stump1eb44332009-09-09 15:08:12 +00001129 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001130 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001131 return;
1132
1133 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001134 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001135 (!isa<InitListExpr>(IList->getInit(Index)) ||
1136 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001137 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001138 diag::err_flexible_array_init_nonempty)
1139 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001140 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001141 << *Field;
1142 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001143 ++Index;
1144 return;
1145 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001146 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001147 diag::ext_flexible_array_init)
1148 << IList->getInit(Index)->getSourceRange().getBegin();
1149 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1150 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001151 }
1152
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001153 InitializedEntity MemberEntity =
1154 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001155
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001156 if (isa<InitListExpr>(IList->getInit(Index)))
1157 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1158 StructuredList, StructuredIndex);
1159 else
1160 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001161 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001162}
Steve Naroff0cca7492008-05-01 22:18:59 +00001163
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001164/// \brief Expand a field designator that refers to a member of an
1165/// anonymous struct or union into a series of field designators that
1166/// refers to the field within the appropriate subobject.
1167///
1168/// Field/FieldIndex will be updated to point to the (new)
1169/// currently-designated field.
1170static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001171 DesignatedInitExpr *DIE,
1172 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001173 FieldDecl *Field,
1174 RecordDecl::field_iterator &FieldIter,
1175 unsigned &FieldIndex) {
1176 typedef DesignatedInitExpr::Designator Designator;
1177
1178 // Build the path from the current object to the member of the
1179 // anonymous struct/union (backwards).
1180 llvm::SmallVector<FieldDecl *, 4> Path;
1181 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001183 // Build the replacement designators.
1184 llvm::SmallVector<Designator, 4> Replacements;
1185 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1186 FI = Path.rbegin(), FIEnd = Path.rend();
1187 FI != FIEnd; ++FI) {
1188 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001189 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001190 DIE->getDesignator(DesigIdx)->getDotLoc(),
1191 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1192 else
1193 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1194 SourceLocation()));
1195 Replacements.back().setField(*FI);
1196 }
1197
1198 // Expand the current designator into the set of replacement
1199 // designators, so we have a full subobject path down to where the
1200 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001201 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001202 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001204 // Update FieldIter/FieldIndex;
1205 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001207 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001208 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001209 FieldIter != FEnd; ++FieldIter) {
1210 if (FieldIter->isUnnamedBitfield())
1211 continue;
1212
1213 if (*FieldIter == Path.back())
1214 return;
1215
1216 ++FieldIndex;
1217 }
1218
1219 assert(false && "Unable to find anonymous struct/union field");
1220}
1221
Douglas Gregor05c13a32009-01-22 00:58:24 +00001222/// @brief Check the well-formedness of a C99 designated initializer.
1223///
1224/// Determines whether the designated initializer @p DIE, which
1225/// resides at the given @p Index within the initializer list @p
1226/// IList, is well-formed for a current object of type @p DeclType
1227/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001228/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001229/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001230///
1231/// @param IList The initializer list in which this designated
1232/// initializer occurs.
1233///
Douglas Gregor71199712009-04-15 04:56:10 +00001234/// @param DIE The designated initializer expression.
1235///
1236/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001237///
1238/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1239/// into which the designation in @p DIE should refer.
1240///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001241/// @param NextField If non-NULL and the first designator in @p DIE is
1242/// a field, this will be set to the field declaration corresponding
1243/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001244///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001245/// @param NextElementIndex If non-NULL and the first designator in @p
1246/// DIE is an array designator or GNU array-range designator, this
1247/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001248///
1249/// @param Index Index into @p IList where the designated initializer
1250/// @p DIE occurs.
1251///
Douglas Gregor4c678342009-01-28 21:54:33 +00001252/// @param StructuredList The initializer list expression that
1253/// describes all of the subobject initializers in the order they'll
1254/// actually be initialized.
1255///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001256/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001257bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001258InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001259 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001260 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001261 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001262 QualType &CurrentObjectType,
1263 RecordDecl::field_iterator *NextField,
1264 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001265 unsigned &Index,
1266 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001267 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001268 bool FinishSubobjectInit,
1269 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001270 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001271 // Check the actual initialization for the designated object type.
1272 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001273
1274 // Temporarily remove the designator expression from the
1275 // initializer list that the child calls see, so that we don't try
1276 // to re-process the designator.
1277 unsigned OldIndex = Index;
1278 IList->setInit(OldIndex, DIE->getInit());
1279
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001280 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001281 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001282
1283 // Restore the designated initializer expression in the syntactic
1284 // form of the initializer list.
1285 if (IList->getInit(OldIndex) != DIE->getInit())
1286 DIE->setInit(IList->getInit(OldIndex));
1287 IList->setInit(OldIndex, DIE);
1288
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001289 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001290 }
1291
Douglas Gregor71199712009-04-15 04:56:10 +00001292 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001293 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001294 "Need a non-designated initializer list to start from");
1295
Douglas Gregor71199712009-04-15 04:56:10 +00001296 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001297 // Determine the structural initializer list that corresponds to the
1298 // current subobject.
1299 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001300 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001301 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 SourceRange(D->getStartLocation(),
1303 DIE->getSourceRange().getEnd()));
1304 assert(StructuredList && "Expected a structured initializer list");
1305
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001306 if (D->isFieldDesignator()) {
1307 // C99 6.7.8p7:
1308 //
1309 // If a designator has the form
1310 //
1311 // . identifier
1312 //
1313 // then the current object (defined below) shall have
1314 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001315 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001316 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001317 if (!RT) {
1318 SourceLocation Loc = D->getDotLoc();
1319 if (Loc.isInvalid())
1320 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001321 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1322 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001323 ++Index;
1324 return true;
1325 }
1326
Douglas Gregor4c678342009-01-28 21:54:33 +00001327 // Note: we perform a linear search of the fields here, despite
1328 // the fact that we have a faster lookup method, because we always
1329 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001330 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001331 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001332 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001333 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001334 Field = RT->getDecl()->field_begin(),
1335 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001336 for (; Field != FieldEnd; ++Field) {
1337 if (Field->isUnnamedBitfield())
1338 continue;
1339
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001340 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001341 break;
1342
1343 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001344 }
1345
Douglas Gregor4c678342009-01-28 21:54:33 +00001346 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001347 // There was no normal field in the struct with the designated
1348 // name. Perform another lookup for this name, which may find
1349 // something that we can't designate (e.g., a member function),
1350 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001351 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001352 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001353 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001354 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001355 // Name lookup didn't find anything. Determine whether this
1356 // was a typo for another field name.
1357 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1358 Sema::LookupMemberName);
1359 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1360 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1361 ReplacementField->getDeclContext()->getLookupContext()
1362 ->Equals(RT->getDecl())) {
1363 SemaRef.Diag(D->getFieldLoc(),
1364 diag::err_field_designator_unknown_suggest)
1365 << FieldName << CurrentObjectType << R.getLookupName()
1366 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1367 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001368 SemaRef.Diag(ReplacementField->getLocation(),
1369 diag::note_previous_decl)
1370 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001371 } else {
1372 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1373 << FieldName << CurrentObjectType;
1374 ++Index;
1375 return true;
1376 }
1377 } else if (!KnownField) {
1378 // Determine whether we found a field at all.
1379 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1380 }
1381
1382 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001383 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001384 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001385 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001386 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001387 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001388 ++Index;
1389 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001390 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001391
1392 if (!KnownField &&
1393 cast<RecordDecl>((ReplacementField)->getDeclContext())
1394 ->isAnonymousStructOrUnion()) {
1395 // Handle an field designator that refers to a member of an
1396 // anonymous struct or union.
1397 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1398 ReplacementField,
1399 Field, FieldIndex);
1400 D = DIE->getDesignator(DesigIdx);
1401 } else if (!KnownField) {
1402 // The replacement field comes from typo correction; find it
1403 // in the list of fields.
1404 FieldIndex = 0;
1405 Field = RT->getDecl()->field_begin();
1406 for (; Field != FieldEnd; ++Field) {
1407 if (Field->isUnnamedBitfield())
1408 continue;
1409
1410 if (ReplacementField == *Field ||
1411 Field->getIdentifier() == ReplacementField->getIdentifier())
1412 break;
1413
1414 ++FieldIndex;
1415 }
1416 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001417 } else if (!KnownField &&
1418 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001419 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001420 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1421 Field, FieldIndex);
1422 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001423 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001424
1425 // All of the fields of a union are located at the same place in
1426 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001427 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001428 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001429 StructuredList->setInitializedFieldInUnion(*Field);
1430 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001431
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001432 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001433 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 // Make sure that our non-designated initializer list has space
1436 // for a subobject corresponding to this field.
1437 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001438 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001439
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001440 // This designator names a flexible array member.
1441 if (Field->getType()->isIncompleteArrayType()) {
1442 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001443 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001444 // We can't designate an object within the flexible array
1445 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001446 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001447 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001448 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001450 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001452 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001453 << *Field;
1454 Invalid = true;
1455 }
1456
1457 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1458 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001459 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 diag::err_flexible_array_init_needs_braces)
1461 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001462 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001463 << *Field;
1464 Invalid = true;
1465 }
1466
1467 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001468 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001470 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001471 diag::err_flexible_array_init_nonempty)
1472 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001473 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001474 << *Field;
1475 Invalid = true;
1476 }
1477
1478 if (Invalid) {
1479 ++Index;
1480 return true;
1481 }
1482
1483 // Initialize the array.
1484 bool prevHadError = hadError;
1485 unsigned newStructuredIndex = FieldIndex;
1486 unsigned OldIndex = Index;
1487 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001488
1489 InitializedEntity MemberEntity =
1490 InitializedEntity::InitializeMember(*Field, &Entity);
1491 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001493
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001494 IList->setInit(OldIndex, DIE);
1495 if (hadError && !prevHadError) {
1496 ++Field;
1497 ++FieldIndex;
1498 if (NextField)
1499 *NextField = Field;
1500 StructuredIndex = FieldIndex;
1501 return true;
1502 }
1503 } else {
1504 // Recurse to check later designated subobjects.
1505 QualType FieldType = (*Field)->getType();
1506 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001507
1508 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001509 InitializedEntity::InitializeMember(*Field, &Entity);
1510 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001511 FieldType, 0, 0, Index,
1512 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001513 true, false))
1514 return true;
1515 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001516
1517 // Find the position of the next field to be initialized in this
1518 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001519 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001520 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001521
1522 // If this the first designator, our caller will continue checking
1523 // the rest of this struct/class/union subobject.
1524 if (IsFirstDesignator) {
1525 if (NextField)
1526 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001527 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001528 return false;
1529 }
1530
Douglas Gregor34e79462009-01-28 23:36:17 +00001531 if (!FinishSubobjectInit)
1532 return false;
1533
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001534 // We've already initialized something in the union; we're done.
1535 if (RT->getDecl()->isUnion())
1536 return hadError;
1537
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001538 // Check the remaining fields within this class/struct/union subobject.
1539 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001540
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001541 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001542 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001543 return hadError && !prevHadError;
1544 }
1545
1546 // C99 6.7.8p6:
1547 //
1548 // If a designator has the form
1549 //
1550 // [ constant-expression ]
1551 //
1552 // then the current object (defined below) shall have array
1553 // type and the expression shall be an integer constant
1554 // expression. If the array is of unknown size, any
1555 // nonnegative value is valid.
1556 //
1557 // Additionally, cope with the GNU extension that permits
1558 // designators of the form
1559 //
1560 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001561 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001563 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001564 << CurrentObjectType;
1565 ++Index;
1566 return true;
1567 }
1568
1569 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001570 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1571 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001573 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001574 DesignatedEndIndex = DesignatedStartIndex;
1575 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001577
Mike Stump1eb44332009-09-09 15:08:12 +00001578
1579 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001580 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001581 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001582 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001583 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001584
Chris Lattner3bf68932009-04-25 21:59:05 +00001585 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001586 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587 }
1588
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589 if (isa<ConstantArrayType>(AT)) {
1590 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001591 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1592 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1593 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1594 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1595 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001596 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001598 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001599 << IndexExpr->getSourceRange();
1600 ++Index;
1601 return true;
1602 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001603 } else {
1604 // Make sure the bit-widths and signedness match.
1605 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1606 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001607 else if (DesignatedStartIndex.getBitWidth() <
1608 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001609 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1610 DesignatedStartIndex.setIsUnsigned(true);
1611 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor4c678342009-01-28 21:54:33 +00001614 // Make sure that our non-designated initializer list has space
1615 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001616 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001617 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001618 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001619
Douglas Gregor34e79462009-01-28 23:36:17 +00001620 // Repeatedly perform subobject initializations in the range
1621 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001622
Douglas Gregor34e79462009-01-28 23:36:17 +00001623 // Move to the next designator
1624 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1625 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001626
1627 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001628 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001629
Douglas Gregor34e79462009-01-28 23:36:17 +00001630 while (DesignatedStartIndex <= DesignatedEndIndex) {
1631 // Recurse to check later designated subobjects.
1632 QualType ElementType = AT->getElementType();
1633 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001634
1635 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001636 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001637 ElementType, 0, 0, Index,
1638 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001639 (DesignatedStartIndex == DesignatedEndIndex),
1640 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001641 return true;
1642
1643 // Move to the next index in the array that we'll be initializing.
1644 ++DesignatedStartIndex;
1645 ElementIndex = DesignatedStartIndex.getZExtValue();
1646 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001647
1648 // If this the first designator, our caller will continue checking
1649 // the rest of this array subobject.
1650 if (IsFirstDesignator) {
1651 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001652 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001653 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 return false;
1655 }
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Douglas Gregor34e79462009-01-28 23:36:17 +00001657 if (!FinishSubobjectInit)
1658 return false;
1659
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001660 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001662 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001663 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001664 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001665 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001666}
1667
Douglas Gregor4c678342009-01-28 21:54:33 +00001668// Get the structured initializer list for a subobject of type
1669// @p CurrentObjectType.
1670InitListExpr *
1671InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1672 QualType CurrentObjectType,
1673 InitListExpr *StructuredList,
1674 unsigned StructuredIndex,
1675 SourceRange InitRange) {
1676 Expr *ExistingInit = 0;
1677 if (!StructuredList)
1678 ExistingInit = SyntacticToSemantic[IList];
1679 else if (StructuredIndex < StructuredList->getNumInits())
1680 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Douglas Gregor4c678342009-01-28 21:54:33 +00001682 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1683 return Result;
1684
1685 if (ExistingInit) {
1686 // We are creating an initializer list that initializes the
1687 // subobjects of the current object, but there was already an
1688 // initialization that completely initialized the current
1689 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001690 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001691 // struct X { int a, b; };
1692 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001693 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1695 // designated initializer re-initializes the whole
1696 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001697 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001698 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001699 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001700 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001701 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001702 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001703 << ExistingInit->getSourceRange();
1704 }
1705
Mike Stump1eb44332009-09-09 15:08:12 +00001706 InitListExpr *Result
Ted Kremenekba7bc552010-02-19 01:50:18 +00001707 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1708 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001709
Douglas Gregor2c792812010-02-09 00:50:06 +00001710 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001711
Douglas Gregorfa219202009-03-20 23:58:33 +00001712 // Pre-allocate storage for the structured initializer list.
1713 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001714 unsigned NumInits = 0;
1715 if (!StructuredList)
1716 NumInits = IList->getNumInits();
1717 else if (Index < IList->getNumInits()) {
1718 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1719 NumInits = SubList->getNumInits();
1720 }
1721
Mike Stump1eb44332009-09-09 15:08:12 +00001722 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001723 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1724 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1725 NumElements = CAType->getSize().getZExtValue();
1726 // Simple heuristic so that we don't allocate a very large
1727 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001728 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001729 NumElements = 0;
1730 }
John McCall183700f2009-09-21 23:43:11 +00001731 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001732 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001733 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001734 RecordDecl *RDecl = RType->getDecl();
1735 if (RDecl->isUnion())
1736 NumElements = 1;
1737 else
Mike Stump1eb44332009-09-09 15:08:12 +00001738 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001739 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001740 }
1741
Douglas Gregor08457732009-03-21 18:13:52 +00001742 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001743 NumElements = IList->getNumInits();
1744
Ted Kremenekba7bc552010-02-19 01:50:18 +00001745 Result->reserveInits(NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001746
Douglas Gregor4c678342009-01-28 21:54:33 +00001747 // Link this new initializer list into the structured initializer
1748 // lists.
1749 if (StructuredList)
Ted Kremenekba7bc552010-02-19 01:50:18 +00001750 StructuredList->updateInit(StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 else {
1752 Result->setSyntacticForm(IList);
1753 SyntacticToSemantic[IList] = Result;
1754 }
1755
1756 return Result;
1757}
1758
1759/// Update the initializer at index @p StructuredIndex within the
1760/// structured initializer list to the value @p expr.
1761void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1762 unsigned &StructuredIndex,
1763 Expr *expr) {
1764 // No structured initializer list to update
1765 if (!StructuredList)
1766 return;
1767
Ted Kremenekba7bc552010-02-19 01:50:18 +00001768 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001770 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001771 diag::warn_initializer_overrides)
1772 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001773 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001775 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001776 << PrevInit->getSourceRange();
1777 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 ++StructuredIndex;
1780}
1781
Douglas Gregor05c13a32009-01-22 00:58:24 +00001782/// Check that the given Index expression is a valid array designator
1783/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001784/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001785/// and produces a reasonable diagnostic if there is a
1786/// failure. Returns true if there was an error, false otherwise. If
1787/// everything went okay, Value will receive the value of the constant
1788/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001789static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001790CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001791 SourceLocation Loc = Index->getSourceRange().getBegin();
1792
1793 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001794 if (S.VerifyIntegerConstantExpression(Index, &Value))
1795 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001796
Chris Lattner3bf68932009-04-25 21:59:05 +00001797 if (Value.isSigned() && Value.isNegative())
1798 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001799 << Value.toString(10) << Index->getSourceRange();
1800
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001801 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001802 return false;
1803}
1804
1805Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1806 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001807 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001808 OwningExprResult Init) {
1809 typedef DesignatedInitExpr::Designator ASTDesignator;
1810
1811 bool Invalid = false;
1812 llvm::SmallVector<ASTDesignator, 32> Designators;
1813 llvm::SmallVector<Expr *, 32> InitExpressions;
1814
1815 // Build designators and check array designator expressions.
1816 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1817 const Designator &D = Desig.getDesignator(Idx);
1818 switch (D.getKind()) {
1819 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001820 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001821 D.getFieldLoc()));
1822 break;
1823
1824 case Designator::ArrayDesignator: {
1825 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1826 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001827 if (!Index->isTypeDependent() &&
1828 !Index->isValueDependent() &&
1829 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001830 Invalid = true;
1831 else {
1832 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001833 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001834 D.getRBracketLoc()));
1835 InitExpressions.push_back(Index);
1836 }
1837 break;
1838 }
1839
1840 case Designator::ArrayRangeDesignator: {
1841 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1842 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1843 llvm::APSInt StartValue;
1844 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001845 bool StartDependent = StartIndex->isTypeDependent() ||
1846 StartIndex->isValueDependent();
1847 bool EndDependent = EndIndex->isTypeDependent() ||
1848 EndIndex->isValueDependent();
1849 if ((!StartDependent &&
1850 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1851 (!EndDependent &&
1852 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001853 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001854 else {
1855 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001856 if (StartDependent || EndDependent) {
1857 // Nothing to compute.
1858 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001859 EndValue.extend(StartValue.getBitWidth());
1860 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1861 StartValue.extend(EndValue.getBitWidth());
1862
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001863 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001864 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001865 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001866 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1867 Invalid = true;
1868 } else {
1869 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001870 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001871 D.getEllipsisLoc(),
1872 D.getRBracketLoc()));
1873 InitExpressions.push_back(StartIndex);
1874 InitExpressions.push_back(EndIndex);
1875 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001876 }
1877 break;
1878 }
1879 }
1880 }
1881
1882 if (Invalid || Init.isInvalid())
1883 return ExprError();
1884
1885 // Clear out the expressions within the designation.
1886 Desig.ClearExprs(*this);
1887
1888 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001889 = DesignatedInitExpr::Create(Context,
1890 Designators.data(), Designators.size(),
1891 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001892 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001893 return Owned(DIE);
1894}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001895
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001896bool Sema::CheckInitList(const InitializedEntity &Entity,
1897 InitListExpr *&InitList, QualType &DeclType) {
1898 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001899 if (!CheckInitList.HadError())
1900 InitList = CheckInitList.getFullyStructuredList();
1901
1902 return CheckInitList.HadError();
1903}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001904
Douglas Gregor20093b42009-12-09 23:02:17 +00001905//===----------------------------------------------------------------------===//
1906// Initialization entity
1907//===----------------------------------------------------------------------===//
1908
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001909InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1910 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001911 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001912{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001913 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1914 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001915 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001916 } else {
1917 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001918 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001919 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001920}
1921
1922InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1923 CXXBaseSpecifier *Base)
1924{
1925 InitializedEntity Result;
1926 Result.Kind = EK_Base;
1927 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001928 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001929 return Result;
1930}
1931
Douglas Gregor99a2e602009-12-16 01:38:02 +00001932DeclarationName InitializedEntity::getName() const {
1933 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001934 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001935 if (!VariableOrMember)
1936 return DeclarationName();
1937 // Fall through
1938
1939 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001940 case EK_Member:
1941 return VariableOrMember->getDeclName();
1942
1943 case EK_Result:
1944 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001945 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001946 case EK_Temporary:
1947 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001948 case EK_ArrayElement:
1949 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001950 return DeclarationName();
1951 }
1952
1953 // Silence GCC warning
1954 return DeclarationName();
1955}
1956
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001957DeclaratorDecl *InitializedEntity::getDecl() const {
1958 switch (getKind()) {
1959 case EK_Variable:
1960 case EK_Parameter:
1961 case EK_Member:
1962 return VariableOrMember;
1963
1964 case EK_Result:
1965 case EK_Exception:
1966 case EK_New:
1967 case EK_Temporary:
1968 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001969 case EK_ArrayElement:
1970 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001971 return 0;
1972 }
1973
1974 // Silence GCC warning
1975 return 0;
1976}
1977
Douglas Gregor20093b42009-12-09 23:02:17 +00001978//===----------------------------------------------------------------------===//
1979// Initialization sequence
1980//===----------------------------------------------------------------------===//
1981
1982void InitializationSequence::Step::Destroy() {
1983 switch (Kind) {
1984 case SK_ResolveAddressOfOverloadedFunction:
1985 case SK_CastDerivedToBaseRValue:
1986 case SK_CastDerivedToBaseLValue:
1987 case SK_BindReference:
1988 case SK_BindReferenceToTemporary:
1989 case SK_UserConversion:
1990 case SK_QualificationConversionRValue:
1991 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001992 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001993 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001994 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001995 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001996 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001997 break;
1998
1999 case SK_ConversionSequence:
2000 delete ICS;
2001 }
2002}
2003
Douglas Gregorb70cf442010-03-26 20:14:36 +00002004bool InitializationSequence::isDirectReferenceBinding() const {
2005 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2006}
2007
2008bool InitializationSequence::isAmbiguous() const {
2009 if (getKind() != FailedSequence)
2010 return false;
2011
2012 switch (getFailureKind()) {
2013 case FK_TooManyInitsForReference:
2014 case FK_ArrayNeedsInitList:
2015 case FK_ArrayNeedsInitListOrStringLiteral:
2016 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2017 case FK_NonConstLValueReferenceBindingToTemporary:
2018 case FK_NonConstLValueReferenceBindingToUnrelated:
2019 case FK_RValueReferenceBindingToLValue:
2020 case FK_ReferenceInitDropsQualifiers:
2021 case FK_ReferenceInitFailed:
2022 case FK_ConversionFailed:
2023 case FK_TooManyInitsForScalar:
2024 case FK_ReferenceBindingToInitList:
2025 case FK_InitListBadDestinationType:
2026 case FK_DefaultInitOfConst:
2027 return false;
2028
2029 case FK_ReferenceInitOverloadFailed:
2030 case FK_UserConversionOverloadFailed:
2031 case FK_ConstructorOverloadFailed:
2032 return FailedOverloadResult == OR_Ambiguous;
2033 }
2034
2035 return false;
2036}
2037
Douglas Gregor20093b42009-12-09 23:02:17 +00002038void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002039 FunctionDecl *Function,
2040 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002041 Step S;
2042 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2043 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002044 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002045 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002046 Steps.push_back(S);
2047}
2048
2049void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2050 bool IsLValue) {
2051 Step S;
2052 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2053 S.Type = BaseType;
2054 Steps.push_back(S);
2055}
2056
2057void InitializationSequence::AddReferenceBindingStep(QualType T,
2058 bool BindingTemporary) {
2059 Step S;
2060 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2061 S.Type = T;
2062 Steps.push_back(S);
2063}
2064
Eli Friedman03981012009-12-11 02:42:07 +00002065void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002066 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002067 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002068 Step S;
2069 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002070 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002071 S.Function.Function = Function;
2072 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002073 Steps.push_back(S);
2074}
2075
2076void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2077 bool IsLValue) {
2078 Step S;
2079 S.Kind = IsLValue? SK_QualificationConversionLValue
2080 : SK_QualificationConversionRValue;
2081 S.Type = Ty;
2082 Steps.push_back(S);
2083}
2084
2085void InitializationSequence::AddConversionSequenceStep(
2086 const ImplicitConversionSequence &ICS,
2087 QualType T) {
2088 Step S;
2089 S.Kind = SK_ConversionSequence;
2090 S.Type = T;
2091 S.ICS = new ImplicitConversionSequence(ICS);
2092 Steps.push_back(S);
2093}
2094
Douglas Gregord87b61f2009-12-10 17:56:55 +00002095void InitializationSequence::AddListInitializationStep(QualType T) {
2096 Step S;
2097 S.Kind = SK_ListInitialization;
2098 S.Type = T;
2099 Steps.push_back(S);
2100}
2101
Douglas Gregor51c56d62009-12-14 20:49:26 +00002102void
2103InitializationSequence::AddConstructorInitializationStep(
2104 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002105 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002106 QualType T) {
2107 Step S;
2108 S.Kind = SK_ConstructorInitialization;
2109 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002110 S.Function.Function = Constructor;
2111 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002112 Steps.push_back(S);
2113}
2114
Douglas Gregor71d17402009-12-15 00:01:57 +00002115void InitializationSequence::AddZeroInitializationStep(QualType T) {
2116 Step S;
2117 S.Kind = SK_ZeroInitialization;
2118 S.Type = T;
2119 Steps.push_back(S);
2120}
2121
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002122void InitializationSequence::AddCAssignmentStep(QualType T) {
2123 Step S;
2124 S.Kind = SK_CAssignment;
2125 S.Type = T;
2126 Steps.push_back(S);
2127}
2128
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002129void InitializationSequence::AddStringInitStep(QualType T) {
2130 Step S;
2131 S.Kind = SK_StringInit;
2132 S.Type = T;
2133 Steps.push_back(S);
2134}
2135
Douglas Gregor20093b42009-12-09 23:02:17 +00002136void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2137 OverloadingResult Result) {
2138 SequenceKind = FailedSequence;
2139 this->Failure = Failure;
2140 this->FailedOverloadResult = Result;
2141}
2142
2143//===----------------------------------------------------------------------===//
2144// Attempt initialization
2145//===----------------------------------------------------------------------===//
2146
2147/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002148static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 const InitializedEntity &Entity,
2150 const InitializationKind &Kind,
2151 InitListExpr *InitList,
2152 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002153 // FIXME: We only perform rudimentary checking of list
2154 // initializations at this point, then assume that any list
2155 // initialization of an array, aggregate, or scalar will be
2156 // well-formed. We we actually "perform" list initialization, we'll
2157 // do all of the necessary checking. C++0x initializer lists will
2158 // force us to perform more checking here.
2159 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2160
Douglas Gregord6542d82009-12-22 15:35:07 +00002161 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002162
2163 // C++ [dcl.init]p13:
2164 // If T is a scalar type, then a declaration of the form
2165 //
2166 // T x = { a };
2167 //
2168 // is equivalent to
2169 //
2170 // T x = a;
2171 if (DestType->isScalarType()) {
2172 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2173 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2174 return;
2175 }
2176
2177 // Assume scalar initialization from a single value works.
2178 } else if (DestType->isAggregateType()) {
2179 // Assume aggregate initialization works.
2180 } else if (DestType->isVectorType()) {
2181 // Assume vector initialization works.
2182 } else if (DestType->isReferenceType()) {
2183 // FIXME: C++0x defines behavior for this.
2184 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2185 return;
2186 } else if (DestType->isRecordType()) {
2187 // FIXME: C++0x defines behavior for this
2188 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2189 }
2190
2191 // Add a general "list initialization" step.
2192 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002193}
2194
2195/// \brief Try a reference initialization that involves calling a conversion
2196/// function.
2197///
2198/// FIXME: look intos DRs 656, 896
2199static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2200 const InitializedEntity &Entity,
2201 const InitializationKind &Kind,
2202 Expr *Initializer,
2203 bool AllowRValues,
2204 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002205 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002206 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2207 QualType T1 = cv1T1.getUnqualifiedType();
2208 QualType cv2T2 = Initializer->getType();
2209 QualType T2 = cv2T2.getUnqualifiedType();
2210
2211 bool DerivedToBase;
2212 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2213 T1, T2, DerivedToBase) &&
2214 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002215 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002216
2217 // Build the candidate set directly in the initialization sequence
2218 // structure, so that it will persist if we fail.
2219 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2220 CandidateSet.clear();
2221
2222 // Determine whether we are allowed to call explicit constructors or
2223 // explicit conversion operators.
2224 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2225
2226 const RecordType *T1RecordType = 0;
2227 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2228 // The type we're converting to is a class type. Enumerate its constructors
2229 // to see if there is a suitable conversion.
2230 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2231
2232 DeclarationName ConstructorName
2233 = S.Context.DeclarationNames.getCXXConstructorName(
2234 S.Context.getCanonicalType(T1).getUnqualifiedType());
2235 DeclContext::lookup_iterator Con, ConEnd;
2236 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2237 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002238 NamedDecl *D = *Con;
2239 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2240
Douglas Gregor20093b42009-12-09 23:02:17 +00002241 // Find the constructor (which may be a template).
2242 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002243 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002244 if (ConstructorTmpl)
2245 Constructor = cast<CXXConstructorDecl>(
2246 ConstructorTmpl->getTemplatedDecl());
2247 else
John McCall9aa472c2010-03-19 07:35:19 +00002248 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002249
2250 if (!Constructor->isInvalidDecl() &&
2251 Constructor->isConvertingConstructor(AllowExplicit)) {
2252 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002253 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002254 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002255 &Initializer, 1, CandidateSet);
2256 else
John McCall9aa472c2010-03-19 07:35:19 +00002257 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002258 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002259 }
2260 }
2261 }
2262
2263 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2264 // The type we're converting from is a class type, enumerate its conversion
2265 // functions.
2266 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2267
2268 // Determine the type we are converting to. If we are allowed to
2269 // convert to an rvalue, take the type that the destination type
2270 // refers to.
2271 QualType ToType = AllowRValues? cv1T1 : DestType;
2272
John McCalleec51cf2010-01-20 00:46:10 +00002273 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002274 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002275 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2276 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002277 NamedDecl *D = *I;
2278 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2279 if (isa<UsingShadowDecl>(D))
2280 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2281
2282 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2283 CXXConversionDecl *Conv;
2284 if (ConvTemplate)
2285 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2286 else
2287 Conv = cast<CXXConversionDecl>(*I);
2288
2289 // If the conversion function doesn't return a reference type,
2290 // it can't be considered for this conversion unless we're allowed to
2291 // consider rvalues.
2292 // FIXME: Do we need to make sure that we only consider conversion
2293 // candidates with reference-compatible results? That might be needed to
2294 // break recursion.
2295 if ((AllowExplicit || !Conv->isExplicit()) &&
2296 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2297 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002298 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002299 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002300 ToType, CandidateSet);
2301 else
John McCall9aa472c2010-03-19 07:35:19 +00002302 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002303 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 }
2305 }
2306 }
2307
2308 SourceLocation DeclLoc = Initializer->getLocStart();
2309
2310 // Perform overload resolution. If it fails, return the failed result.
2311 OverloadCandidateSet::iterator Best;
2312 if (OverloadingResult Result
2313 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2314 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002315
Douglas Gregor20093b42009-12-09 23:02:17 +00002316 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002317
2318 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002319 if (isa<CXXConversionDecl>(Function))
2320 T2 = Function->getResultType();
2321 else
2322 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002323
2324 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002325 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCallb13b7372010-02-01 03:16:54 +00002326 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002327
2328 // Determine whether we need to perform derived-to-base or
2329 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002330 bool NewDerivedToBase = false;
2331 Sema::ReferenceCompareResult NewRefRelationship
2332 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2333 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002334 if (NewRefRelationship == Sema::Ref_Incompatible) {
2335 // If the type we've converted to is not reference-related to the
2336 // type we're looking for, then there is another conversion step
2337 // we need to perform to produce a temporary of the right type
2338 // that we'll be binding to.
2339 ImplicitConversionSequence ICS;
2340 ICS.setStandard();
2341 ICS.Standard = Best->FinalConversion;
2342 T2 = ICS.Standard.getToType(2);
2343 Sequence.AddConversionSequenceStep(ICS, T2);
2344 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002345 Sequence.AddDerivedToBaseCastStep(
2346 S.Context.getQualifiedType(T1,
2347 T2.getNonReferenceType().getQualifiers()),
2348 /*isLValue=*/true);
2349
2350 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2351 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2352
2353 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2354 return OR_Success;
2355}
2356
2357/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2358static void TryReferenceInitialization(Sema &S,
2359 const InitializedEntity &Entity,
2360 const InitializationKind &Kind,
2361 Expr *Initializer,
2362 InitializationSequence &Sequence) {
2363 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2364
Douglas Gregord6542d82009-12-22 15:35:07 +00002365 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002366 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002367 Qualifiers T1Quals;
2368 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002369 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002370 Qualifiers T2Quals;
2371 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002372 SourceLocation DeclLoc = Initializer->getLocStart();
2373
2374 // If the initializer is the address of an overloaded function, try
2375 // to resolve the overloaded function. If all goes well, T2 is the
2376 // type of the resulting function.
2377 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002378 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002379 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2380 T1,
John McCall6bb80172010-03-30 21:47:33 +00002381 false,
2382 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002383 if (!Fn) {
2384 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2385 return;
2386 }
2387
John McCall6bb80172010-03-30 21:47:33 +00002388 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002389 cv2T2 = Fn->getType();
2390 T2 = cv2T2.getUnqualifiedType();
2391 }
2392
2393 // FIXME: Rvalue references
2394 bool ForceRValue = false;
2395
2396 // Compute some basic properties of the types and the initializer.
2397 bool isLValueRef = DestType->isLValueReferenceType();
2398 bool isRValueRef = !isLValueRef;
2399 bool DerivedToBase = false;
2400 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2401 Initializer->isLvalue(S.Context);
2402 Sema::ReferenceCompareResult RefRelationship
2403 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2404
2405 // C++0x [dcl.init.ref]p5:
2406 // A reference to type "cv1 T1" is initialized by an expression of type
2407 // "cv2 T2" as follows:
2408 //
2409 // - If the reference is an lvalue reference and the initializer
2410 // expression
2411 OverloadingResult ConvOvlResult = OR_Success;
2412 if (isLValueRef) {
2413 if (InitLvalue == Expr::LV_Valid &&
2414 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2415 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2416 // reference-compatible with "cv2 T2," or
2417 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002418 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002420 // can occur. However, we do pay attention to whether it is a bit-field
2421 // to decide whether we're actually binding to a temporary created from
2422 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002423 if (DerivedToBase)
2424 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002425 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002426 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002427 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002429 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002430 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002431 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 return;
2433 }
2434
2435 // - has a class type (i.e., T2 is a class type), where T1 is not
2436 // reference-related to T2, and can be implicitly converted to an
2437 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2438 // with "cv3 T3" (this conversion is selected by enumerating the
2439 // applicable conversion functions (13.3.1.6) and choosing the best
2440 // one through overload resolution (13.3)),
2441 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2442 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2443 Initializer,
2444 /*AllowRValues=*/false,
2445 Sequence);
2446 if (ConvOvlResult == OR_Success)
2447 return;
John McCall1d318332010-01-12 00:44:57 +00002448 if (ConvOvlResult != OR_No_Viable_Function) {
2449 Sequence.SetOverloadFailure(
2450 InitializationSequence::FK_ReferenceInitOverloadFailed,
2451 ConvOvlResult);
2452 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002453 }
2454 }
2455
2456 // - Otherwise, the reference shall be an lvalue reference to a
2457 // non-volatile const type (i.e., cv1 shall be const), or the reference
2458 // shall be an rvalue reference and the initializer expression shall
2459 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002460 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002461 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2462 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2463 Sequence.SetOverloadFailure(
2464 InitializationSequence::FK_ReferenceInitOverloadFailed,
2465 ConvOvlResult);
2466 else if (isLValueRef)
2467 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2468 ? (RefRelationship == Sema::Ref_Related
2469 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2470 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2471 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2472 else
2473 Sequence.SetFailed(
2474 InitializationSequence::FK_RValueReferenceBindingToLValue);
2475
2476 return;
2477 }
2478
2479 // - If T1 and T2 are class types and
2480 if (T1->isRecordType() && T2->isRecordType()) {
2481 // - the initializer expression is an rvalue and "cv1 T1" is
2482 // reference-compatible with "cv2 T2", or
2483 if (InitLvalue != Expr::LV_Valid &&
2484 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2485 if (DerivedToBase)
2486 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002487 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002488 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002489 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2491 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2492 return;
2493 }
2494
2495 // - T1 is not reference-related to T2 and the initializer expression
2496 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2497 // conversion is selected by enumerating the applicable conversion
2498 // functions (13.3.1.6) and choosing the best one through overload
2499 // resolution (13.3)),
2500 if (RefRelationship == Sema::Ref_Incompatible) {
2501 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2502 Kind, Initializer,
2503 /*AllowRValues=*/true,
2504 Sequence);
2505 if (ConvOvlResult)
2506 Sequence.SetOverloadFailure(
2507 InitializationSequence::FK_ReferenceInitOverloadFailed,
2508 ConvOvlResult);
2509
2510 return;
2511 }
2512
2513 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2514 return;
2515 }
2516
2517 // - If the initializer expression is an rvalue, with T2 an array type,
2518 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2519 // is bound to the object represented by the rvalue (see 3.10).
2520 // FIXME: How can an array type be reference-compatible with anything?
2521 // Don't we mean the element types of T1 and T2?
2522
2523 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2524 // from the initializer expression using the rules for a non-reference
2525 // copy initialization (8.5). The reference is then bound to the
2526 // temporary. [...]
2527 // Determine whether we are allowed to call explicit constructors or
2528 // explicit conversion operators.
2529 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2530 ImplicitConversionSequence ICS
2531 = S.TryImplicitConversion(Initializer, cv1T1,
2532 /*SuppressUserConversions=*/false, AllowExplicit,
2533 /*ForceRValue=*/false,
2534 /*FIXME:InOverloadResolution=*/false,
2535 /*UserCast=*/Kind.isExplicitCast());
2536
John McCall1d318332010-01-12 00:44:57 +00002537 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002538 // FIXME: Use the conversion function set stored in ICS to turn
2539 // this into an overloading ambiguity diagnostic. However, we need
2540 // to keep that set as an OverloadCandidateSet rather than as some
2541 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002542 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2543 Sequence.SetOverloadFailure(
2544 InitializationSequence::FK_ReferenceInitOverloadFailed,
2545 ConvOvlResult);
2546 else
2547 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002548 return;
2549 }
2550
2551 // [...] If T1 is reference-related to T2, cv1 must be the
2552 // same cv-qualification as, or greater cv-qualification
2553 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002554 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2555 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002556 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002557 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2559 return;
2560 }
2561
2562 // Perform the actual conversion.
2563 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2564 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2565 return;
2566}
2567
2568/// \brief Attempt character array initialization from a string literal
2569/// (C++ [dcl.init.string], C99 6.7.8).
2570static void TryStringLiteralInitialization(Sema &S,
2571 const InitializedEntity &Entity,
2572 const InitializationKind &Kind,
2573 Expr *Initializer,
2574 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002575 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002576 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002577}
2578
Douglas Gregor20093b42009-12-09 23:02:17 +00002579/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2580/// enumerates the constructors of the initialized entity and performs overload
2581/// resolution to select the best.
2582static void TryConstructorInitialization(Sema &S,
2583 const InitializedEntity &Entity,
2584 const InitializationKind &Kind,
2585 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002586 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002587 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002588 if (Kind.getKind() == InitializationKind::IK_Copy)
2589 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2590 else
2591 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002592
2593 // Build the candidate set directly in the initialization sequence
2594 // structure, so that it will persist if we fail.
2595 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2596 CandidateSet.clear();
2597
2598 // Determine whether we are allowed to call explicit constructors or
2599 // explicit conversion operators.
2600 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2601 Kind.getKind() == InitializationKind::IK_Value ||
2602 Kind.getKind() == InitializationKind::IK_Default);
2603
2604 // The type we're converting to is a class type. Enumerate its constructors
2605 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002606 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2607 assert(DestRecordType && "Constructor initialization requires record type");
2608 CXXRecordDecl *DestRecordDecl
2609 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2610
2611 DeclarationName ConstructorName
2612 = S.Context.DeclarationNames.getCXXConstructorName(
2613 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2614 DeclContext::lookup_iterator Con, ConEnd;
2615 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2616 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002617 NamedDecl *D = *Con;
2618 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2619
Douglas Gregor51c56d62009-12-14 20:49:26 +00002620 // Find the constructor (which may be a template).
2621 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002622 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002623 if (ConstructorTmpl)
2624 Constructor = cast<CXXConstructorDecl>(
2625 ConstructorTmpl->getTemplatedDecl());
2626 else
John McCall9aa472c2010-03-19 07:35:19 +00002627 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002628
2629 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002630 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002631 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002632 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002633 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002634 Args, NumArgs, CandidateSet);
2635 else
John McCall9aa472c2010-03-19 07:35:19 +00002636 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002637 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002638 }
2639 }
2640
2641 SourceLocation DeclLoc = Kind.getLocation();
2642
2643 // Perform overload resolution. If it fails, return the failed result.
2644 OverloadCandidateSet::iterator Best;
2645 if (OverloadingResult Result
2646 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2647 Sequence.SetOverloadFailure(
2648 InitializationSequence::FK_ConstructorOverloadFailed,
2649 Result);
2650 return;
2651 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002652
2653 // C++0x [dcl.init]p6:
2654 // If a program calls for the default initialization of an object
2655 // of a const-qualified type T, T shall be a class type with a
2656 // user-provided default constructor.
2657 if (Kind.getKind() == InitializationKind::IK_Default &&
2658 Entity.getType().isConstQualified() &&
2659 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2660 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2661 return;
2662 }
2663
Douglas Gregor51c56d62009-12-14 20:49:26 +00002664 // Add the constructor initialization step. Any cv-qualification conversion is
2665 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002666 if (Kind.getKind() == InitializationKind::IK_Copy) {
John McCall9aa472c2010-03-19 07:35:19 +00002667 Sequence.AddUserConversionStep(Best->Function, Best->FoundDecl, DestType);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002668 } else {
2669 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002670 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002671 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002672 DestType);
2673 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002674}
2675
Douglas Gregor71d17402009-12-15 00:01:57 +00002676/// \brief Attempt value initialization (C++ [dcl.init]p7).
2677static void TryValueInitialization(Sema &S,
2678 const InitializedEntity &Entity,
2679 const InitializationKind &Kind,
2680 InitializationSequence &Sequence) {
2681 // C++ [dcl.init]p5:
2682 //
2683 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002684 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002685
2686 // -- if T is an array type, then each element is value-initialized;
2687 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2688 T = AT->getElementType();
2689
2690 if (const RecordType *RT = T->getAs<RecordType>()) {
2691 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2692 // -- if T is a class type (clause 9) with a user-declared
2693 // constructor (12.1), then the default constructor for T is
2694 // called (and the initialization is ill-formed if T has no
2695 // accessible default constructor);
2696 //
2697 // FIXME: we really want to refer to a single subobject of the array,
2698 // but Entity doesn't have a way to capture that (yet).
2699 if (ClassDecl->hasUserDeclaredConstructor())
2700 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2701
Douglas Gregor16006c92009-12-16 18:50:27 +00002702 // -- if T is a (possibly cv-qualified) non-union class type
2703 // without a user-provided constructor, then the object is
2704 // zero-initialized and, if T’s implicitly-declared default
2705 // constructor is non-trivial, that constructor is called.
2706 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2707 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2708 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002709 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002710 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2711 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002712 }
2713 }
2714
Douglas Gregord6542d82009-12-22 15:35:07 +00002715 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002716 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2717}
2718
Douglas Gregor99a2e602009-12-16 01:38:02 +00002719/// \brief Attempt default initialization (C++ [dcl.init]p6).
2720static void TryDefaultInitialization(Sema &S,
2721 const InitializedEntity &Entity,
2722 const InitializationKind &Kind,
2723 InitializationSequence &Sequence) {
2724 assert(Kind.getKind() == InitializationKind::IK_Default);
2725
2726 // C++ [dcl.init]p6:
2727 // To default-initialize an object of type T means:
2728 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002729 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002730 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2731 DestType = Array->getElementType();
2732
2733 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2734 // constructor for T is called (and the initialization is ill-formed if
2735 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002736 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002737 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2738 Sequence);
2739 }
2740
2741 // - otherwise, no initialization is performed.
2742 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2743
2744 // If a program calls for the default initialization of an object of
2745 // a const-qualified type T, T shall be a class type with a user-provided
2746 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002747 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002748 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2749}
2750
Douglas Gregor20093b42009-12-09 23:02:17 +00002751/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2752/// which enumerates all conversion functions and performs overload resolution
2753/// to select the best.
2754static void TryUserDefinedConversion(Sema &S,
2755 const InitializedEntity &Entity,
2756 const InitializationKind &Kind,
2757 Expr *Initializer,
2758 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002759 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2760
Douglas Gregord6542d82009-12-22 15:35:07 +00002761 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002762 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2763 QualType SourceType = Initializer->getType();
2764 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2765 "Must have a class type to perform a user-defined conversion");
2766
2767 // Build the candidate set directly in the initialization sequence
2768 // structure, so that it will persist if we fail.
2769 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2770 CandidateSet.clear();
2771
2772 // Determine whether we are allowed to call explicit constructors or
2773 // explicit conversion operators.
2774 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2775
2776 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2777 // The type we're converting to is a class type. Enumerate its constructors
2778 // to see if there is a suitable conversion.
2779 CXXRecordDecl *DestRecordDecl
2780 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2781
2782 DeclarationName ConstructorName
2783 = S.Context.DeclarationNames.getCXXConstructorName(
2784 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2785 DeclContext::lookup_iterator Con, ConEnd;
2786 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2787 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002788 NamedDecl *D = *Con;
2789 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2790
Douglas Gregor4a520a22009-12-14 17:27:33 +00002791 // Find the constructor (which may be a template).
2792 CXXConstructorDecl *Constructor = 0;
2793 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002794 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002795 if (ConstructorTmpl)
2796 Constructor = cast<CXXConstructorDecl>(
2797 ConstructorTmpl->getTemplatedDecl());
2798 else
John McCall9aa472c2010-03-19 07:35:19 +00002799 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002800
2801 if (!Constructor->isInvalidDecl() &&
2802 Constructor->isConvertingConstructor(AllowExplicit)) {
2803 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002804 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002805 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002806 &Initializer, 1, CandidateSet);
2807 else
John McCall9aa472c2010-03-19 07:35:19 +00002808 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002809 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002810 }
2811 }
2812 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002813
2814 SourceLocation DeclLoc = Initializer->getLocStart();
2815
Douglas Gregor4a520a22009-12-14 17:27:33 +00002816 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2817 // The type we're converting from is a class type, enumerate its conversion
2818 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002819
Eli Friedman33c2da92009-12-20 22:12:03 +00002820 // We can only enumerate the conversion functions for a complete type; if
2821 // the type isn't complete, simply skip this step.
2822 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2823 CXXRecordDecl *SourceRecordDecl
2824 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002825
John McCalleec51cf2010-01-20 00:46:10 +00002826 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002827 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002828 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002829 E = Conversions->end();
2830 I != E; ++I) {
2831 NamedDecl *D = *I;
2832 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2833 if (isa<UsingShadowDecl>(D))
2834 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2835
2836 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2837 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002838 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002839 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002840 else
John McCall32daa422010-03-31 01:36:47 +00002841 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002842
2843 if (AllowExplicit || !Conv->isExplicit()) {
2844 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002845 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002846 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002847 CandidateSet);
2848 else
John McCall9aa472c2010-03-19 07:35:19 +00002849 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002850 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002851 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002852 }
2853 }
2854 }
2855
Douglas Gregor4a520a22009-12-14 17:27:33 +00002856 // Perform overload resolution. If it fails, return the failed result.
2857 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002858 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002859 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2860 Sequence.SetOverloadFailure(
2861 InitializationSequence::FK_UserConversionOverloadFailed,
2862 Result);
2863 return;
2864 }
John McCall1d318332010-01-12 00:44:57 +00002865
Douglas Gregor4a520a22009-12-14 17:27:33 +00002866 FunctionDecl *Function = Best->Function;
2867
2868 if (isa<CXXConstructorDecl>(Function)) {
2869 // Add the user-defined conversion step. Any cv-qualification conversion is
2870 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002871 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002872 return;
2873 }
2874
2875 // Add the user-defined conversion step that calls the conversion function.
2876 QualType ConvType = Function->getResultType().getNonReferenceType();
John McCall9aa472c2010-03-19 07:35:19 +00002877 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002878
2879 // If the conversion following the call to the conversion function is
2880 // interesting, add it as a separate step.
2881 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2882 Best->FinalConversion.Third) {
2883 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002884 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002885 ICS.Standard = Best->FinalConversion;
2886 Sequence.AddConversionSequenceStep(ICS, DestType);
2887 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002888}
2889
2890/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2891/// non-class type to another.
2892static void TryImplicitConversion(Sema &S,
2893 const InitializedEntity &Entity,
2894 const InitializationKind &Kind,
2895 Expr *Initializer,
2896 InitializationSequence &Sequence) {
2897 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002898 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002899 /*SuppressUserConversions=*/true,
2900 /*AllowExplicit=*/false,
2901 /*ForceRValue=*/false,
2902 /*FIXME:InOverloadResolution=*/false,
2903 /*UserCast=*/Kind.isExplicitCast());
2904
John McCall1d318332010-01-12 00:44:57 +00002905 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002906 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2907 return;
2908 }
2909
Douglas Gregord6542d82009-12-22 15:35:07 +00002910 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002911}
2912
2913InitializationSequence::InitializationSequence(Sema &S,
2914 const InitializedEntity &Entity,
2915 const InitializationKind &Kind,
2916 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002917 unsigned NumArgs)
2918 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002919 ASTContext &Context = S.Context;
2920
2921 // C++0x [dcl.init]p16:
2922 // The semantics of initializers are as follows. The destination type is
2923 // the type of the object or reference being initialized and the source
2924 // type is the type of the initializer expression. The source type is not
2925 // defined when the initializer is a braced-init-list or when it is a
2926 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002927 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002928
2929 if (DestType->isDependentType() ||
2930 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2931 SequenceKind = DependentSequence;
2932 return;
2933 }
2934
2935 QualType SourceType;
2936 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002937 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002938 Initializer = Args[0];
2939 if (!isa<InitListExpr>(Initializer))
2940 SourceType = Initializer->getType();
2941 }
2942
2943 // - If the initializer is a braced-init-list, the object is
2944 // list-initialized (8.5.4).
2945 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2946 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002947 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002948 }
2949
2950 // - If the destination type is a reference type, see 8.5.3.
2951 if (DestType->isReferenceType()) {
2952 // C++0x [dcl.init.ref]p1:
2953 // A variable declared to be a T& or T&&, that is, "reference to type T"
2954 // (8.3.2), shall be initialized by an object, or function, of type T or
2955 // by an object that can be converted into a T.
2956 // (Therefore, multiple arguments are not permitted.)
2957 if (NumArgs != 1)
2958 SetFailed(FK_TooManyInitsForReference);
2959 else
2960 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2961 return;
2962 }
2963
2964 // - If the destination type is an array of characters, an array of
2965 // char16_t, an array of char32_t, or an array of wchar_t, and the
2966 // initializer is a string literal, see 8.5.2.
2967 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2968 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2969 return;
2970 }
2971
2972 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002973 if (Kind.getKind() == InitializationKind::IK_Value ||
2974 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002975 TryValueInitialization(S, Entity, Kind, *this);
2976 return;
2977 }
2978
Douglas Gregor99a2e602009-12-16 01:38:02 +00002979 // Handle default initialization.
2980 if (Kind.getKind() == InitializationKind::IK_Default){
2981 TryDefaultInitialization(S, Entity, Kind, *this);
2982 return;
2983 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002984
Douglas Gregor20093b42009-12-09 23:02:17 +00002985 // - Otherwise, if the destination type is an array, the program is
2986 // ill-formed.
2987 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2988 if (AT->getElementType()->isAnyCharacterType())
2989 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2990 else
2991 SetFailed(FK_ArrayNeedsInitList);
2992
2993 return;
2994 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002995
2996 // Handle initialization in C
2997 if (!S.getLangOptions().CPlusPlus) {
2998 setSequenceKind(CAssignment);
2999 AddCAssignmentStep(DestType);
3000 return;
3001 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003002
3003 // - If the destination type is a (possibly cv-qualified) class type:
3004 if (DestType->isRecordType()) {
3005 // - If the initialization is direct-initialization, or if it is
3006 // copy-initialization where the cv-unqualified version of the
3007 // source type is the same class as, or a derived class of, the
3008 // class of the destination, constructors are considered. [...]
3009 if (Kind.getKind() == InitializationKind::IK_Direct ||
3010 (Kind.getKind() == InitializationKind::IK_Copy &&
3011 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3012 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003013 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003014 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003015 // - Otherwise (i.e., for the remaining copy-initialization cases),
3016 // user-defined conversion sequences that can convert from the source
3017 // type to the destination type or (when a conversion function is
3018 // used) to a derived class thereof are enumerated as described in
3019 // 13.3.1.4, and the best one is chosen through overload resolution
3020 // (13.3).
3021 else
3022 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3023 return;
3024 }
3025
Douglas Gregor99a2e602009-12-16 01:38:02 +00003026 if (NumArgs > 1) {
3027 SetFailed(FK_TooManyInitsForScalar);
3028 return;
3029 }
3030 assert(NumArgs == 1 && "Zero-argument case handled above");
3031
Douglas Gregor20093b42009-12-09 23:02:17 +00003032 // - Otherwise, if the source type is a (possibly cv-qualified) class
3033 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003034 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003035 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3036 return;
3037 }
3038
3039 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003040 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003041 // conversions (Clause 4) will be used, if necessary, to convert the
3042 // initializer expression to the cv-unqualified version of the
3043 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003044 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003045 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3046}
3047
3048InitializationSequence::~InitializationSequence() {
3049 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3050 StepEnd = Steps.end();
3051 Step != StepEnd; ++Step)
3052 Step->Destroy();
3053}
3054
3055//===----------------------------------------------------------------------===//
3056// Perform initialization
3057//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003058static Sema::AssignmentAction
3059getAssignmentAction(const InitializedEntity &Entity) {
3060 switch(Entity.getKind()) {
3061 case InitializedEntity::EK_Variable:
3062 case InitializedEntity::EK_New:
3063 return Sema::AA_Initializing;
3064
3065 case InitializedEntity::EK_Parameter:
3066 // FIXME: Can we tell when we're sending vs. passing?
3067 return Sema::AA_Passing;
3068
3069 case InitializedEntity::EK_Result:
3070 return Sema::AA_Returning;
3071
3072 case InitializedEntity::EK_Exception:
3073 case InitializedEntity::EK_Base:
3074 llvm_unreachable("No assignment action for C++-specific initialization");
3075 break;
3076
3077 case InitializedEntity::EK_Temporary:
3078 // FIXME: Can we tell apart casting vs. converting?
3079 return Sema::AA_Casting;
3080
3081 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003082 case InitializedEntity::EK_ArrayElement:
3083 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003084 return Sema::AA_Initializing;
3085 }
3086
3087 return Sema::AA_Converting;
3088}
3089
3090static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3091 bool IsCopy) {
3092 switch (Entity.getKind()) {
3093 case InitializedEntity::EK_Result:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003094 case InitializedEntity::EK_ArrayElement:
3095 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003096 return !IsCopy;
3097
3098 case InitializedEntity::EK_New:
3099 case InitializedEntity::EK_Variable:
3100 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003101 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003102 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003103 return false;
3104
3105 case InitializedEntity::EK_Parameter:
3106 case InitializedEntity::EK_Temporary:
3107 return true;
3108 }
3109
3110 llvm_unreachable("missed an InitializedEntity kind?");
3111}
3112
3113/// \brief If we need to perform an additional copy of the initialized object
3114/// for this kind of entity (e.g., the result of a function or an object being
3115/// thrown), make the copy.
3116static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3117 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003118 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003119 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003120 Expr *CurInitExpr = (Expr *)CurInit.get();
3121
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003122 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003123
3124 switch (Entity.getKind()) {
3125 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003126 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003127 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003128 Loc = Entity.getReturnLoc();
3129 break;
3130
3131 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003132 Loc = Entity.getThrowLoc();
3133 break;
3134
3135 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003136 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003137 Kind.getKind() != InitializationKind::IK_Copy)
3138 return move(CurInit);
3139 Loc = Entity.getDecl()->getLocation();
3140 break;
3141
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003142 case InitializedEntity::EK_ArrayElement:
3143 case InitializedEntity::EK_Member:
3144 if (Entity.getType()->isReferenceType() ||
3145 Kind.getKind() != InitializationKind::IK_Copy)
3146 return move(CurInit);
3147 Loc = CurInitExpr->getLocStart();
3148 break;
3149
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003150 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003151 // FIXME: Do we need this initialization for a parameter?
3152 return move(CurInit);
3153
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003154 case InitializedEntity::EK_New:
3155 case InitializedEntity::EK_Temporary:
3156 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003157 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003158 // We don't need to copy for any of these initialized entities.
3159 return move(CurInit);
3160 }
3161
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003162 CXXRecordDecl *Class = 0;
3163 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3164 Class = cast<CXXRecordDecl>(Record->getDecl());
3165 if (!Class)
3166 return move(CurInit);
3167
3168 // Perform overload resolution using the class's copy constructors.
3169 DeclarationName ConstructorName
3170 = S.Context.DeclarationNames.getCXXConstructorName(
3171 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3172 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003173 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003174 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3175 Con != ConEnd; ++Con) {
3176 // Find the constructor (which may be a template).
3177 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3178 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003179 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003180 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003181
3182 DeclAccessPair FoundDecl
3183 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3184 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003185 &CurInitExpr, 1, CandidateSet);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003186 }
3187
3188 OverloadCandidateSet::iterator Best;
3189 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3190 case OR_Success:
3191 break;
3192
3193 case OR_No_Viable_Function:
3194 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003195 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003196 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003197 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3198 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003199 return S.ExprError();
3200
3201 case OR_Ambiguous:
3202 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003203 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003204 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003205 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3206 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003207 return S.ExprError();
3208
3209 case OR_Deleted:
3210 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003211 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003212 << CurInitExpr->getSourceRange();
3213 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3214 << Best->Function->isDeleted();
3215 return S.ExprError();
3216 }
3217
John McCall9aa472c2010-03-19 07:35:19 +00003218 S.CheckConstructorAccess(Loc,
3219 cast<CXXConstructorDecl>(Best->Function),
3220 Best->FoundDecl.getAccess());
3221
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003222 CurInit.release();
3223 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3224 cast<CXXConstructorDecl>(Best->Function),
3225 /*Elidable=*/true,
3226 Sema::MultiExprArg(S,
3227 (void**)&CurInitExpr, 1));
3228}
Douglas Gregor20093b42009-12-09 23:02:17 +00003229
3230Action::OwningExprResult
3231InitializationSequence::Perform(Sema &S,
3232 const InitializedEntity &Entity,
3233 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003234 Action::MultiExprArg Args,
3235 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003236 if (SequenceKind == FailedSequence) {
3237 unsigned NumArgs = Args.size();
3238 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3239 return S.ExprError();
3240 }
3241
3242 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003243 // If the declaration is a non-dependent, incomplete array type
3244 // that has an initializer, then its type will be completed once
3245 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003246 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003247 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003248 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003249 if (const IncompleteArrayType *ArrayT
3250 = S.Context.getAsIncompleteArrayType(DeclType)) {
3251 // FIXME: We don't currently have the ability to accurately
3252 // compute the length of an initializer list without
3253 // performing full type-checking of the initializer list
3254 // (since we have to determine where braces are implicitly
3255 // introduced and such). So, we fall back to making the array
3256 // type a dependently-sized array type with no specified
3257 // bound.
3258 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3259 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003260
Douglas Gregord87b61f2009-12-10 17:56:55 +00003261 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003262 if (DeclaratorDecl *DD = Entity.getDecl()) {
3263 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3264 TypeLoc TL = TInfo->getTypeLoc();
3265 if (IncompleteArrayTypeLoc *ArrayLoc
3266 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3267 Brackets = ArrayLoc->getBracketsRange();
3268 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003269 }
3270
3271 *ResultType
3272 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3273 /*NumElts=*/0,
3274 ArrayT->getSizeModifier(),
3275 ArrayT->getIndexTypeCVRQualifiers(),
3276 Brackets);
3277 }
3278
3279 }
3280 }
3281
Eli Friedman08544622009-12-22 02:35:53 +00003282 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003283 return Sema::OwningExprResult(S, Args.release()[0]);
3284
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003285 if (Args.size() == 0)
3286 return S.Owned((Expr *)0);
3287
Douglas Gregor20093b42009-12-09 23:02:17 +00003288 unsigned NumArgs = Args.size();
3289 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3290 SourceLocation(),
3291 (Expr **)Args.release(),
3292 NumArgs,
3293 SourceLocation()));
3294 }
3295
Douglas Gregor99a2e602009-12-16 01:38:02 +00003296 if (SequenceKind == NoInitialization)
3297 return S.Owned((Expr *)0);
3298
Douglas Gregord6542d82009-12-22 15:35:07 +00003299 QualType DestType = Entity.getType().getNonReferenceType();
3300 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003301 // the same as Entity.getDecl()->getType() in cases involving type merging,
3302 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003303 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003304 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003305 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003306
Douglas Gregor99a2e602009-12-16 01:38:02 +00003307 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3308
3309 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3310
3311 // For initialization steps that start with a single initializer,
3312 // grab the only argument out the Args and place it into the "current"
3313 // initializer.
3314 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003315 case SK_ResolveAddressOfOverloadedFunction:
3316 case SK_CastDerivedToBaseRValue:
3317 case SK_CastDerivedToBaseLValue:
3318 case SK_BindReference:
3319 case SK_BindReferenceToTemporary:
3320 case SK_UserConversion:
3321 case SK_QualificationConversionLValue:
3322 case SK_QualificationConversionRValue:
3323 case SK_ConversionSequence:
3324 case SK_ListInitialization:
3325 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003326 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003327 assert(Args.size() == 1);
3328 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3329 if (CurInit.isInvalid())
3330 return S.ExprError();
3331 break;
3332
3333 case SK_ConstructorInitialization:
3334 case SK_ZeroInitialization:
3335 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003336 }
3337
3338 // Walk through the computed steps for the initialization sequence,
3339 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003340 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003341 for (step_iterator Step = step_begin(), StepEnd = step_end();
3342 Step != StepEnd; ++Step) {
3343 if (CurInit.isInvalid())
3344 return S.ExprError();
3345
3346 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003347 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003348
3349 switch (Step->Kind) {
3350 case SK_ResolveAddressOfOverloadedFunction:
3351 // Overload resolution determined which function invoke; update the
3352 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003353 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb13b7372010-02-01 03:16:54 +00003354 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003355 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003356 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003357 break;
3358
3359 case SK_CastDerivedToBaseRValue:
3360 case SK_CastDerivedToBaseLValue: {
3361 // We have a derived-to-base cast that produces either an rvalue or an
3362 // lvalue. Perform that cast.
3363
3364 // Casts to inaccessible base classes are allowed with C-style casts.
3365 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3366 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3367 CurInitExpr->getLocStart(),
3368 CurInitExpr->getSourceRange(),
3369 IgnoreBaseAccess))
3370 return S.ExprError();
3371
3372 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3373 CastExpr::CK_DerivedToBase,
3374 (Expr*)CurInit.release(),
3375 Step->Kind == SK_CastDerivedToBaseLValue));
3376 break;
3377 }
3378
3379 case SK_BindReference:
3380 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3381 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3382 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003383 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 << BitField->getDeclName()
3385 << CurInitExpr->getSourceRange();
3386 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3387 return S.ExprError();
3388 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003389
Anders Carlsson09380262010-01-31 17:18:49 +00003390 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003391 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003392 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3393 << Entity.getType().isVolatileQualified()
3394 << CurInitExpr->getSourceRange();
3395 return S.ExprError();
3396 }
3397
Douglas Gregor20093b42009-12-09 23:02:17 +00003398 // Reference binding does not have any corresponding ASTs.
3399
3400 // Check exception specifications
3401 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3402 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003403
Douglas Gregor20093b42009-12-09 23:02:17 +00003404 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003405
Douglas Gregor20093b42009-12-09 23:02:17 +00003406 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003407 // Reference binding does not have any corresponding ASTs.
3408
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 // Check exception specifications
3410 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3411 return S.ExprError();
3412
Douglas Gregor20093b42009-12-09 23:02:17 +00003413 break;
3414
3415 case SK_UserConversion: {
3416 // We have a user-defined conversion that invokes either a constructor
3417 // or a conversion function.
3418 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003419 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003420 FunctionDecl *Fn = Step->Function.Function;
3421 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003422 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003423 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 // Build a call to the selected constructor.
3425 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3426 SourceLocation Loc = CurInitExpr->getLocStart();
3427 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003428
Douglas Gregor20093b42009-12-09 23:02:17 +00003429 // Determine the arguments required to actually perform the constructor
3430 // call.
3431 if (S.CompleteConstructorCall(Constructor,
3432 Sema::MultiExprArg(S,
3433 (void **)&CurInitExpr,
3434 1),
3435 Loc, ConstructorArgs))
3436 return S.ExprError();
3437
3438 // Build the an expression that constructs a temporary.
3439 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3440 move_arg(ConstructorArgs));
3441 if (CurInit.isInvalid())
3442 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003443
John McCall9aa472c2010-03-19 07:35:19 +00003444 S.CheckConstructorAccess(Kind.getLocation(), Constructor,
3445 FoundFn.getAccess());
Douglas Gregor20093b42009-12-09 23:02:17 +00003446
3447 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003448 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3449 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3450 S.IsDerivedFrom(SourceType, Class))
3451 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003452 } else {
3453 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003454 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003455 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003456 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003457 FoundFn);
John McCallb13b7372010-02-01 03:16:54 +00003458
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 // FIXME: Should we move this initialization into a separate
3460 // derived-to-base conversion? I believe the answer is "no", because
3461 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003462 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003463 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 return S.ExprError();
3465
3466 // Do a little dance to make sure that CurInit has the proper
3467 // pointer.
3468 CurInit.release();
3469
3470 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003471 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3472 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 if (CurInit.isInvalid() || !CurInit.get())
3474 return S.ExprError();
3475
3476 CastKind = CastExpr::CK_UserDefinedConversion;
3477 }
3478
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003479 if (shouldBindAsTemporary(Entity, IsCopy))
3480 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3481
Douglas Gregor20093b42009-12-09 23:02:17 +00003482 CurInitExpr = CurInit.takeAs<Expr>();
3483 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3484 CastKind,
3485 CurInitExpr,
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003486 IsLvalue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003487
3488 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003489 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003490 break;
3491 }
3492
3493 case SK_QualificationConversionLValue:
3494 case SK_QualificationConversionRValue:
3495 // Perform a qualification conversion; these can never go wrong.
3496 S.ImpCastExprToType(CurInitExpr, Step->Type,
3497 CastExpr::CK_NoOp,
3498 Step->Kind == SK_QualificationConversionLValue);
3499 CurInit.release();
3500 CurInit = S.Owned(CurInitExpr);
3501 break;
3502
3503 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003504 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003505 false, false, *Step->ICS))
3506 return S.ExprError();
3507
3508 CurInit.release();
3509 CurInit = S.Owned(CurInitExpr);
3510 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003511
3512 case SK_ListInitialization: {
3513 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3514 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003515 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003516 return S.ExprError();
3517
3518 CurInit.release();
3519 CurInit = S.Owned(InitList);
3520 break;
3521 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003522
3523 case SK_ConstructorInitialization: {
3524 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003525 = cast<CXXConstructorDecl>(Step->Function.Function);
John McCallb13b7372010-02-01 03:16:54 +00003526
Douglas Gregor51c56d62009-12-14 20:49:26 +00003527 // Build a call to the selected constructor.
3528 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3529 SourceLocation Loc = Kind.getLocation();
3530
3531 // Determine the arguments required to actually perform the constructor
3532 // call.
3533 if (S.CompleteConstructorCall(Constructor, move(Args),
3534 Loc, ConstructorArgs))
3535 return S.ExprError();
3536
3537 // Build the an expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003538 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3539 (Kind.getKind() == InitializationKind::IK_Direct ||
3540 Kind.getKind() == InitializationKind::IK_Value)) {
3541 // An explicitly-constructed temporary, e.g., X(1, 2).
3542 unsigned NumExprs = ConstructorArgs.size();
3543 Expr **Exprs = (Expr **)ConstructorArgs.take();
3544 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3545 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3546 Constructor,
3547 Entity.getType(),
3548 Kind.getLocation(),
3549 Exprs,
3550 NumExprs,
3551 Kind.getParenRange().getEnd()));
3552 } else
3553 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3554 Constructor,
3555 move_arg(ConstructorArgs),
3556 ConstructorInitRequiresZeroInit,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003557 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003558 if (CurInit.isInvalid())
3559 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003560
3561 // Only check access if all of that succeeded.
John McCall9aa472c2010-03-19 07:35:19 +00003562 S.CheckConstructorAccess(Loc, Constructor,
3563 Step->Function.FoundDecl.getAccess());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003564
3565 bool Elidable
3566 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3567 if (shouldBindAsTemporary(Entity, Elidable))
3568 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3569
3570 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003571 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003572 break;
3573 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003574
3575 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003576 step_iterator NextStep = Step;
3577 ++NextStep;
3578 if (NextStep != StepEnd &&
3579 NextStep->Kind == SK_ConstructorInitialization) {
3580 // The need for zero-initialization is recorded directly into
3581 // the call to the object's constructor within the next step.
3582 ConstructorInitRequiresZeroInit = true;
3583 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3584 S.getLangOptions().CPlusPlus &&
3585 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003586 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3587 Kind.getRange().getBegin(),
3588 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003589 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003590 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003591 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003592 break;
3593 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003594
3595 case SK_CAssignment: {
3596 QualType SourceType = CurInitExpr->getType();
3597 Sema::AssignConvertType ConvTy =
3598 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003599
3600 // If this is a call, allow conversion to a transparent union.
3601 if (ConvTy != Sema::Compatible &&
3602 Entity.getKind() == InitializedEntity::EK_Parameter &&
3603 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3604 == Sema::Compatible)
3605 ConvTy = Sema::Compatible;
3606
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003607 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3608 Step->Type, SourceType,
3609 CurInitExpr, getAssignmentAction(Entity)))
3610 return S.ExprError();
3611
3612 CurInit.release();
3613 CurInit = S.Owned(CurInitExpr);
3614 break;
3615 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003616
3617 case SK_StringInit: {
3618 QualType Ty = Step->Type;
3619 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3620 break;
3621 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003622 }
3623 }
3624
3625 return move(CurInit);
3626}
3627
3628//===----------------------------------------------------------------------===//
3629// Diagnose initialization failures
3630//===----------------------------------------------------------------------===//
3631bool InitializationSequence::Diagnose(Sema &S,
3632 const InitializedEntity &Entity,
3633 const InitializationKind &Kind,
3634 Expr **Args, unsigned NumArgs) {
3635 if (SequenceKind != FailedSequence)
3636 return false;
3637
Douglas Gregord6542d82009-12-22 15:35:07 +00003638 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 switch (Failure) {
3640 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003641 // FIXME: Customize for the initialized entity?
3642 if (NumArgs == 0)
3643 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3644 << DestType.getNonReferenceType();
3645 else // FIXME: diagnostic below could be better!
3646 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3647 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003648 break;
3649
3650 case FK_ArrayNeedsInitList:
3651 case FK_ArrayNeedsInitListOrStringLiteral:
3652 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3653 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3654 break;
3655
John McCall6bb80172010-03-30 21:47:33 +00003656 case FK_AddressOfOverloadFailed: {
3657 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 S.ResolveAddressOfOverloadedFunction(Args[0],
3659 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003660 true,
3661 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003662 break;
John McCall6bb80172010-03-30 21:47:33 +00003663 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003664
3665 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003666 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003667 switch (FailedOverloadResult) {
3668 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003669 if (Failure == FK_UserConversionOverloadFailed)
3670 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3671 << Args[0]->getType() << DestType
3672 << Args[0]->getSourceRange();
3673 else
3674 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3675 << DestType << Args[0]->getType()
3676 << Args[0]->getSourceRange();
3677
John McCallcbce6062010-01-12 07:18:19 +00003678 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3679 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003680 break;
3681
3682 case OR_No_Viable_Function:
3683 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3684 << Args[0]->getType() << DestType.getNonReferenceType()
3685 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003686 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3687 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 break;
3689
3690 case OR_Deleted: {
3691 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3692 << Args[0]->getType() << DestType.getNonReferenceType()
3693 << Args[0]->getSourceRange();
3694 OverloadCandidateSet::iterator Best;
3695 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3696 Kind.getLocation(),
3697 Best);
3698 if (Ovl == OR_Deleted) {
3699 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3700 << Best->Function->isDeleted();
3701 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003702 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003703 }
3704 break;
3705 }
3706
3707 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003708 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003709 break;
3710 }
3711 break;
3712
3713 case FK_NonConstLValueReferenceBindingToTemporary:
3714 case FK_NonConstLValueReferenceBindingToUnrelated:
3715 S.Diag(Kind.getLocation(),
3716 Failure == FK_NonConstLValueReferenceBindingToTemporary
3717 ? diag::err_lvalue_reference_bind_to_temporary
3718 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003719 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003720 << DestType.getNonReferenceType()
3721 << Args[0]->getType()
3722 << Args[0]->getSourceRange();
3723 break;
3724
3725 case FK_RValueReferenceBindingToLValue:
3726 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3727 << Args[0]->getSourceRange();
3728 break;
3729
3730 case FK_ReferenceInitDropsQualifiers:
3731 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3732 << DestType.getNonReferenceType()
3733 << Args[0]->getType()
3734 << Args[0]->getSourceRange();
3735 break;
3736
3737 case FK_ReferenceInitFailed:
3738 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3739 << DestType.getNonReferenceType()
3740 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3741 << Args[0]->getType()
3742 << Args[0]->getSourceRange();
3743 break;
3744
3745 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003746 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3747 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003748 << DestType
3749 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3750 << Args[0]->getType()
3751 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003752 break;
3753
3754 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003755 SourceRange R;
3756
3757 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3758 R = SourceRange(InitList->getInit(1)->getLocStart(),
3759 InitList->getLocEnd());
3760 else
3761 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003762
3763 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003764 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003765 break;
3766 }
3767
3768 case FK_ReferenceBindingToInitList:
3769 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3770 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3771 break;
3772
3773 case FK_InitListBadDestinationType:
3774 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3775 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3776 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003777
3778 case FK_ConstructorOverloadFailed: {
3779 SourceRange ArgsRange;
3780 if (NumArgs)
3781 ArgsRange = SourceRange(Args[0]->getLocStart(),
3782 Args[NumArgs - 1]->getLocEnd());
3783
3784 // FIXME: Using "DestType" for the entity we're printing is probably
3785 // bad.
3786 switch (FailedOverloadResult) {
3787 case OR_Ambiguous:
3788 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3789 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003790 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003791 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003792 break;
3793
3794 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003795 if (Kind.getKind() == InitializationKind::IK_Default &&
3796 (Entity.getKind() == InitializedEntity::EK_Base ||
3797 Entity.getKind() == InitializedEntity::EK_Member) &&
3798 isa<CXXConstructorDecl>(S.CurContext)) {
3799 // This is implicit default initialization of a member or
3800 // base within a constructor. If no viable function was
3801 // found, notify the user that she needs to explicitly
3802 // initialize this base/member.
3803 CXXConstructorDecl *Constructor
3804 = cast<CXXConstructorDecl>(S.CurContext);
3805 if (Entity.getKind() == InitializedEntity::EK_Base) {
3806 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3807 << Constructor->isImplicit()
3808 << S.Context.getTypeDeclType(Constructor->getParent())
3809 << /*base=*/0
3810 << Entity.getType();
3811
3812 RecordDecl *BaseDecl
3813 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3814 ->getDecl();
3815 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3816 << S.Context.getTagDeclType(BaseDecl);
3817 } else {
3818 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3819 << Constructor->isImplicit()
3820 << S.Context.getTypeDeclType(Constructor->getParent())
3821 << /*member=*/1
3822 << Entity.getName();
3823 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3824
3825 if (const RecordType *Record
3826 = Entity.getType()->getAs<RecordType>())
3827 S.Diag(Record->getDecl()->getLocation(),
3828 diag::note_previous_decl)
3829 << S.Context.getTagDeclType(Record->getDecl());
3830 }
3831 break;
3832 }
3833
Douglas Gregor51c56d62009-12-14 20:49:26 +00003834 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3835 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003836 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3837 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003838 break;
3839
3840 case OR_Deleted: {
3841 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3842 << true << DestType << ArgsRange;
3843 OverloadCandidateSet::iterator Best;
3844 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3845 Kind.getLocation(),
3846 Best);
3847 if (Ovl == OR_Deleted) {
3848 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3849 << Best->Function->isDeleted();
3850 } else {
3851 llvm_unreachable("Inconsistent overload resolution?");
3852 }
3853 break;
3854 }
3855
3856 case OR_Success:
3857 llvm_unreachable("Conversion did not fail!");
3858 break;
3859 }
3860 break;
3861 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003862
3863 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003864 if (Entity.getKind() == InitializedEntity::EK_Member &&
3865 isa<CXXConstructorDecl>(S.CurContext)) {
3866 // This is implicit default-initialization of a const member in
3867 // a constructor. Complain that it needs to be explicitly
3868 // initialized.
3869 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3870 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3871 << Constructor->isImplicit()
3872 << S.Context.getTypeDeclType(Constructor->getParent())
3873 << /*const=*/1
3874 << Entity.getName();
3875 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3876 << Entity.getName();
3877 } else {
3878 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3879 << DestType << (bool)DestType->getAs<RecordType>();
3880 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003881 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003882 }
3883
3884 return true;
3885}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003886
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003887void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3888 switch (SequenceKind) {
3889 case FailedSequence: {
3890 OS << "Failed sequence: ";
3891 switch (Failure) {
3892 case FK_TooManyInitsForReference:
3893 OS << "too many initializers for reference";
3894 break;
3895
3896 case FK_ArrayNeedsInitList:
3897 OS << "array requires initializer list";
3898 break;
3899
3900 case FK_ArrayNeedsInitListOrStringLiteral:
3901 OS << "array requires initializer list or string literal";
3902 break;
3903
3904 case FK_AddressOfOverloadFailed:
3905 OS << "address of overloaded function failed";
3906 break;
3907
3908 case FK_ReferenceInitOverloadFailed:
3909 OS << "overload resolution for reference initialization failed";
3910 break;
3911
3912 case FK_NonConstLValueReferenceBindingToTemporary:
3913 OS << "non-const lvalue reference bound to temporary";
3914 break;
3915
3916 case FK_NonConstLValueReferenceBindingToUnrelated:
3917 OS << "non-const lvalue reference bound to unrelated type";
3918 break;
3919
3920 case FK_RValueReferenceBindingToLValue:
3921 OS << "rvalue reference bound to an lvalue";
3922 break;
3923
3924 case FK_ReferenceInitDropsQualifiers:
3925 OS << "reference initialization drops qualifiers";
3926 break;
3927
3928 case FK_ReferenceInitFailed:
3929 OS << "reference initialization failed";
3930 break;
3931
3932 case FK_ConversionFailed:
3933 OS << "conversion failed";
3934 break;
3935
3936 case FK_TooManyInitsForScalar:
3937 OS << "too many initializers for scalar";
3938 break;
3939
3940 case FK_ReferenceBindingToInitList:
3941 OS << "referencing binding to initializer list";
3942 break;
3943
3944 case FK_InitListBadDestinationType:
3945 OS << "initializer list for non-aggregate, non-scalar type";
3946 break;
3947
3948 case FK_UserConversionOverloadFailed:
3949 OS << "overloading failed for user-defined conversion";
3950 break;
3951
3952 case FK_ConstructorOverloadFailed:
3953 OS << "constructor overloading failed";
3954 break;
3955
3956 case FK_DefaultInitOfConst:
3957 OS << "default initialization of a const variable";
3958 break;
3959 }
3960 OS << '\n';
3961 return;
3962 }
3963
3964 case DependentSequence:
3965 OS << "Dependent sequence: ";
3966 return;
3967
3968 case UserDefinedConversion:
3969 OS << "User-defined conversion sequence: ";
3970 break;
3971
3972 case ConstructorInitialization:
3973 OS << "Constructor initialization sequence: ";
3974 break;
3975
3976 case ReferenceBinding:
3977 OS << "Reference binding: ";
3978 break;
3979
3980 case ListInitialization:
3981 OS << "List initialization: ";
3982 break;
3983
3984 case ZeroInitialization:
3985 OS << "Zero initialization\n";
3986 return;
3987
3988 case NoInitialization:
3989 OS << "No initialization\n";
3990 return;
3991
3992 case StandardConversion:
3993 OS << "Standard conversion: ";
3994 break;
3995
3996 case CAssignment:
3997 OS << "C assignment: ";
3998 break;
3999
4000 case StringInit:
4001 OS << "String initialization: ";
4002 break;
4003 }
4004
4005 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4006 if (S != step_begin()) {
4007 OS << " -> ";
4008 }
4009
4010 switch (S->Kind) {
4011 case SK_ResolveAddressOfOverloadedFunction:
4012 OS << "resolve address of overloaded function";
4013 break;
4014
4015 case SK_CastDerivedToBaseRValue:
4016 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4017 break;
4018
4019 case SK_CastDerivedToBaseLValue:
4020 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4021 break;
4022
4023 case SK_BindReference:
4024 OS << "bind reference to lvalue";
4025 break;
4026
4027 case SK_BindReferenceToTemporary:
4028 OS << "bind reference to a temporary";
4029 break;
4030
4031 case SK_UserConversion:
John McCall9aa472c2010-03-19 07:35:19 +00004032 OS << "user-defined conversion via "
4033 << S->Function.Function->getNameAsString();
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004034 break;
4035
4036 case SK_QualificationConversionRValue:
4037 OS << "qualification conversion (rvalue)";
4038
4039 case SK_QualificationConversionLValue:
4040 OS << "qualification conversion (lvalue)";
4041 break;
4042
4043 case SK_ConversionSequence:
4044 OS << "implicit conversion sequence (";
4045 S->ICS->DebugPrint(); // FIXME: use OS
4046 OS << ")";
4047 break;
4048
4049 case SK_ListInitialization:
4050 OS << "list initialization";
4051 break;
4052
4053 case SK_ConstructorInitialization:
4054 OS << "constructor initialization";
4055 break;
4056
4057 case SK_ZeroInitialization:
4058 OS << "zero initialization";
4059 break;
4060
4061 case SK_CAssignment:
4062 OS << "C assignment";
4063 break;
4064
4065 case SK_StringInit:
4066 OS << "string initialization";
4067 break;
4068 }
4069 }
4070}
4071
4072void InitializationSequence::dump() const {
4073 dump(llvm::errs());
4074}
4075
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004076//===----------------------------------------------------------------------===//
4077// Initialization helper functions
4078//===----------------------------------------------------------------------===//
4079Sema::OwningExprResult
4080Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4081 SourceLocation EqualLoc,
4082 OwningExprResult Init) {
4083 if (Init.isInvalid())
4084 return ExprError();
4085
4086 Expr *InitE = (Expr *)Init.get();
4087 assert(InitE && "No initialization expression?");
4088
4089 if (EqualLoc.isInvalid())
4090 EqualLoc = InitE->getLocStart();
4091
4092 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4093 EqualLoc);
4094 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4095 Init.release();
4096 return Seq.Perform(*this, Entity, Kind,
4097 MultiExprArg(*this, (void**)&InitE, 1));
4098}