blob: 98db60854f3ec021b3f1c41ec9f08d0458aaa22b [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;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001054 while (Index < IList->getNumInits()) {
1055 Expr *Init = IList->getInit(Index);
1056
1057 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001058 // If we're not the subobject that matches up with the '{' for
1059 // the designator, we shouldn't be handling the
1060 // designator. Return immediately.
1061 if (!SubobjectIsDesignatorContext)
1062 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001064 // Handle this designated initializer. Field will be updated to
1065 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001066 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001067 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001068 StructuredList, StructuredIndex,
1069 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001070 hadError = true;
1071
Douglas Gregordfb5e592009-02-12 19:00:39 +00001072 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001073 continue;
1074 }
1075
1076 if (Field == FieldEnd) {
1077 // We've run out of fields. We're done.
1078 break;
1079 }
1080
Douglas Gregordfb5e592009-02-12 19:00:39 +00001081 // We've already initialized a member of a union. We're done.
1082 if (InitializedSomething && DeclType->isUnionType())
1083 break;
1084
Douglas Gregor44b43212008-12-11 16:49:14 +00001085 // If we've hit the flexible array member at the end, we're done.
1086 if (Field->getType()->isIncompleteArrayType())
1087 break;
1088
Douglas Gregor0bb76892009-01-29 16:53:55 +00001089 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001090 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001091 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001092 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001093 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001094
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001095 InitializedEntity MemberEntity =
1096 InitializedEntity::InitializeMember(*Field, &Entity);
1097 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1098 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001099 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001100
1101 if (DeclType->isUnionType()) {
1102 // Initialize the first field within the union.
1103 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001104 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001105
1106 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001107 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001108
Mike Stump1eb44332009-09-09 15:08:12 +00001109 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001110 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001111 return;
1112
1113 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001114 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001115 (!isa<InitListExpr>(IList->getInit(Index)) ||
1116 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001117 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001118 diag::err_flexible_array_init_nonempty)
1119 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001120 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001121 << *Field;
1122 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001123 ++Index;
1124 return;
1125 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001126 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001127 diag::ext_flexible_array_init)
1128 << IList->getInit(Index)->getSourceRange().getBegin();
1129 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1130 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001131 }
1132
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001133 InitializedEntity MemberEntity =
1134 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001135
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001136 if (isa<InitListExpr>(IList->getInit(Index)))
1137 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1138 StructuredList, StructuredIndex);
1139 else
1140 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001141 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001142}
Steve Naroff0cca7492008-05-01 22:18:59 +00001143
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001144/// \brief Expand a field designator that refers to a member of an
1145/// anonymous struct or union into a series of field designators that
1146/// refers to the field within the appropriate subobject.
1147///
1148/// Field/FieldIndex will be updated to point to the (new)
1149/// currently-designated field.
1150static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001151 DesignatedInitExpr *DIE,
1152 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001153 FieldDecl *Field,
1154 RecordDecl::field_iterator &FieldIter,
1155 unsigned &FieldIndex) {
1156 typedef DesignatedInitExpr::Designator Designator;
1157
1158 // Build the path from the current object to the member of the
1159 // anonymous struct/union (backwards).
1160 llvm::SmallVector<FieldDecl *, 4> Path;
1161 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001163 // Build the replacement designators.
1164 llvm::SmallVector<Designator, 4> Replacements;
1165 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1166 FI = Path.rbegin(), FIEnd = Path.rend();
1167 FI != FIEnd; ++FI) {
1168 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001169 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001170 DIE->getDesignator(DesigIdx)->getDotLoc(),
1171 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1172 else
1173 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1174 SourceLocation()));
1175 Replacements.back().setField(*FI);
1176 }
1177
1178 // Expand the current designator into the set of replacement
1179 // designators, so we have a full subobject path down to where the
1180 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001181 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001182 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001184 // Update FieldIter/FieldIndex;
1185 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001186 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001187 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001188 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001189 FieldIter != FEnd; ++FieldIter) {
1190 if (FieldIter->isUnnamedBitfield())
1191 continue;
1192
1193 if (*FieldIter == Path.back())
1194 return;
1195
1196 ++FieldIndex;
1197 }
1198
1199 assert(false && "Unable to find anonymous struct/union field");
1200}
1201
Douglas Gregor05c13a32009-01-22 00:58:24 +00001202/// @brief Check the well-formedness of a C99 designated initializer.
1203///
1204/// Determines whether the designated initializer @p DIE, which
1205/// resides at the given @p Index within the initializer list @p
1206/// IList, is well-formed for a current object of type @p DeclType
1207/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001208/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001209/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001210///
1211/// @param IList The initializer list in which this designated
1212/// initializer occurs.
1213///
Douglas Gregor71199712009-04-15 04:56:10 +00001214/// @param DIE The designated initializer expression.
1215///
1216/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001217///
1218/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1219/// into which the designation in @p DIE should refer.
1220///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001221/// @param NextField If non-NULL and the first designator in @p DIE is
1222/// a field, this will be set to the field declaration corresponding
1223/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001224///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001225/// @param NextElementIndex If non-NULL and the first designator in @p
1226/// DIE is an array designator or GNU array-range designator, this
1227/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001228///
1229/// @param Index Index into @p IList where the designated initializer
1230/// @p DIE occurs.
1231///
Douglas Gregor4c678342009-01-28 21:54:33 +00001232/// @param StructuredList The initializer list expression that
1233/// describes all of the subobject initializers in the order they'll
1234/// actually be initialized.
1235///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001236/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001237bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001238InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001239 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001240 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001241 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001242 QualType &CurrentObjectType,
1243 RecordDecl::field_iterator *NextField,
1244 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001245 unsigned &Index,
1246 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001247 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001248 bool FinishSubobjectInit,
1249 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001250 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001251 // Check the actual initialization for the designated object type.
1252 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001253
1254 // Temporarily remove the designator expression from the
1255 // initializer list that the child calls see, so that we don't try
1256 // to re-process the designator.
1257 unsigned OldIndex = Index;
1258 IList->setInit(OldIndex, DIE->getInit());
1259
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001260 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001261 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001262
1263 // Restore the designated initializer expression in the syntactic
1264 // form of the initializer list.
1265 if (IList->getInit(OldIndex) != DIE->getInit())
1266 DIE->setInit(IList->getInit(OldIndex));
1267 IList->setInit(OldIndex, DIE);
1268
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001269 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001270 }
1271
Douglas Gregor71199712009-04-15 04:56:10 +00001272 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001273 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001274 "Need a non-designated initializer list to start from");
1275
Douglas Gregor71199712009-04-15 04:56:10 +00001276 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001277 // Determine the structural initializer list that corresponds to the
1278 // current subobject.
1279 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001280 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001281 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001282 SourceRange(D->getStartLocation(),
1283 DIE->getSourceRange().getEnd()));
1284 assert(StructuredList && "Expected a structured initializer list");
1285
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001286 if (D->isFieldDesignator()) {
1287 // C99 6.7.8p7:
1288 //
1289 // If a designator has the form
1290 //
1291 // . identifier
1292 //
1293 // then the current object (defined below) shall have
1294 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001295 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001296 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 if (!RT) {
1298 SourceLocation Loc = D->getDotLoc();
1299 if (Loc.isInvalid())
1300 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001301 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1302 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001303 ++Index;
1304 return true;
1305 }
1306
Douglas Gregor4c678342009-01-28 21:54:33 +00001307 // Note: we perform a linear search of the fields here, despite
1308 // the fact that we have a faster lookup method, because we always
1309 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001310 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001311 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001312 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001313 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001314 Field = RT->getDecl()->field_begin(),
1315 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001316 for (; Field != FieldEnd; ++Field) {
1317 if (Field->isUnnamedBitfield())
1318 continue;
1319
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001320 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001321 break;
1322
1323 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001324 }
1325
Douglas Gregor4c678342009-01-28 21:54:33 +00001326 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001327 // There was no normal field in the struct with the designated
1328 // name. Perform another lookup for this name, which may find
1329 // something that we can't designate (e.g., a member function),
1330 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001331 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001332 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001333 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001335 // Name lookup didn't find anything. Determine whether this
1336 // was a typo for another field name.
1337 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1338 Sema::LookupMemberName);
1339 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1340 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1341 ReplacementField->getDeclContext()->getLookupContext()
1342 ->Equals(RT->getDecl())) {
1343 SemaRef.Diag(D->getFieldLoc(),
1344 diag::err_field_designator_unknown_suggest)
1345 << FieldName << CurrentObjectType << R.getLookupName()
1346 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1347 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001348 SemaRef.Diag(ReplacementField->getLocation(),
1349 diag::note_previous_decl)
1350 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001351 } else {
1352 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1353 << FieldName << CurrentObjectType;
1354 ++Index;
1355 return true;
1356 }
1357 } else if (!KnownField) {
1358 // Determine whether we found a field at all.
1359 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1360 }
1361
1362 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001363 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001364 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001366 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001367 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001368 ++Index;
1369 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001370 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001371
1372 if (!KnownField &&
1373 cast<RecordDecl>((ReplacementField)->getDeclContext())
1374 ->isAnonymousStructOrUnion()) {
1375 // Handle an field designator that refers to a member of an
1376 // anonymous struct or union.
1377 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1378 ReplacementField,
1379 Field, FieldIndex);
1380 D = DIE->getDesignator(DesigIdx);
1381 } else if (!KnownField) {
1382 // The replacement field comes from typo correction; find it
1383 // in the list of fields.
1384 FieldIndex = 0;
1385 Field = RT->getDecl()->field_begin();
1386 for (; Field != FieldEnd; ++Field) {
1387 if (Field->isUnnamedBitfield())
1388 continue;
1389
1390 if (ReplacementField == *Field ||
1391 Field->getIdentifier() == ReplacementField->getIdentifier())
1392 break;
1393
1394 ++FieldIndex;
1395 }
1396 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001397 } else if (!KnownField &&
1398 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001400 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1401 Field, FieldIndex);
1402 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001403 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001404
1405 // All of the fields of a union are located at the same place in
1406 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001407 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001408 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001409 StructuredList->setInitializedFieldInUnion(*Field);
1410 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001411
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001412 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001413 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Douglas Gregor4c678342009-01-28 21:54:33 +00001415 // Make sure that our non-designated initializer list has space
1416 // for a subobject corresponding to this field.
1417 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001418 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001419
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001420 // This designator names a flexible array member.
1421 if (Field->getType()->isIncompleteArrayType()) {
1422 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001423 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001424 // We can't designate an object within the flexible array
1425 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001426 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001427 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001428 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001429 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001430 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001431 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001432 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001433 << *Field;
1434 Invalid = true;
1435 }
1436
1437 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1438 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001439 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001440 diag::err_flexible_array_init_needs_braces)
1441 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001442 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001443 << *Field;
1444 Invalid = true;
1445 }
1446
1447 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001448 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001450 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 diag::err_flexible_array_init_nonempty)
1452 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001453 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001454 << *Field;
1455 Invalid = true;
1456 }
1457
1458 if (Invalid) {
1459 ++Index;
1460 return true;
1461 }
1462
1463 // Initialize the array.
1464 bool prevHadError = hadError;
1465 unsigned newStructuredIndex = FieldIndex;
1466 unsigned OldIndex = Index;
1467 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001468
1469 InitializedEntity MemberEntity =
1470 InitializedEntity::InitializeMember(*Field, &Entity);
1471 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001473
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001474 IList->setInit(OldIndex, DIE);
1475 if (hadError && !prevHadError) {
1476 ++Field;
1477 ++FieldIndex;
1478 if (NextField)
1479 *NextField = Field;
1480 StructuredIndex = FieldIndex;
1481 return true;
1482 }
1483 } else {
1484 // Recurse to check later designated subobjects.
1485 QualType FieldType = (*Field)->getType();
1486 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001487
1488 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001489 InitializedEntity::InitializeMember(*Field, &Entity);
1490 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001491 FieldType, 0, 0, Index,
1492 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001493 true, false))
1494 return true;
1495 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001496
1497 // Find the position of the next field to be initialized in this
1498 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001499 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001500 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001501
1502 // If this the first designator, our caller will continue checking
1503 // the rest of this struct/class/union subobject.
1504 if (IsFirstDesignator) {
1505 if (NextField)
1506 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001507 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001508 return false;
1509 }
1510
Douglas Gregor34e79462009-01-28 23:36:17 +00001511 if (!FinishSubobjectInit)
1512 return false;
1513
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001514 // We've already initialized something in the union; we're done.
1515 if (RT->getDecl()->isUnion())
1516 return hadError;
1517
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001518 // Check the remaining fields within this class/struct/union subobject.
1519 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001520
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001521 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001522 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523 return hadError && !prevHadError;
1524 }
1525
1526 // C99 6.7.8p6:
1527 //
1528 // If a designator has the form
1529 //
1530 // [ constant-expression ]
1531 //
1532 // then the current object (defined below) shall have array
1533 // type and the expression shall be an integer constant
1534 // expression. If the array is of unknown size, any
1535 // nonnegative value is valid.
1536 //
1537 // Additionally, cope with the GNU extension that permits
1538 // designators of the form
1539 //
1540 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001541 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001542 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001543 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001544 << CurrentObjectType;
1545 ++Index;
1546 return true;
1547 }
1548
1549 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001550 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1551 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001553 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001554 DesignatedEndIndex = DesignatedStartIndex;
1555 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001556 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001557
Mike Stump1eb44332009-09-09 15:08:12 +00001558
1559 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001560 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001561 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001562 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001564
Chris Lattner3bf68932009-04-25 21:59:05 +00001565 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001566 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001567 }
1568
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001569 if (isa<ConstantArrayType>(AT)) {
1570 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001571 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1572 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1573 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1574 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1575 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001576 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001577 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001578 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001579 << IndexExpr->getSourceRange();
1580 ++Index;
1581 return true;
1582 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 } else {
1584 // Make sure the bit-widths and signedness match.
1585 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1586 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001587 else if (DesignatedStartIndex.getBitWidth() <
1588 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001589 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1590 DesignatedStartIndex.setIsUnsigned(true);
1591 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Douglas Gregor4c678342009-01-28 21:54:33 +00001594 // Make sure that our non-designated initializer list has space
1595 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001596 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001597 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001598 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001599
Douglas Gregor34e79462009-01-28 23:36:17 +00001600 // Repeatedly perform subobject initializations in the range
1601 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001602
Douglas Gregor34e79462009-01-28 23:36:17 +00001603 // Move to the next designator
1604 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1605 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001606
1607 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001608 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001609
Douglas Gregor34e79462009-01-28 23:36:17 +00001610 while (DesignatedStartIndex <= DesignatedEndIndex) {
1611 // Recurse to check later designated subobjects.
1612 QualType ElementType = AT->getElementType();
1613 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001614
1615 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001616 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001617 ElementType, 0, 0, Index,
1618 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001619 (DesignatedStartIndex == DesignatedEndIndex),
1620 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 return true;
1622
1623 // Move to the next index in the array that we'll be initializing.
1624 ++DesignatedStartIndex;
1625 ElementIndex = DesignatedStartIndex.getZExtValue();
1626 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001627
1628 // If this the first designator, our caller will continue checking
1629 // the rest of this array subobject.
1630 if (IsFirstDesignator) {
1631 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001632 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001634 return false;
1635 }
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor34e79462009-01-28 23:36:17 +00001637 if (!FinishSubobjectInit)
1638 return false;
1639
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001641 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001642 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001643 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001644 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001645 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001646}
1647
Douglas Gregor4c678342009-01-28 21:54:33 +00001648// Get the structured initializer list for a subobject of type
1649// @p CurrentObjectType.
1650InitListExpr *
1651InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1652 QualType CurrentObjectType,
1653 InitListExpr *StructuredList,
1654 unsigned StructuredIndex,
1655 SourceRange InitRange) {
1656 Expr *ExistingInit = 0;
1657 if (!StructuredList)
1658 ExistingInit = SyntacticToSemantic[IList];
1659 else if (StructuredIndex < StructuredList->getNumInits())
1660 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1663 return Result;
1664
1665 if (ExistingInit) {
1666 // We are creating an initializer list that initializes the
1667 // subobjects of the current object, but there was already an
1668 // initialization that completely initialized the current
1669 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001670 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001671 // struct X { int a, b; };
1672 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001673 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001674 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1675 // designated initializer re-initializes the whole
1676 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001677 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001678 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001679 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001680 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001681 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001682 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001683 << ExistingInit->getSourceRange();
1684 }
1685
Mike Stump1eb44332009-09-09 15:08:12 +00001686 InitListExpr *Result
Ted Kremenekba7bc552010-02-19 01:50:18 +00001687 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1688 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001689
Douglas Gregor2c792812010-02-09 00:50:06 +00001690 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001691
Douglas Gregorfa219202009-03-20 23:58:33 +00001692 // Pre-allocate storage for the structured initializer list.
1693 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001694 unsigned NumInits = 0;
1695 if (!StructuredList)
1696 NumInits = IList->getNumInits();
1697 else if (Index < IList->getNumInits()) {
1698 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1699 NumInits = SubList->getNumInits();
1700 }
1701
Mike Stump1eb44332009-09-09 15:08:12 +00001702 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001703 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1704 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1705 NumElements = CAType->getSize().getZExtValue();
1706 // Simple heuristic so that we don't allocate a very large
1707 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001708 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001709 NumElements = 0;
1710 }
John McCall183700f2009-09-21 23:43:11 +00001711 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001712 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001713 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001714 RecordDecl *RDecl = RType->getDecl();
1715 if (RDecl->isUnion())
1716 NumElements = 1;
1717 else
Mike Stump1eb44332009-09-09 15:08:12 +00001718 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001719 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001720 }
1721
Douglas Gregor08457732009-03-21 18:13:52 +00001722 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001723 NumElements = IList->getNumInits();
1724
Ted Kremenekba7bc552010-02-19 01:50:18 +00001725 Result->reserveInits(NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001726
Douglas Gregor4c678342009-01-28 21:54:33 +00001727 // Link this new initializer list into the structured initializer
1728 // lists.
1729 if (StructuredList)
Ted Kremenekba7bc552010-02-19 01:50:18 +00001730 StructuredList->updateInit(StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 else {
1732 Result->setSyntacticForm(IList);
1733 SyntacticToSemantic[IList] = Result;
1734 }
1735
1736 return Result;
1737}
1738
1739/// Update the initializer at index @p StructuredIndex within the
1740/// structured initializer list to the value @p expr.
1741void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1742 unsigned &StructuredIndex,
1743 Expr *expr) {
1744 // No structured initializer list to update
1745 if (!StructuredList)
1746 return;
1747
Ted Kremenekba7bc552010-02-19 01:50:18 +00001748 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001749 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001750 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 diag::warn_initializer_overrides)
1752 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001753 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001754 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001755 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001756 << PrevInit->getSourceRange();
1757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Douglas Gregor4c678342009-01-28 21:54:33 +00001759 ++StructuredIndex;
1760}
1761
Douglas Gregor05c13a32009-01-22 00:58:24 +00001762/// Check that the given Index expression is a valid array designator
1763/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001764/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001765/// and produces a reasonable diagnostic if there is a
1766/// failure. Returns true if there was an error, false otherwise. If
1767/// everything went okay, Value will receive the value of the constant
1768/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001769static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001770CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001771 SourceLocation Loc = Index->getSourceRange().getBegin();
1772
1773 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001774 if (S.VerifyIntegerConstantExpression(Index, &Value))
1775 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001776
Chris Lattner3bf68932009-04-25 21:59:05 +00001777 if (Value.isSigned() && Value.isNegative())
1778 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001779 << Value.toString(10) << Index->getSourceRange();
1780
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001781 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001782 return false;
1783}
1784
1785Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1786 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001787 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001788 OwningExprResult Init) {
1789 typedef DesignatedInitExpr::Designator ASTDesignator;
1790
1791 bool Invalid = false;
1792 llvm::SmallVector<ASTDesignator, 32> Designators;
1793 llvm::SmallVector<Expr *, 32> InitExpressions;
1794
1795 // Build designators and check array designator expressions.
1796 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1797 const Designator &D = Desig.getDesignator(Idx);
1798 switch (D.getKind()) {
1799 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001800 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001801 D.getFieldLoc()));
1802 break;
1803
1804 case Designator::ArrayDesignator: {
1805 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1806 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001807 if (!Index->isTypeDependent() &&
1808 !Index->isValueDependent() &&
1809 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001810 Invalid = true;
1811 else {
1812 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001813 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001814 D.getRBracketLoc()));
1815 InitExpressions.push_back(Index);
1816 }
1817 break;
1818 }
1819
1820 case Designator::ArrayRangeDesignator: {
1821 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1822 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1823 llvm::APSInt StartValue;
1824 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001825 bool StartDependent = StartIndex->isTypeDependent() ||
1826 StartIndex->isValueDependent();
1827 bool EndDependent = EndIndex->isTypeDependent() ||
1828 EndIndex->isValueDependent();
1829 if ((!StartDependent &&
1830 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1831 (!EndDependent &&
1832 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001833 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001834 else {
1835 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001836 if (StartDependent || EndDependent) {
1837 // Nothing to compute.
1838 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001839 EndValue.extend(StartValue.getBitWidth());
1840 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1841 StartValue.extend(EndValue.getBitWidth());
1842
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001843 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001844 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001845 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001846 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1847 Invalid = true;
1848 } else {
1849 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001850 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001851 D.getEllipsisLoc(),
1852 D.getRBracketLoc()));
1853 InitExpressions.push_back(StartIndex);
1854 InitExpressions.push_back(EndIndex);
1855 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001856 }
1857 break;
1858 }
1859 }
1860 }
1861
1862 if (Invalid || Init.isInvalid())
1863 return ExprError();
1864
1865 // Clear out the expressions within the designation.
1866 Desig.ClearExprs(*this);
1867
1868 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001869 = DesignatedInitExpr::Create(Context,
1870 Designators.data(), Designators.size(),
1871 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001872 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001873 return Owned(DIE);
1874}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001875
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001876bool Sema::CheckInitList(const InitializedEntity &Entity,
1877 InitListExpr *&InitList, QualType &DeclType) {
1878 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001879 if (!CheckInitList.HadError())
1880 InitList = CheckInitList.getFullyStructuredList();
1881
1882 return CheckInitList.HadError();
1883}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001884
Douglas Gregor20093b42009-12-09 23:02:17 +00001885//===----------------------------------------------------------------------===//
1886// Initialization entity
1887//===----------------------------------------------------------------------===//
1888
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001889InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1890 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001891 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001892{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001893 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1894 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001895 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001896 } else {
1897 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001898 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001899 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001900}
1901
1902InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1903 CXXBaseSpecifier *Base)
1904{
1905 InitializedEntity Result;
1906 Result.Kind = EK_Base;
1907 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001908 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001909 return Result;
1910}
1911
Douglas Gregor99a2e602009-12-16 01:38:02 +00001912DeclarationName InitializedEntity::getName() const {
1913 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001914 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001915 if (!VariableOrMember)
1916 return DeclarationName();
1917 // Fall through
1918
1919 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001920 case EK_Member:
1921 return VariableOrMember->getDeclName();
1922
1923 case EK_Result:
1924 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001925 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001926 case EK_Temporary:
1927 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001928 case EK_ArrayElement:
1929 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001930 return DeclarationName();
1931 }
1932
1933 // Silence GCC warning
1934 return DeclarationName();
1935}
1936
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001937DeclaratorDecl *InitializedEntity::getDecl() const {
1938 switch (getKind()) {
1939 case EK_Variable:
1940 case EK_Parameter:
1941 case EK_Member:
1942 return VariableOrMember;
1943
1944 case EK_Result:
1945 case EK_Exception:
1946 case EK_New:
1947 case EK_Temporary:
1948 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001949 case EK_ArrayElement:
1950 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001951 return 0;
1952 }
1953
1954 // Silence GCC warning
1955 return 0;
1956}
1957
Douglas Gregor20093b42009-12-09 23:02:17 +00001958//===----------------------------------------------------------------------===//
1959// Initialization sequence
1960//===----------------------------------------------------------------------===//
1961
1962void InitializationSequence::Step::Destroy() {
1963 switch (Kind) {
1964 case SK_ResolveAddressOfOverloadedFunction:
1965 case SK_CastDerivedToBaseRValue:
1966 case SK_CastDerivedToBaseLValue:
1967 case SK_BindReference:
1968 case SK_BindReferenceToTemporary:
1969 case SK_UserConversion:
1970 case SK_QualificationConversionRValue:
1971 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001972 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001973 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001974 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001975 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001976 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001977 break;
1978
1979 case SK_ConversionSequence:
1980 delete ICS;
1981 }
1982}
1983
1984void InitializationSequence::AddAddressOverloadResolutionStep(
1985 FunctionDecl *Function) {
1986 Step S;
1987 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1988 S.Type = Function->getType();
John McCallb13b7372010-02-01 03:16:54 +00001989 // Access is currently ignored for these.
1990 S.Function = DeclAccessPair::make(Function, AccessSpecifier(0));
Douglas Gregor20093b42009-12-09 23:02:17 +00001991 Steps.push_back(S);
1992}
1993
1994void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1995 bool IsLValue) {
1996 Step S;
1997 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1998 S.Type = BaseType;
1999 Steps.push_back(S);
2000}
2001
2002void InitializationSequence::AddReferenceBindingStep(QualType T,
2003 bool BindingTemporary) {
2004 Step S;
2005 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2006 S.Type = T;
2007 Steps.push_back(S);
2008}
2009
Eli Friedman03981012009-12-11 02:42:07 +00002010void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCallb13b7372010-02-01 03:16:54 +00002011 AccessSpecifier Access,
Eli Friedman03981012009-12-11 02:42:07 +00002012 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002013 Step S;
2014 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002015 S.Type = T;
John McCallb13b7372010-02-01 03:16:54 +00002016 S.Function = DeclAccessPair::make(Function, Access);
Douglas Gregor20093b42009-12-09 23:02:17 +00002017 Steps.push_back(S);
2018}
2019
2020void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2021 bool IsLValue) {
2022 Step S;
2023 S.Kind = IsLValue? SK_QualificationConversionLValue
2024 : SK_QualificationConversionRValue;
2025 S.Type = Ty;
2026 Steps.push_back(S);
2027}
2028
2029void InitializationSequence::AddConversionSequenceStep(
2030 const ImplicitConversionSequence &ICS,
2031 QualType T) {
2032 Step S;
2033 S.Kind = SK_ConversionSequence;
2034 S.Type = T;
2035 S.ICS = new ImplicitConversionSequence(ICS);
2036 Steps.push_back(S);
2037}
2038
Douglas Gregord87b61f2009-12-10 17:56:55 +00002039void InitializationSequence::AddListInitializationStep(QualType T) {
2040 Step S;
2041 S.Kind = SK_ListInitialization;
2042 S.Type = T;
2043 Steps.push_back(S);
2044}
2045
Douglas Gregor51c56d62009-12-14 20:49:26 +00002046void
2047InitializationSequence::AddConstructorInitializationStep(
2048 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002049 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002050 QualType T) {
2051 Step S;
2052 S.Kind = SK_ConstructorInitialization;
2053 S.Type = T;
John McCallb13b7372010-02-01 03:16:54 +00002054 S.Function = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002055 Steps.push_back(S);
2056}
2057
Douglas Gregor71d17402009-12-15 00:01:57 +00002058void InitializationSequence::AddZeroInitializationStep(QualType T) {
2059 Step S;
2060 S.Kind = SK_ZeroInitialization;
2061 S.Type = T;
2062 Steps.push_back(S);
2063}
2064
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002065void InitializationSequence::AddCAssignmentStep(QualType T) {
2066 Step S;
2067 S.Kind = SK_CAssignment;
2068 S.Type = T;
2069 Steps.push_back(S);
2070}
2071
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002072void InitializationSequence::AddStringInitStep(QualType T) {
2073 Step S;
2074 S.Kind = SK_StringInit;
2075 S.Type = T;
2076 Steps.push_back(S);
2077}
2078
Douglas Gregor20093b42009-12-09 23:02:17 +00002079void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2080 OverloadingResult Result) {
2081 SequenceKind = FailedSequence;
2082 this->Failure = Failure;
2083 this->FailedOverloadResult = Result;
2084}
2085
2086//===----------------------------------------------------------------------===//
2087// Attempt initialization
2088//===----------------------------------------------------------------------===//
2089
2090/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002091static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002092 const InitializedEntity &Entity,
2093 const InitializationKind &Kind,
2094 InitListExpr *InitList,
2095 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002096 // FIXME: We only perform rudimentary checking of list
2097 // initializations at this point, then assume that any list
2098 // initialization of an array, aggregate, or scalar will be
2099 // well-formed. We we actually "perform" list initialization, we'll
2100 // do all of the necessary checking. C++0x initializer lists will
2101 // force us to perform more checking here.
2102 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2103
Douglas Gregord6542d82009-12-22 15:35:07 +00002104 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002105
2106 // C++ [dcl.init]p13:
2107 // If T is a scalar type, then a declaration of the form
2108 //
2109 // T x = { a };
2110 //
2111 // is equivalent to
2112 //
2113 // T x = a;
2114 if (DestType->isScalarType()) {
2115 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2116 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2117 return;
2118 }
2119
2120 // Assume scalar initialization from a single value works.
2121 } else if (DestType->isAggregateType()) {
2122 // Assume aggregate initialization works.
2123 } else if (DestType->isVectorType()) {
2124 // Assume vector initialization works.
2125 } else if (DestType->isReferenceType()) {
2126 // FIXME: C++0x defines behavior for this.
2127 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2128 return;
2129 } else if (DestType->isRecordType()) {
2130 // FIXME: C++0x defines behavior for this
2131 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2132 }
2133
2134 // Add a general "list initialization" step.
2135 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002136}
2137
2138/// \brief Try a reference initialization that involves calling a conversion
2139/// function.
2140///
2141/// FIXME: look intos DRs 656, 896
2142static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2143 const InitializedEntity &Entity,
2144 const InitializationKind &Kind,
2145 Expr *Initializer,
2146 bool AllowRValues,
2147 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002148 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2150 QualType T1 = cv1T1.getUnqualifiedType();
2151 QualType cv2T2 = Initializer->getType();
2152 QualType T2 = cv2T2.getUnqualifiedType();
2153
2154 bool DerivedToBase;
2155 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2156 T1, T2, DerivedToBase) &&
2157 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002158 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002159
2160 // Build the candidate set directly in the initialization sequence
2161 // structure, so that it will persist if we fail.
2162 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2163 CandidateSet.clear();
2164
2165 // Determine whether we are allowed to call explicit constructors or
2166 // explicit conversion operators.
2167 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2168
2169 const RecordType *T1RecordType = 0;
2170 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2171 // The type we're converting to is a class type. Enumerate its constructors
2172 // to see if there is a suitable conversion.
2173 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2174
2175 DeclarationName ConstructorName
2176 = S.Context.DeclarationNames.getCXXConstructorName(
2177 S.Context.getCanonicalType(T1).getUnqualifiedType());
2178 DeclContext::lookup_iterator Con, ConEnd;
2179 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2180 Con != ConEnd; ++Con) {
2181 // Find the constructor (which may be a template).
2182 CXXConstructorDecl *Constructor = 0;
2183 FunctionTemplateDecl *ConstructorTmpl
2184 = dyn_cast<FunctionTemplateDecl>(*Con);
2185 if (ConstructorTmpl)
2186 Constructor = cast<CXXConstructorDecl>(
2187 ConstructorTmpl->getTemplatedDecl());
2188 else
2189 Constructor = cast<CXXConstructorDecl>(*Con);
2190
2191 if (!Constructor->isInvalidDecl() &&
2192 Constructor->isConvertingConstructor(AllowExplicit)) {
2193 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002194 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2195 ConstructorTmpl->getAccess(),
2196 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002197 &Initializer, 1, CandidateSet);
2198 else
John McCall86820f52010-01-26 01:37:31 +00002199 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2200 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002201 }
2202 }
2203 }
2204
2205 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2206 // The type we're converting from is a class type, enumerate its conversion
2207 // functions.
2208 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2209
2210 // Determine the type we are converting to. If we are allowed to
2211 // convert to an rvalue, take the type that the destination type
2212 // refers to.
2213 QualType ToType = AllowRValues? cv1T1 : DestType;
2214
John McCalleec51cf2010-01-20 00:46:10 +00002215 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002216 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002217 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2218 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002219 NamedDecl *D = *I;
2220 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2221 if (isa<UsingShadowDecl>(D))
2222 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2223
2224 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2225 CXXConversionDecl *Conv;
2226 if (ConvTemplate)
2227 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2228 else
2229 Conv = cast<CXXConversionDecl>(*I);
2230
2231 // If the conversion function doesn't return a reference type,
2232 // it can't be considered for this conversion unless we're allowed to
2233 // consider rvalues.
2234 // FIXME: Do we need to make sure that we only consider conversion
2235 // candidates with reference-compatible results? That might be needed to
2236 // break recursion.
2237 if ((AllowExplicit || !Conv->isExplicit()) &&
2238 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2239 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002240 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2241 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002242 ToType, CandidateSet);
2243 else
John McCall86820f52010-01-26 01:37:31 +00002244 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002245 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002246 }
2247 }
2248 }
2249
2250 SourceLocation DeclLoc = Initializer->getLocStart();
2251
2252 // Perform overload resolution. If it fails, return the failed result.
2253 OverloadCandidateSet::iterator Best;
2254 if (OverloadingResult Result
2255 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2256 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002257
Douglas Gregor20093b42009-12-09 23:02:17 +00002258 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002259
2260 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002261 if (isa<CXXConversionDecl>(Function))
2262 T2 = Function->getResultType();
2263 else
2264 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002265
2266 // Add the user-defined conversion step.
John McCallb13b7372010-02-01 03:16:54 +00002267 Sequence.AddUserConversionStep(Function, Best->getAccess(),
2268 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002269
2270 // Determine whether we need to perform derived-to-base or
2271 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002272 bool NewDerivedToBase = false;
2273 Sema::ReferenceCompareResult NewRefRelationship
2274 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2275 NewDerivedToBase);
2276 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2277 "Overload resolution picked a bad conversion function");
2278 (void)NewRefRelationship;
2279 if (NewDerivedToBase)
2280 Sequence.AddDerivedToBaseCastStep(
2281 S.Context.getQualifiedType(T1,
2282 T2.getNonReferenceType().getQualifiers()),
2283 /*isLValue=*/true);
2284
2285 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2286 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2287
2288 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2289 return OR_Success;
2290}
2291
2292/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2293static void TryReferenceInitialization(Sema &S,
2294 const InitializedEntity &Entity,
2295 const InitializationKind &Kind,
2296 Expr *Initializer,
2297 InitializationSequence &Sequence) {
2298 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2299
Douglas Gregord6542d82009-12-22 15:35:07 +00002300 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002301 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002302 Qualifiers T1Quals;
2303 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002305 Qualifiers T2Quals;
2306 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002307 SourceLocation DeclLoc = Initializer->getLocStart();
2308
2309 // If the initializer is the address of an overloaded function, try
2310 // to resolve the overloaded function. If all goes well, T2 is the
2311 // type of the resulting function.
2312 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2313 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2314 T1,
2315 false);
2316 if (!Fn) {
2317 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2318 return;
2319 }
2320
2321 Sequence.AddAddressOverloadResolutionStep(Fn);
2322 cv2T2 = Fn->getType();
2323 T2 = cv2T2.getUnqualifiedType();
2324 }
2325
2326 // FIXME: Rvalue references
2327 bool ForceRValue = false;
2328
2329 // Compute some basic properties of the types and the initializer.
2330 bool isLValueRef = DestType->isLValueReferenceType();
2331 bool isRValueRef = !isLValueRef;
2332 bool DerivedToBase = false;
2333 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2334 Initializer->isLvalue(S.Context);
2335 Sema::ReferenceCompareResult RefRelationship
2336 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2337
2338 // C++0x [dcl.init.ref]p5:
2339 // A reference to type "cv1 T1" is initialized by an expression of type
2340 // "cv2 T2" as follows:
2341 //
2342 // - If the reference is an lvalue reference and the initializer
2343 // expression
2344 OverloadingResult ConvOvlResult = OR_Success;
2345 if (isLValueRef) {
2346 if (InitLvalue == Expr::LV_Valid &&
2347 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2348 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2349 // reference-compatible with "cv2 T2," or
2350 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002351 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002352 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002353 // can occur. However, we do pay attention to whether it is a bit-field
2354 // to decide whether we're actually binding to a temporary created from
2355 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002356 if (DerivedToBase)
2357 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002358 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002359 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002360 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002361 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002362 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002363 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002364 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002365 return;
2366 }
2367
2368 // - has a class type (i.e., T2 is a class type), where T1 is not
2369 // reference-related to T2, and can be implicitly converted to an
2370 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2371 // with "cv3 T3" (this conversion is selected by enumerating the
2372 // applicable conversion functions (13.3.1.6) and choosing the best
2373 // one through overload resolution (13.3)),
2374 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2375 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2376 Initializer,
2377 /*AllowRValues=*/false,
2378 Sequence);
2379 if (ConvOvlResult == OR_Success)
2380 return;
John McCall1d318332010-01-12 00:44:57 +00002381 if (ConvOvlResult != OR_No_Viable_Function) {
2382 Sequence.SetOverloadFailure(
2383 InitializationSequence::FK_ReferenceInitOverloadFailed,
2384 ConvOvlResult);
2385 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002386 }
2387 }
2388
2389 // - Otherwise, the reference shall be an lvalue reference to a
2390 // non-volatile const type (i.e., cv1 shall be const), or the reference
2391 // shall be an rvalue reference and the initializer expression shall
2392 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002393 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002394 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2395 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2396 Sequence.SetOverloadFailure(
2397 InitializationSequence::FK_ReferenceInitOverloadFailed,
2398 ConvOvlResult);
2399 else if (isLValueRef)
2400 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2401 ? (RefRelationship == Sema::Ref_Related
2402 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2403 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2404 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2405 else
2406 Sequence.SetFailed(
2407 InitializationSequence::FK_RValueReferenceBindingToLValue);
2408
2409 return;
2410 }
2411
2412 // - If T1 and T2 are class types and
2413 if (T1->isRecordType() && T2->isRecordType()) {
2414 // - the initializer expression is an rvalue and "cv1 T1" is
2415 // reference-compatible with "cv2 T2", or
2416 if (InitLvalue != Expr::LV_Valid &&
2417 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2418 if (DerivedToBase)
2419 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002420 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002421 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002422 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002423 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2424 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2425 return;
2426 }
2427
2428 // - T1 is not reference-related to T2 and the initializer expression
2429 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2430 // conversion is selected by enumerating the applicable conversion
2431 // functions (13.3.1.6) and choosing the best one through overload
2432 // resolution (13.3)),
2433 if (RefRelationship == Sema::Ref_Incompatible) {
2434 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2435 Kind, Initializer,
2436 /*AllowRValues=*/true,
2437 Sequence);
2438 if (ConvOvlResult)
2439 Sequence.SetOverloadFailure(
2440 InitializationSequence::FK_ReferenceInitOverloadFailed,
2441 ConvOvlResult);
2442
2443 return;
2444 }
2445
2446 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2447 return;
2448 }
2449
2450 // - If the initializer expression is an rvalue, with T2 an array type,
2451 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2452 // is bound to the object represented by the rvalue (see 3.10).
2453 // FIXME: How can an array type be reference-compatible with anything?
2454 // Don't we mean the element types of T1 and T2?
2455
2456 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2457 // from the initializer expression using the rules for a non-reference
2458 // copy initialization (8.5). The reference is then bound to the
2459 // temporary. [...]
2460 // Determine whether we are allowed to call explicit constructors or
2461 // explicit conversion operators.
2462 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2463 ImplicitConversionSequence ICS
2464 = S.TryImplicitConversion(Initializer, cv1T1,
2465 /*SuppressUserConversions=*/false, AllowExplicit,
2466 /*ForceRValue=*/false,
2467 /*FIXME:InOverloadResolution=*/false,
2468 /*UserCast=*/Kind.isExplicitCast());
2469
John McCall1d318332010-01-12 00:44:57 +00002470 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 // FIXME: Use the conversion function set stored in ICS to turn
2472 // this into an overloading ambiguity diagnostic. However, we need
2473 // to keep that set as an OverloadCandidateSet rather than as some
2474 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002475 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2476 Sequence.SetOverloadFailure(
2477 InitializationSequence::FK_ReferenceInitOverloadFailed,
2478 ConvOvlResult);
2479 else
2480 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002481 return;
2482 }
2483
2484 // [...] If T1 is reference-related to T2, cv1 must be the
2485 // same cv-qualification as, or greater cv-qualification
2486 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002487 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2488 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002489 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002490 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002491 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2492 return;
2493 }
2494
2495 // Perform the actual conversion.
2496 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2497 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2498 return;
2499}
2500
2501/// \brief Attempt character array initialization from a string literal
2502/// (C++ [dcl.init.string], C99 6.7.8).
2503static void TryStringLiteralInitialization(Sema &S,
2504 const InitializedEntity &Entity,
2505 const InitializationKind &Kind,
2506 Expr *Initializer,
2507 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002508 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002509 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002510}
2511
Douglas Gregor20093b42009-12-09 23:02:17 +00002512/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2513/// enumerates the constructors of the initialized entity and performs overload
2514/// resolution to select the best.
2515static void TryConstructorInitialization(Sema &S,
2516 const InitializedEntity &Entity,
2517 const InitializationKind &Kind,
2518 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002519 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002520 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002521 if (Kind.getKind() == InitializationKind::IK_Copy)
2522 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2523 else
2524 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002525
2526 // Build the candidate set directly in the initialization sequence
2527 // structure, so that it will persist if we fail.
2528 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2529 CandidateSet.clear();
2530
2531 // Determine whether we are allowed to call explicit constructors or
2532 // explicit conversion operators.
2533 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2534 Kind.getKind() == InitializationKind::IK_Value ||
2535 Kind.getKind() == InitializationKind::IK_Default);
2536
2537 // The type we're converting to is a class type. Enumerate its constructors
2538 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002539 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2540 assert(DestRecordType && "Constructor initialization requires record type");
2541 CXXRecordDecl *DestRecordDecl
2542 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2543
2544 DeclarationName ConstructorName
2545 = S.Context.DeclarationNames.getCXXConstructorName(
2546 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2547 DeclContext::lookup_iterator Con, ConEnd;
2548 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2549 Con != ConEnd; ++Con) {
2550 // Find the constructor (which may be a template).
2551 CXXConstructorDecl *Constructor = 0;
2552 FunctionTemplateDecl *ConstructorTmpl
2553 = dyn_cast<FunctionTemplateDecl>(*Con);
2554 if (ConstructorTmpl)
2555 Constructor = cast<CXXConstructorDecl>(
2556 ConstructorTmpl->getTemplatedDecl());
2557 else
2558 Constructor = cast<CXXConstructorDecl>(*Con);
2559
2560 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002561 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002562 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002563 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2564 ConstructorTmpl->getAccess(),
2565 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002566 Args, NumArgs, CandidateSet);
2567 else
John McCall86820f52010-01-26 01:37:31 +00002568 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2569 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002570 }
2571 }
2572
2573 SourceLocation DeclLoc = Kind.getLocation();
2574
2575 // Perform overload resolution. If it fails, return the failed result.
2576 OverloadCandidateSet::iterator Best;
2577 if (OverloadingResult Result
2578 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2579 Sequence.SetOverloadFailure(
2580 InitializationSequence::FK_ConstructorOverloadFailed,
2581 Result);
2582 return;
2583 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002584
2585 // C++0x [dcl.init]p6:
2586 // If a program calls for the default initialization of an object
2587 // of a const-qualified type T, T shall be a class type with a
2588 // user-provided default constructor.
2589 if (Kind.getKind() == InitializationKind::IK_Default &&
2590 Entity.getType().isConstQualified() &&
2591 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2592 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2593 return;
2594 }
2595
Douglas Gregor51c56d62009-12-14 20:49:26 +00002596 // Add the constructor initialization step. Any cv-qualification conversion is
2597 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002598 if (Kind.getKind() == InitializationKind::IK_Copy) {
John McCallb13b7372010-02-01 03:16:54 +00002599 Sequence.AddUserConversionStep(Best->Function, Best->getAccess(), DestType);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002600 } else {
2601 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002602 cast<CXXConstructorDecl>(Best->Function),
John McCallb13b7372010-02-01 03:16:54 +00002603 Best->getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002604 DestType);
2605 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002606}
2607
Douglas Gregor71d17402009-12-15 00:01:57 +00002608/// \brief Attempt value initialization (C++ [dcl.init]p7).
2609static void TryValueInitialization(Sema &S,
2610 const InitializedEntity &Entity,
2611 const InitializationKind &Kind,
2612 InitializationSequence &Sequence) {
2613 // C++ [dcl.init]p5:
2614 //
2615 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002616 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002617
2618 // -- if T is an array type, then each element is value-initialized;
2619 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2620 T = AT->getElementType();
2621
2622 if (const RecordType *RT = T->getAs<RecordType>()) {
2623 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2624 // -- if T is a class type (clause 9) with a user-declared
2625 // constructor (12.1), then the default constructor for T is
2626 // called (and the initialization is ill-formed if T has no
2627 // accessible default constructor);
2628 //
2629 // FIXME: we really want to refer to a single subobject of the array,
2630 // but Entity doesn't have a way to capture that (yet).
2631 if (ClassDecl->hasUserDeclaredConstructor())
2632 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2633
Douglas Gregor16006c92009-12-16 18:50:27 +00002634 // -- if T is a (possibly cv-qualified) non-union class type
2635 // without a user-provided constructor, then the object is
2636 // zero-initialized and, if T’s implicitly-declared default
2637 // constructor is non-trivial, that constructor is called.
2638 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2639 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2640 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002641 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002642 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2643 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002644 }
2645 }
2646
Douglas Gregord6542d82009-12-22 15:35:07 +00002647 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002648 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2649}
2650
Douglas Gregor99a2e602009-12-16 01:38:02 +00002651/// \brief Attempt default initialization (C++ [dcl.init]p6).
2652static void TryDefaultInitialization(Sema &S,
2653 const InitializedEntity &Entity,
2654 const InitializationKind &Kind,
2655 InitializationSequence &Sequence) {
2656 assert(Kind.getKind() == InitializationKind::IK_Default);
2657
2658 // C++ [dcl.init]p6:
2659 // To default-initialize an object of type T means:
2660 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002661 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002662 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2663 DestType = Array->getElementType();
2664
2665 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2666 // constructor for T is called (and the initialization is ill-formed if
2667 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002668 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002669 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2670 Sequence);
2671 }
2672
2673 // - otherwise, no initialization is performed.
2674 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2675
2676 // If a program calls for the default initialization of an object of
2677 // a const-qualified type T, T shall be a class type with a user-provided
2678 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002679 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002680 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2681}
2682
Douglas Gregor20093b42009-12-09 23:02:17 +00002683/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2684/// which enumerates all conversion functions and performs overload resolution
2685/// to select the best.
2686static void TryUserDefinedConversion(Sema &S,
2687 const InitializedEntity &Entity,
2688 const InitializationKind &Kind,
2689 Expr *Initializer,
2690 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002691 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2692
Douglas Gregord6542d82009-12-22 15:35:07 +00002693 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002694 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2695 QualType SourceType = Initializer->getType();
2696 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2697 "Must have a class type to perform a user-defined conversion");
2698
2699 // Build the candidate set directly in the initialization sequence
2700 // structure, so that it will persist if we fail.
2701 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2702 CandidateSet.clear();
2703
2704 // Determine whether we are allowed to call explicit constructors or
2705 // explicit conversion operators.
2706 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2707
2708 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2709 // The type we're converting to is a class type. Enumerate its constructors
2710 // to see if there is a suitable conversion.
2711 CXXRecordDecl *DestRecordDecl
2712 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2713
2714 DeclarationName ConstructorName
2715 = S.Context.DeclarationNames.getCXXConstructorName(
2716 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2717 DeclContext::lookup_iterator Con, ConEnd;
2718 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2719 Con != ConEnd; ++Con) {
2720 // Find the constructor (which may be a template).
2721 CXXConstructorDecl *Constructor = 0;
2722 FunctionTemplateDecl *ConstructorTmpl
2723 = dyn_cast<FunctionTemplateDecl>(*Con);
2724 if (ConstructorTmpl)
2725 Constructor = cast<CXXConstructorDecl>(
2726 ConstructorTmpl->getTemplatedDecl());
2727 else
2728 Constructor = cast<CXXConstructorDecl>(*Con);
2729
2730 if (!Constructor->isInvalidDecl() &&
2731 Constructor->isConvertingConstructor(AllowExplicit)) {
2732 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002733 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2734 ConstructorTmpl->getAccess(),
2735 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002736 &Initializer, 1, CandidateSet);
2737 else
John McCall86820f52010-01-26 01:37:31 +00002738 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2739 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002740 }
2741 }
2742 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002743
2744 SourceLocation DeclLoc = Initializer->getLocStart();
2745
Douglas Gregor4a520a22009-12-14 17:27:33 +00002746 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2747 // The type we're converting from is a class type, enumerate its conversion
2748 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002749
Eli Friedman33c2da92009-12-20 22:12:03 +00002750 // We can only enumerate the conversion functions for a complete type; if
2751 // the type isn't complete, simply skip this step.
2752 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2753 CXXRecordDecl *SourceRecordDecl
2754 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002755
John McCalleec51cf2010-01-20 00:46:10 +00002756 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002757 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002758 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002759 E = Conversions->end();
2760 I != E; ++I) {
2761 NamedDecl *D = *I;
2762 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2763 if (isa<UsingShadowDecl>(D))
2764 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2765
2766 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2767 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002768 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002769 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002770 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002771 Conv = cast<CXXConversionDecl>(*I);
2772
2773 if (AllowExplicit || !Conv->isExplicit()) {
2774 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002775 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2776 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002777 CandidateSet);
2778 else
John McCall86820f52010-01-26 01:37:31 +00002779 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2780 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002781 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002782 }
2783 }
2784 }
2785
Douglas Gregor4a520a22009-12-14 17:27:33 +00002786 // Perform overload resolution. If it fails, return the failed result.
2787 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002788 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002789 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2790 Sequence.SetOverloadFailure(
2791 InitializationSequence::FK_UserConversionOverloadFailed,
2792 Result);
2793 return;
2794 }
John McCall1d318332010-01-12 00:44:57 +00002795
Douglas Gregor4a520a22009-12-14 17:27:33 +00002796 FunctionDecl *Function = Best->Function;
2797
2798 if (isa<CXXConstructorDecl>(Function)) {
2799 // Add the user-defined conversion step. Any cv-qualification conversion is
2800 // subsumed by the initialization.
John McCallb13b7372010-02-01 03:16:54 +00002801 Sequence.AddUserConversionStep(Function, Best->getAccess(), DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002802 return;
2803 }
2804
2805 // Add the user-defined conversion step that calls the conversion function.
2806 QualType ConvType = Function->getResultType().getNonReferenceType();
John McCallb13b7372010-02-01 03:16:54 +00002807 Sequence.AddUserConversionStep(Function, Best->getAccess(), ConvType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002808
2809 // If the conversion following the call to the conversion function is
2810 // interesting, add it as a separate step.
2811 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2812 Best->FinalConversion.Third) {
2813 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002814 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002815 ICS.Standard = Best->FinalConversion;
2816 Sequence.AddConversionSequenceStep(ICS, DestType);
2817 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002818}
2819
2820/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2821/// non-class type to another.
2822static void TryImplicitConversion(Sema &S,
2823 const InitializedEntity &Entity,
2824 const InitializationKind &Kind,
2825 Expr *Initializer,
2826 InitializationSequence &Sequence) {
2827 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002828 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002829 /*SuppressUserConversions=*/true,
2830 /*AllowExplicit=*/false,
2831 /*ForceRValue=*/false,
2832 /*FIXME:InOverloadResolution=*/false,
2833 /*UserCast=*/Kind.isExplicitCast());
2834
John McCall1d318332010-01-12 00:44:57 +00002835 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002836 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2837 return;
2838 }
2839
Douglas Gregord6542d82009-12-22 15:35:07 +00002840 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002841}
2842
2843InitializationSequence::InitializationSequence(Sema &S,
2844 const InitializedEntity &Entity,
2845 const InitializationKind &Kind,
2846 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002847 unsigned NumArgs)
2848 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002849 ASTContext &Context = S.Context;
2850
2851 // C++0x [dcl.init]p16:
2852 // The semantics of initializers are as follows. The destination type is
2853 // the type of the object or reference being initialized and the source
2854 // type is the type of the initializer expression. The source type is not
2855 // defined when the initializer is a braced-init-list or when it is a
2856 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002857 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002858
2859 if (DestType->isDependentType() ||
2860 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2861 SequenceKind = DependentSequence;
2862 return;
2863 }
2864
2865 QualType SourceType;
2866 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002867 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002868 Initializer = Args[0];
2869 if (!isa<InitListExpr>(Initializer))
2870 SourceType = Initializer->getType();
2871 }
2872
2873 // - If the initializer is a braced-init-list, the object is
2874 // list-initialized (8.5.4).
2875 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2876 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002877 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002878 }
2879
2880 // - If the destination type is a reference type, see 8.5.3.
2881 if (DestType->isReferenceType()) {
2882 // C++0x [dcl.init.ref]p1:
2883 // A variable declared to be a T& or T&&, that is, "reference to type T"
2884 // (8.3.2), shall be initialized by an object, or function, of type T or
2885 // by an object that can be converted into a T.
2886 // (Therefore, multiple arguments are not permitted.)
2887 if (NumArgs != 1)
2888 SetFailed(FK_TooManyInitsForReference);
2889 else
2890 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2891 return;
2892 }
2893
2894 // - If the destination type is an array of characters, an array of
2895 // char16_t, an array of char32_t, or an array of wchar_t, and the
2896 // initializer is a string literal, see 8.5.2.
2897 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2898 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2899 return;
2900 }
2901
2902 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002903 if (Kind.getKind() == InitializationKind::IK_Value ||
2904 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002905 TryValueInitialization(S, Entity, Kind, *this);
2906 return;
2907 }
2908
Douglas Gregor99a2e602009-12-16 01:38:02 +00002909 // Handle default initialization.
2910 if (Kind.getKind() == InitializationKind::IK_Default){
2911 TryDefaultInitialization(S, Entity, Kind, *this);
2912 return;
2913 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002914
Douglas Gregor20093b42009-12-09 23:02:17 +00002915 // - Otherwise, if the destination type is an array, the program is
2916 // ill-formed.
2917 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2918 if (AT->getElementType()->isAnyCharacterType())
2919 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2920 else
2921 SetFailed(FK_ArrayNeedsInitList);
2922
2923 return;
2924 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002925
2926 // Handle initialization in C
2927 if (!S.getLangOptions().CPlusPlus) {
2928 setSequenceKind(CAssignment);
2929 AddCAssignmentStep(DestType);
2930 return;
2931 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002932
2933 // - If the destination type is a (possibly cv-qualified) class type:
2934 if (DestType->isRecordType()) {
2935 // - If the initialization is direct-initialization, or if it is
2936 // copy-initialization where the cv-unqualified version of the
2937 // source type is the same class as, or a derived class of, the
2938 // class of the destination, constructors are considered. [...]
2939 if (Kind.getKind() == InitializationKind::IK_Direct ||
2940 (Kind.getKind() == InitializationKind::IK_Copy &&
2941 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2942 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002943 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002944 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002945 // - Otherwise (i.e., for the remaining copy-initialization cases),
2946 // user-defined conversion sequences that can convert from the source
2947 // type to the destination type or (when a conversion function is
2948 // used) to a derived class thereof are enumerated as described in
2949 // 13.3.1.4, and the best one is chosen through overload resolution
2950 // (13.3).
2951 else
2952 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2953 return;
2954 }
2955
Douglas Gregor99a2e602009-12-16 01:38:02 +00002956 if (NumArgs > 1) {
2957 SetFailed(FK_TooManyInitsForScalar);
2958 return;
2959 }
2960 assert(NumArgs == 1 && "Zero-argument case handled above");
2961
Douglas Gregor20093b42009-12-09 23:02:17 +00002962 // - Otherwise, if the source type is a (possibly cv-qualified) class
2963 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002964 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002965 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2966 return;
2967 }
2968
2969 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002970 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002971 // conversions (Clause 4) will be used, if necessary, to convert the
2972 // initializer expression to the cv-unqualified version of the
2973 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002974 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002975 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2976}
2977
2978InitializationSequence::~InitializationSequence() {
2979 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2980 StepEnd = Steps.end();
2981 Step != StepEnd; ++Step)
2982 Step->Destroy();
2983}
2984
2985//===----------------------------------------------------------------------===//
2986// Perform initialization
2987//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002988static Sema::AssignmentAction
2989getAssignmentAction(const InitializedEntity &Entity) {
2990 switch(Entity.getKind()) {
2991 case InitializedEntity::EK_Variable:
2992 case InitializedEntity::EK_New:
2993 return Sema::AA_Initializing;
2994
2995 case InitializedEntity::EK_Parameter:
2996 // FIXME: Can we tell when we're sending vs. passing?
2997 return Sema::AA_Passing;
2998
2999 case InitializedEntity::EK_Result:
3000 return Sema::AA_Returning;
3001
3002 case InitializedEntity::EK_Exception:
3003 case InitializedEntity::EK_Base:
3004 llvm_unreachable("No assignment action for C++-specific initialization");
3005 break;
3006
3007 case InitializedEntity::EK_Temporary:
3008 // FIXME: Can we tell apart casting vs. converting?
3009 return Sema::AA_Casting;
3010
3011 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003012 case InitializedEntity::EK_ArrayElement:
3013 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003014 return Sema::AA_Initializing;
3015 }
3016
3017 return Sema::AA_Converting;
3018}
3019
3020static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3021 bool IsCopy) {
3022 switch (Entity.getKind()) {
3023 case InitializedEntity::EK_Result:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003024 case InitializedEntity::EK_ArrayElement:
3025 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003026 return !IsCopy;
3027
3028 case InitializedEntity::EK_New:
3029 case InitializedEntity::EK_Variable:
3030 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003031 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003032 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003033 return false;
3034
3035 case InitializedEntity::EK_Parameter:
3036 case InitializedEntity::EK_Temporary:
3037 return true;
3038 }
3039
3040 llvm_unreachable("missed an InitializedEntity kind?");
3041}
3042
3043/// \brief If we need to perform an additional copy of the initialized object
3044/// for this kind of entity (e.g., the result of a function or an object being
3045/// thrown), make the copy.
3046static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3047 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003048 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003049 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003050 Expr *CurInitExpr = (Expr *)CurInit.get();
3051
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003052 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003053
3054 switch (Entity.getKind()) {
3055 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003056 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003057 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003058 Loc = Entity.getReturnLoc();
3059 break;
3060
3061 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003062 Loc = Entity.getThrowLoc();
3063 break;
3064
3065 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003066 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003067 Kind.getKind() != InitializationKind::IK_Copy)
3068 return move(CurInit);
3069 Loc = Entity.getDecl()->getLocation();
3070 break;
3071
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003072 case InitializedEntity::EK_ArrayElement:
3073 case InitializedEntity::EK_Member:
3074 if (Entity.getType()->isReferenceType() ||
3075 Kind.getKind() != InitializationKind::IK_Copy)
3076 return move(CurInit);
3077 Loc = CurInitExpr->getLocStart();
3078 break;
3079
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003080 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003081 // FIXME: Do we need this initialization for a parameter?
3082 return move(CurInit);
3083
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003084 case InitializedEntity::EK_New:
3085 case InitializedEntity::EK_Temporary:
3086 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003087 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003088 // We don't need to copy for any of these initialized entities.
3089 return move(CurInit);
3090 }
3091
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003092 CXXRecordDecl *Class = 0;
3093 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3094 Class = cast<CXXRecordDecl>(Record->getDecl());
3095 if (!Class)
3096 return move(CurInit);
3097
3098 // Perform overload resolution using the class's copy constructors.
3099 DeclarationName ConstructorName
3100 = S.Context.DeclarationNames.getCXXConstructorName(
3101 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3102 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003103 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003104 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3105 Con != ConEnd; ++Con) {
3106 // Find the constructor (which may be a template).
3107 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3108 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003109 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003110 continue;
3111
John McCall86820f52010-01-26 01:37:31 +00003112 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3113 &CurInitExpr, 1, CandidateSet);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003114 }
3115
3116 OverloadCandidateSet::iterator Best;
3117 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3118 case OR_Success:
3119 break;
3120
3121 case OR_No_Viable_Function:
3122 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003123 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003124 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003125 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3126 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003127 return S.ExprError();
3128
3129 case OR_Ambiguous:
3130 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003131 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003132 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003133 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3134 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003135 return S.ExprError();
3136
3137 case OR_Deleted:
3138 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003139 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003140 << CurInitExpr->getSourceRange();
3141 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3142 << Best->Function->isDeleted();
3143 return S.ExprError();
3144 }
3145
3146 CurInit.release();
3147 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3148 cast<CXXConstructorDecl>(Best->Function),
3149 /*Elidable=*/true,
3150 Sema::MultiExprArg(S,
3151 (void**)&CurInitExpr, 1));
3152}
Douglas Gregor20093b42009-12-09 23:02:17 +00003153
3154Action::OwningExprResult
3155InitializationSequence::Perform(Sema &S,
3156 const InitializedEntity &Entity,
3157 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003158 Action::MultiExprArg Args,
3159 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003160 if (SequenceKind == FailedSequence) {
3161 unsigned NumArgs = Args.size();
3162 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3163 return S.ExprError();
3164 }
3165
3166 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003167 // If the declaration is a non-dependent, incomplete array type
3168 // that has an initializer, then its type will be completed once
3169 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003170 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003171 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003172 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003173 if (const IncompleteArrayType *ArrayT
3174 = S.Context.getAsIncompleteArrayType(DeclType)) {
3175 // FIXME: We don't currently have the ability to accurately
3176 // compute the length of an initializer list without
3177 // performing full type-checking of the initializer list
3178 // (since we have to determine where braces are implicitly
3179 // introduced and such). So, we fall back to making the array
3180 // type a dependently-sized array type with no specified
3181 // bound.
3182 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3183 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003184
Douglas Gregord87b61f2009-12-10 17:56:55 +00003185 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003186 if (DeclaratorDecl *DD = Entity.getDecl()) {
3187 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3188 TypeLoc TL = TInfo->getTypeLoc();
3189 if (IncompleteArrayTypeLoc *ArrayLoc
3190 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3191 Brackets = ArrayLoc->getBracketsRange();
3192 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003193 }
3194
3195 *ResultType
3196 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3197 /*NumElts=*/0,
3198 ArrayT->getSizeModifier(),
3199 ArrayT->getIndexTypeCVRQualifiers(),
3200 Brackets);
3201 }
3202
3203 }
3204 }
3205
Eli Friedman08544622009-12-22 02:35:53 +00003206 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003207 return Sema::OwningExprResult(S, Args.release()[0]);
3208
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003209 if (Args.size() == 0)
3210 return S.Owned((Expr *)0);
3211
Douglas Gregor20093b42009-12-09 23:02:17 +00003212 unsigned NumArgs = Args.size();
3213 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3214 SourceLocation(),
3215 (Expr **)Args.release(),
3216 NumArgs,
3217 SourceLocation()));
3218 }
3219
Douglas Gregor99a2e602009-12-16 01:38:02 +00003220 if (SequenceKind == NoInitialization)
3221 return S.Owned((Expr *)0);
3222
Douglas Gregord6542d82009-12-22 15:35:07 +00003223 QualType DestType = Entity.getType().getNonReferenceType();
3224 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003225 // the same as Entity.getDecl()->getType() in cases involving type merging,
3226 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003227 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003228 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003229 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003230
Douglas Gregor99a2e602009-12-16 01:38:02 +00003231 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3232
3233 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3234
3235 // For initialization steps that start with a single initializer,
3236 // grab the only argument out the Args and place it into the "current"
3237 // initializer.
3238 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003239 case SK_ResolveAddressOfOverloadedFunction:
3240 case SK_CastDerivedToBaseRValue:
3241 case SK_CastDerivedToBaseLValue:
3242 case SK_BindReference:
3243 case SK_BindReferenceToTemporary:
3244 case SK_UserConversion:
3245 case SK_QualificationConversionLValue:
3246 case SK_QualificationConversionRValue:
3247 case SK_ConversionSequence:
3248 case SK_ListInitialization:
3249 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003250 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003251 assert(Args.size() == 1);
3252 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3253 if (CurInit.isInvalid())
3254 return S.ExprError();
3255 break;
3256
3257 case SK_ConstructorInitialization:
3258 case SK_ZeroInitialization:
3259 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003260 }
3261
3262 // Walk through the computed steps for the initialization sequence,
3263 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003264 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003265 for (step_iterator Step = step_begin(), StepEnd = step_end();
3266 Step != StepEnd; ++Step) {
3267 if (CurInit.isInvalid())
3268 return S.ExprError();
3269
3270 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003271 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003272
3273 switch (Step->Kind) {
3274 case SK_ResolveAddressOfOverloadedFunction:
3275 // Overload resolution determined which function invoke; update the
3276 // initializer to reflect that choice.
John McCallb13b7372010-02-01 03:16:54 +00003277 // Access control was done in overload resolution.
3278 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
3279 cast<FunctionDecl>(Step->Function.getDecl()));
Douglas Gregor20093b42009-12-09 23:02:17 +00003280 break;
3281
3282 case SK_CastDerivedToBaseRValue:
3283 case SK_CastDerivedToBaseLValue: {
3284 // We have a derived-to-base cast that produces either an rvalue or an
3285 // lvalue. Perform that cast.
3286
3287 // Casts to inaccessible base classes are allowed with C-style casts.
3288 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3289 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3290 CurInitExpr->getLocStart(),
3291 CurInitExpr->getSourceRange(),
3292 IgnoreBaseAccess))
3293 return S.ExprError();
3294
3295 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3296 CastExpr::CK_DerivedToBase,
3297 (Expr*)CurInit.release(),
3298 Step->Kind == SK_CastDerivedToBaseLValue));
3299 break;
3300 }
3301
3302 case SK_BindReference:
3303 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3304 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3305 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003306 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 << BitField->getDeclName()
3308 << CurInitExpr->getSourceRange();
3309 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3310 return S.ExprError();
3311 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003312
Anders Carlsson09380262010-01-31 17:18:49 +00003313 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003314 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003315 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3316 << Entity.getType().isVolatileQualified()
3317 << CurInitExpr->getSourceRange();
3318 return S.ExprError();
3319 }
3320
Douglas Gregor20093b42009-12-09 23:02:17 +00003321 // Reference binding does not have any corresponding ASTs.
3322
3323 // Check exception specifications
3324 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3325 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003326
Douglas Gregor20093b42009-12-09 23:02:17 +00003327 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003328
Douglas Gregor20093b42009-12-09 23:02:17 +00003329 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003330 // Reference binding does not have any corresponding ASTs.
3331
Douglas Gregor20093b42009-12-09 23:02:17 +00003332 // Check exception specifications
3333 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3334 return S.ExprError();
3335
Douglas Gregor20093b42009-12-09 23:02:17 +00003336 break;
3337
3338 case SK_UserConversion: {
3339 // We have a user-defined conversion that invokes either a constructor
3340 // or a conversion function.
3341 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003342 bool IsCopy = false;
John McCallb13b7372010-02-01 03:16:54 +00003343 FunctionDecl *Fn = cast<FunctionDecl>(Step->Function.getDecl());
3344 AccessSpecifier FnAccess = Step->Function.getAccess();
3345 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 // Build a call to the selected constructor.
3347 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3348 SourceLocation Loc = CurInitExpr->getLocStart();
3349 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003350
Douglas Gregor20093b42009-12-09 23:02:17 +00003351 // Determine the arguments required to actually perform the constructor
3352 // call.
3353 if (S.CompleteConstructorCall(Constructor,
3354 Sema::MultiExprArg(S,
3355 (void **)&CurInitExpr,
3356 1),
3357 Loc, ConstructorArgs))
3358 return S.ExprError();
3359
3360 // Build the an expression that constructs a temporary.
3361 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3362 move_arg(ConstructorArgs));
3363 if (CurInit.isInvalid())
3364 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003365
3366 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FnAccess);
Douglas Gregor20093b42009-12-09 23:02:17 +00003367
3368 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003369 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3370 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3371 S.IsDerivedFrom(SourceType, Class))
3372 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003373 } else {
3374 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003375 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003376
John McCallb13b7372010-02-01 03:16:54 +00003377 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr,
3378 Conversion, FnAccess);
3379
Douglas Gregor20093b42009-12-09 23:02:17 +00003380 // FIXME: Should we move this initialization into a separate
3381 // derived-to-base conversion? I believe the answer is "no", because
3382 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003383 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
3384 Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 return S.ExprError();
3386
3387 // Do a little dance to make sure that CurInit has the proper
3388 // pointer.
3389 CurInit.release();
3390
3391 // Build the actual call to the conversion function.
3392 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3393 if (CurInit.isInvalid() || !CurInit.get())
3394 return S.ExprError();
3395
3396 CastKind = CastExpr::CK_UserDefinedConversion;
3397 }
3398
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003399 if (shouldBindAsTemporary(Entity, IsCopy))
3400 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3401
Douglas Gregor20093b42009-12-09 23:02:17 +00003402 CurInitExpr = CurInit.takeAs<Expr>();
3403 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3404 CastKind,
3405 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003406 false));
3407
3408 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003409 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003410 break;
3411 }
3412
3413 case SK_QualificationConversionLValue:
3414 case SK_QualificationConversionRValue:
3415 // Perform a qualification conversion; these can never go wrong.
3416 S.ImpCastExprToType(CurInitExpr, Step->Type,
3417 CastExpr::CK_NoOp,
3418 Step->Kind == SK_QualificationConversionLValue);
3419 CurInit.release();
3420 CurInit = S.Owned(CurInitExpr);
3421 break;
3422
3423 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003424 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003425 false, false, *Step->ICS))
3426 return S.ExprError();
3427
3428 CurInit.release();
3429 CurInit = S.Owned(CurInitExpr);
3430 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003431
3432 case SK_ListInitialization: {
3433 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3434 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003435 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003436 return S.ExprError();
3437
3438 CurInit.release();
3439 CurInit = S.Owned(InitList);
3440 break;
3441 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003442
3443 case SK_ConstructorInitialization: {
3444 CXXConstructorDecl *Constructor
John McCallb13b7372010-02-01 03:16:54 +00003445 = cast<CXXConstructorDecl>(Step->Function.getDecl());
3446
Douglas Gregor51c56d62009-12-14 20:49:26 +00003447 // Build a call to the selected constructor.
3448 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3449 SourceLocation Loc = Kind.getLocation();
3450
3451 // Determine the arguments required to actually perform the constructor
3452 // call.
3453 if (S.CompleteConstructorCall(Constructor, move(Args),
3454 Loc, ConstructorArgs))
3455 return S.ExprError();
3456
3457 // Build the an expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003458 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3459 (Kind.getKind() == InitializationKind::IK_Direct ||
3460 Kind.getKind() == InitializationKind::IK_Value)) {
3461 // An explicitly-constructed temporary, e.g., X(1, 2).
3462 unsigned NumExprs = ConstructorArgs.size();
3463 Expr **Exprs = (Expr **)ConstructorArgs.take();
3464 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3465 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3466 Constructor,
3467 Entity.getType(),
3468 Kind.getLocation(),
3469 Exprs,
3470 NumExprs,
3471 Kind.getParenRange().getEnd()));
3472 } else
3473 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3474 Constructor,
3475 move_arg(ConstructorArgs),
3476 ConstructorInitRequiresZeroInit,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003477 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003478 if (CurInit.isInvalid())
3479 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003480
3481 // Only check access if all of that succeeded.
3482 S.CheckConstructorAccess(Loc, Constructor, Step->Function.getAccess());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003483
3484 bool Elidable
3485 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3486 if (shouldBindAsTemporary(Entity, Elidable))
3487 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3488
3489 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003490 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003491 break;
3492 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003493
3494 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003495 step_iterator NextStep = Step;
3496 ++NextStep;
3497 if (NextStep != StepEnd &&
3498 NextStep->Kind == SK_ConstructorInitialization) {
3499 // The need for zero-initialization is recorded directly into
3500 // the call to the object's constructor within the next step.
3501 ConstructorInitRequiresZeroInit = true;
3502 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3503 S.getLangOptions().CPlusPlus &&
3504 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003505 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3506 Kind.getRange().getBegin(),
3507 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003508 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003509 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003510 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003511 break;
3512 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003513
3514 case SK_CAssignment: {
3515 QualType SourceType = CurInitExpr->getType();
3516 Sema::AssignConvertType ConvTy =
3517 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003518
3519 // If this is a call, allow conversion to a transparent union.
3520 if (ConvTy != Sema::Compatible &&
3521 Entity.getKind() == InitializedEntity::EK_Parameter &&
3522 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3523 == Sema::Compatible)
3524 ConvTy = Sema::Compatible;
3525
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003526 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3527 Step->Type, SourceType,
3528 CurInitExpr, getAssignmentAction(Entity)))
3529 return S.ExprError();
3530
3531 CurInit.release();
3532 CurInit = S.Owned(CurInitExpr);
3533 break;
3534 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003535
3536 case SK_StringInit: {
3537 QualType Ty = Step->Type;
3538 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3539 break;
3540 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003541 }
3542 }
3543
3544 return move(CurInit);
3545}
3546
3547//===----------------------------------------------------------------------===//
3548// Diagnose initialization failures
3549//===----------------------------------------------------------------------===//
3550bool InitializationSequence::Diagnose(Sema &S,
3551 const InitializedEntity &Entity,
3552 const InitializationKind &Kind,
3553 Expr **Args, unsigned NumArgs) {
3554 if (SequenceKind != FailedSequence)
3555 return false;
3556
Douglas Gregord6542d82009-12-22 15:35:07 +00003557 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003558 switch (Failure) {
3559 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003560 // FIXME: Customize for the initialized entity?
3561 if (NumArgs == 0)
3562 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3563 << DestType.getNonReferenceType();
3564 else // FIXME: diagnostic below could be better!
3565 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3566 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003567 break;
3568
3569 case FK_ArrayNeedsInitList:
3570 case FK_ArrayNeedsInitListOrStringLiteral:
3571 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3572 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3573 break;
3574
3575 case FK_AddressOfOverloadFailed:
3576 S.ResolveAddressOfOverloadedFunction(Args[0],
3577 DestType.getNonReferenceType(),
3578 true);
3579 break;
3580
3581 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003582 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003583 switch (FailedOverloadResult) {
3584 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003585 if (Failure == FK_UserConversionOverloadFailed)
3586 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3587 << Args[0]->getType() << DestType
3588 << Args[0]->getSourceRange();
3589 else
3590 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3591 << DestType << Args[0]->getType()
3592 << Args[0]->getSourceRange();
3593
John McCallcbce6062010-01-12 07:18:19 +00003594 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3595 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 break;
3597
3598 case OR_No_Viable_Function:
3599 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3600 << Args[0]->getType() << DestType.getNonReferenceType()
3601 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003602 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3603 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003604 break;
3605
3606 case OR_Deleted: {
3607 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3608 << Args[0]->getType() << DestType.getNonReferenceType()
3609 << Args[0]->getSourceRange();
3610 OverloadCandidateSet::iterator Best;
3611 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3612 Kind.getLocation(),
3613 Best);
3614 if (Ovl == OR_Deleted) {
3615 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3616 << Best->Function->isDeleted();
3617 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003618 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003619 }
3620 break;
3621 }
3622
3623 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003624 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 break;
3626 }
3627 break;
3628
3629 case FK_NonConstLValueReferenceBindingToTemporary:
3630 case FK_NonConstLValueReferenceBindingToUnrelated:
3631 S.Diag(Kind.getLocation(),
3632 Failure == FK_NonConstLValueReferenceBindingToTemporary
3633 ? diag::err_lvalue_reference_bind_to_temporary
3634 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003635 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 << DestType.getNonReferenceType()
3637 << Args[0]->getType()
3638 << Args[0]->getSourceRange();
3639 break;
3640
3641 case FK_RValueReferenceBindingToLValue:
3642 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3643 << Args[0]->getSourceRange();
3644 break;
3645
3646 case FK_ReferenceInitDropsQualifiers:
3647 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3648 << DestType.getNonReferenceType()
3649 << Args[0]->getType()
3650 << Args[0]->getSourceRange();
3651 break;
3652
3653 case FK_ReferenceInitFailed:
3654 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3655 << DestType.getNonReferenceType()
3656 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3657 << Args[0]->getType()
3658 << Args[0]->getSourceRange();
3659 break;
3660
3661 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003662 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3663 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003664 << DestType
3665 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3666 << Args[0]->getType()
3667 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003668 break;
3669
3670 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003671 SourceRange R;
3672
3673 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3674 R = SourceRange(InitList->getInit(1)->getLocStart(),
3675 InitList->getLocEnd());
3676 else
3677 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003678
3679 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003680 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003681 break;
3682 }
3683
3684 case FK_ReferenceBindingToInitList:
3685 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3686 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3687 break;
3688
3689 case FK_InitListBadDestinationType:
3690 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3691 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3692 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003693
3694 case FK_ConstructorOverloadFailed: {
3695 SourceRange ArgsRange;
3696 if (NumArgs)
3697 ArgsRange = SourceRange(Args[0]->getLocStart(),
3698 Args[NumArgs - 1]->getLocEnd());
3699
3700 // FIXME: Using "DestType" for the entity we're printing is probably
3701 // bad.
3702 switch (FailedOverloadResult) {
3703 case OR_Ambiguous:
3704 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3705 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003706 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003707 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003708 break;
3709
3710 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003711 if (Kind.getKind() == InitializationKind::IK_Default &&
3712 (Entity.getKind() == InitializedEntity::EK_Base ||
3713 Entity.getKind() == InitializedEntity::EK_Member) &&
3714 isa<CXXConstructorDecl>(S.CurContext)) {
3715 // This is implicit default initialization of a member or
3716 // base within a constructor. If no viable function was
3717 // found, notify the user that she needs to explicitly
3718 // initialize this base/member.
3719 CXXConstructorDecl *Constructor
3720 = cast<CXXConstructorDecl>(S.CurContext);
3721 if (Entity.getKind() == InitializedEntity::EK_Base) {
3722 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3723 << Constructor->isImplicit()
3724 << S.Context.getTypeDeclType(Constructor->getParent())
3725 << /*base=*/0
3726 << Entity.getType();
3727
3728 RecordDecl *BaseDecl
3729 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3730 ->getDecl();
3731 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3732 << S.Context.getTagDeclType(BaseDecl);
3733 } else {
3734 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3735 << Constructor->isImplicit()
3736 << S.Context.getTypeDeclType(Constructor->getParent())
3737 << /*member=*/1
3738 << Entity.getName();
3739 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3740
3741 if (const RecordType *Record
3742 = Entity.getType()->getAs<RecordType>())
3743 S.Diag(Record->getDecl()->getLocation(),
3744 diag::note_previous_decl)
3745 << S.Context.getTagDeclType(Record->getDecl());
3746 }
3747 break;
3748 }
3749
Douglas Gregor51c56d62009-12-14 20:49:26 +00003750 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3751 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003752 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3753 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003754 break;
3755
3756 case OR_Deleted: {
3757 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3758 << true << DestType << ArgsRange;
3759 OverloadCandidateSet::iterator Best;
3760 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3761 Kind.getLocation(),
3762 Best);
3763 if (Ovl == OR_Deleted) {
3764 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3765 << Best->Function->isDeleted();
3766 } else {
3767 llvm_unreachable("Inconsistent overload resolution?");
3768 }
3769 break;
3770 }
3771
3772 case OR_Success:
3773 llvm_unreachable("Conversion did not fail!");
3774 break;
3775 }
3776 break;
3777 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003778
3779 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003780 if (Entity.getKind() == InitializedEntity::EK_Member &&
3781 isa<CXXConstructorDecl>(S.CurContext)) {
3782 // This is implicit default-initialization of a const member in
3783 // a constructor. Complain that it needs to be explicitly
3784 // initialized.
3785 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3786 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3787 << Constructor->isImplicit()
3788 << S.Context.getTypeDeclType(Constructor->getParent())
3789 << /*const=*/1
3790 << Entity.getName();
3791 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3792 << Entity.getName();
3793 } else {
3794 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3795 << DestType << (bool)DestType->getAs<RecordType>();
3796 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003797 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003798 }
3799
3800 return true;
3801}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003802
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003803void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3804 switch (SequenceKind) {
3805 case FailedSequence: {
3806 OS << "Failed sequence: ";
3807 switch (Failure) {
3808 case FK_TooManyInitsForReference:
3809 OS << "too many initializers for reference";
3810 break;
3811
3812 case FK_ArrayNeedsInitList:
3813 OS << "array requires initializer list";
3814 break;
3815
3816 case FK_ArrayNeedsInitListOrStringLiteral:
3817 OS << "array requires initializer list or string literal";
3818 break;
3819
3820 case FK_AddressOfOverloadFailed:
3821 OS << "address of overloaded function failed";
3822 break;
3823
3824 case FK_ReferenceInitOverloadFailed:
3825 OS << "overload resolution for reference initialization failed";
3826 break;
3827
3828 case FK_NonConstLValueReferenceBindingToTemporary:
3829 OS << "non-const lvalue reference bound to temporary";
3830 break;
3831
3832 case FK_NonConstLValueReferenceBindingToUnrelated:
3833 OS << "non-const lvalue reference bound to unrelated type";
3834 break;
3835
3836 case FK_RValueReferenceBindingToLValue:
3837 OS << "rvalue reference bound to an lvalue";
3838 break;
3839
3840 case FK_ReferenceInitDropsQualifiers:
3841 OS << "reference initialization drops qualifiers";
3842 break;
3843
3844 case FK_ReferenceInitFailed:
3845 OS << "reference initialization failed";
3846 break;
3847
3848 case FK_ConversionFailed:
3849 OS << "conversion failed";
3850 break;
3851
3852 case FK_TooManyInitsForScalar:
3853 OS << "too many initializers for scalar";
3854 break;
3855
3856 case FK_ReferenceBindingToInitList:
3857 OS << "referencing binding to initializer list";
3858 break;
3859
3860 case FK_InitListBadDestinationType:
3861 OS << "initializer list for non-aggregate, non-scalar type";
3862 break;
3863
3864 case FK_UserConversionOverloadFailed:
3865 OS << "overloading failed for user-defined conversion";
3866 break;
3867
3868 case FK_ConstructorOverloadFailed:
3869 OS << "constructor overloading failed";
3870 break;
3871
3872 case FK_DefaultInitOfConst:
3873 OS << "default initialization of a const variable";
3874 break;
3875 }
3876 OS << '\n';
3877 return;
3878 }
3879
3880 case DependentSequence:
3881 OS << "Dependent sequence: ";
3882 return;
3883
3884 case UserDefinedConversion:
3885 OS << "User-defined conversion sequence: ";
3886 break;
3887
3888 case ConstructorInitialization:
3889 OS << "Constructor initialization sequence: ";
3890 break;
3891
3892 case ReferenceBinding:
3893 OS << "Reference binding: ";
3894 break;
3895
3896 case ListInitialization:
3897 OS << "List initialization: ";
3898 break;
3899
3900 case ZeroInitialization:
3901 OS << "Zero initialization\n";
3902 return;
3903
3904 case NoInitialization:
3905 OS << "No initialization\n";
3906 return;
3907
3908 case StandardConversion:
3909 OS << "Standard conversion: ";
3910 break;
3911
3912 case CAssignment:
3913 OS << "C assignment: ";
3914 break;
3915
3916 case StringInit:
3917 OS << "String initialization: ";
3918 break;
3919 }
3920
3921 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3922 if (S != step_begin()) {
3923 OS << " -> ";
3924 }
3925
3926 switch (S->Kind) {
3927 case SK_ResolveAddressOfOverloadedFunction:
3928 OS << "resolve address of overloaded function";
3929 break;
3930
3931 case SK_CastDerivedToBaseRValue:
3932 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
3933 break;
3934
3935 case SK_CastDerivedToBaseLValue:
3936 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
3937 break;
3938
3939 case SK_BindReference:
3940 OS << "bind reference to lvalue";
3941 break;
3942
3943 case SK_BindReferenceToTemporary:
3944 OS << "bind reference to a temporary";
3945 break;
3946
3947 case SK_UserConversion:
3948 OS << "user-defined conversion via " << S->Function->getNameAsString();
3949 break;
3950
3951 case SK_QualificationConversionRValue:
3952 OS << "qualification conversion (rvalue)";
3953
3954 case SK_QualificationConversionLValue:
3955 OS << "qualification conversion (lvalue)";
3956 break;
3957
3958 case SK_ConversionSequence:
3959 OS << "implicit conversion sequence (";
3960 S->ICS->DebugPrint(); // FIXME: use OS
3961 OS << ")";
3962 break;
3963
3964 case SK_ListInitialization:
3965 OS << "list initialization";
3966 break;
3967
3968 case SK_ConstructorInitialization:
3969 OS << "constructor initialization";
3970 break;
3971
3972 case SK_ZeroInitialization:
3973 OS << "zero initialization";
3974 break;
3975
3976 case SK_CAssignment:
3977 OS << "C assignment";
3978 break;
3979
3980 case SK_StringInit:
3981 OS << "string initialization";
3982 break;
3983 }
3984 }
3985}
3986
3987void InitializationSequence::dump() const {
3988 dump(llvm::errs());
3989}
3990
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003991//===----------------------------------------------------------------------===//
3992// Initialization helper functions
3993//===----------------------------------------------------------------------===//
3994Sema::OwningExprResult
3995Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3996 SourceLocation EqualLoc,
3997 OwningExprResult Init) {
3998 if (Init.isInvalid())
3999 return ExprError();
4000
4001 Expr *InitE = (Expr *)Init.get();
4002 assert(InitE && "No initialization expression?");
4003
4004 if (EqualLoc.isInvalid())
4005 EqualLoc = InitE->getLocStart();
4006
4007 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4008 EqualLoc);
4009 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4010 Init.release();
4011 return Seq.Perform(*this, Entity, Kind,
4012 MultiExprArg(*this, (void**)&InitE, 1));
4013}