blob: 910d3f6469e56b640e894868b01191e541d57a90 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattnerd8b741c82009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnerd8b741c82009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Eli Friedman893abe42009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000097
Eli Friedman893abe42009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000103}
104
Chris Lattner0cb78032009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregorcde232f2009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000136namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000142
Anders Carlsson6cabf312010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000213
Douglas Gregor2bb07652009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner9ececce2009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000229
Douglas Gregor2bb07652009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
265 Sema::OwningExprResult MemberInit
266 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
267 Sema::MultiExprArg(SemaRef, 0, 0));
268 if (MemberInit.isInvalid()) {
269 hadError = true;
270 return;
271 }
272
273 if (hadError) {
274 // Do nothing
275 } else if (Init < NumInits) {
276 ILE->setInit(Init, MemberInit.takeAs<Expr>());
277 } else if (InitSeq.getKind()
278 == InitializationSequence::ConstructorInitialization) {
279 // Value-initialization requires a constructor call, so
280 // extend the initializer list to include the constructor
281 // call and make a note that we'll need to take another pass
282 // through the initializer list.
283 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
284 RequiresSecondPass = true;
285 }
286 } else if (InitListExpr *InnerILE
287 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
288 FillInValueInitializations(MemberEntity, InnerILE,
289 RequiresSecondPass);
290}
291
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000292/// Recursively replaces NULL values within the given initializer list
293/// with expressions that perform value-initialization of the
294/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000295void
296InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
297 InitListExpr *ILE,
298 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000299 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000300 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000301 SourceLocation Loc = ILE->getSourceRange().getBegin();
302 if (ILE->getSyntacticForm())
303 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000304
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000305 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 if (RType->getDecl()->isUnion() &&
307 ILE->getInitializedFieldInUnion())
308 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
309 Entity, ILE, RequiresSecondPass);
310 else {
311 unsigned Init = 0;
312 for (RecordDecl::field_iterator
313 Field = RType->getDecl()->field_begin(),
314 FieldEnd = RType->getDecl()->field_end();
315 Field != FieldEnd; ++Field) {
316 if (Field->isUnnamedBitfield())
317 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000318
Douglas Gregor2bb07652009-12-22 00:05:34 +0000319 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000320 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321
322 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
323 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000324 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325
Douglas Gregor2bb07652009-12-22 00:05:34 +0000326 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 // Only look at the first initialization of a union.
329 if (RType->getDecl()->isUnion())
330 break;
331 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000332 }
333
334 return;
Mike Stump11289f42009-09-09 15:08:12 +0000335 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000336
337 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000338
Douglas Gregor723796a2009-12-16 06:35:08 +0000339 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000340 unsigned NumInits = ILE->getNumInits();
341 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000342 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000343 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
345 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000346 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
347 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000348 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000350 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000351 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
352 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000353 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000355
Douglas Gregor723796a2009-12-16 06:35:08 +0000356
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000358 if (hadError)
359 return;
360
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000361 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
362 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 ElementEntity.setElementIndex(Init);
364
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000365 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000366 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
367 true);
368 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
369 if (!InitSeq) {
370 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000371 hadError = true;
372 return;
373 }
374
Douglas Gregor723796a2009-12-16 06:35:08 +0000375 Sema::OwningExprResult ElementInit
376 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
377 Sema::MultiExprArg(SemaRef, 0, 0));
378 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
393 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
394 RequiresSecondPass = true;
395 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000402
Douglas Gregor723796a2009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000407
Eli Friedman23a9e312008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000415
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000448}
449
Anders Carlsson6cabf312010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
460 else if (T->isStructureType() || T->isUnionType())
461 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000466
Eli Friedmane0f832b2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000482
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregor5741efb2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000500}
501
Anders Carlsson6cabf312010-01-23 23:23:01 +0000502void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000503 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 unsigned &Index,
505 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000506 unsigned &StructuredIndex,
507 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000508 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 SyntacticToSemantic[IList] = StructuredList;
510 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000511 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
512 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000513 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000515 if (hadError)
516 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000517
Eli Friedman85f54972008-05-25 13:22:35 +0000518 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000519 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000520 if (StructuredIndex == 1 &&
521 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000522 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000523 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000524 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000525 hadError = true;
526 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000527 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000528 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000529 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000530 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000531 // Don't complain for incomplete types, since we'll get an error
532 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000533 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000534 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000535 CurrentObjectType->isArrayType()? 0 :
536 CurrentObjectType->isVectorType()? 1 :
537 CurrentObjectType->isScalarType()? 2 :
538 CurrentObjectType->isUnionType()? 3 :
539 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000540
541 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
543 DK = diag::err_excess_initializers;
544 hadError = true;
545 }
Nate Begeman425038c2009-07-07 21:53:06 +0000546 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
547 DK = diag::err_excess_initializers;
548 hadError = true;
549 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000550
Chris Lattnerb0912a52009-02-24 22:50:46 +0000551 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000553 }
554 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000555
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000556 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000557 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000558 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000559 << CodeModificationHint::CreateRemoval(IList->getLocStart())
560 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000561}
562
Anders Carlsson6cabf312010-01-23 23:23:01 +0000563void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000564 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000565 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000566 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000567 unsigned &Index,
568 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000569 unsigned &StructuredIndex,
570 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000571 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000572 CheckScalarType(Entity, IList, DeclType, Index,
573 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000574 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000575 CheckVectorType(Entity, IList, DeclType, Index,
576 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000577 } else if (DeclType->isAggregateType()) {
578 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000579 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000580 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 StructuredList, StructuredIndex,
583 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000584 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000585 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000586 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000587 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000588 CheckArrayType(Entity, IList, DeclType, Zero,
589 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000590 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000593 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
594 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000596 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000597 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000598 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000599 } else if (DeclType->isRecordType()) {
600 // C++ [dcl.init]p14:
601 // [...] If the class is an aggregate (8.5.1), and the initializer
602 // is a brace-enclosed list, see 8.5.1.
603 //
604 // Note: 8.5.1 is handled below; here, we diagnose the case where
605 // we have an initializer list and a destination type that is not
606 // an aggregate.
607 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000609 << DeclType << IList->getSourceRange();
610 hadError = true;
611 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000612 CheckReferenceType(Entity, IList, DeclType, Index,
613 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000614 } else {
615 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000616 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000617 assert(0 && "Unsupported initializer type");
618 }
619}
620
Anders Carlsson6cabf312010-01-23 23:23:01 +0000621void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000622 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000623 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
626 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000627 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000628 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
629 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000630 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000631 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000632 = getStructuredSubobjectInit(IList, Index, ElemType,
633 StructuredList, StructuredIndex,
634 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000635 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 newStructuredList, newStructuredIndex);
637 ++StructuredIndex;
638 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000639 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
640 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000641 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000643 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000644 CheckScalarType(Entity, IList, ElemType, Index,
645 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000646 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000647 CheckReferenceType(Entity, IList, ElemType, Index,
648 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000649 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000651 // C++ [dcl.init.aggr]p12:
652 // All implicit type conversions (clause 4) are considered when
653 // initializing the aggregate member with an ini- tializer from
654 // an initializer-list. If the initializer can initialize a
655 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000656
Anders Carlsson0bd52402010-01-24 00:19:41 +0000657 // FIXME: Better EqualLoc?
658 InitializationKind Kind =
659 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
660 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
661
662 if (Seq) {
663 Sema::OwningExprResult Result =
664 Seq.Perform(SemaRef, Entity, Kind,
665 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
666 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000667 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000668
669 UpdateStructuredListElement(StructuredList, StructuredIndex,
670 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000671 ++Index;
672 return;
673 }
674
675 // Fall through for subaggregate initialization
676 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000677 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000678 //
679 // The initializer for a structure or union object that has
680 // automatic storage duration shall be either an initializer
681 // list as described below, or a single expression that has
682 // compatible structure or union type. In the latter case, the
683 // initial value of the object, including unnamed members, is
684 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000685 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000686 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000687 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
688 ++Index;
689 return;
690 }
691
692 // Fall through for subaggregate initialization
693 }
694
695 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000696 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000697 // [...] Otherwise, if the member is itself a non-empty
698 // subaggregate, brace elision is assumed and the initializer is
699 // considered for the initialization of the first member of
700 // the subaggregate.
701 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000702 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 StructuredIndex);
704 ++StructuredIndex;
705 } else {
706 // We cannot initialize this element, so let
707 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000708 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 hadError = true;
710 ++Index;
711 ++StructuredIndex;
712 }
713 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000714}
715
Anders Carlsson6cabf312010-01-23 23:23:01 +0000716void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000717 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000718 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000719 InitListExpr *StructuredList,
720 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000721 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000722 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000723 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000724 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000725 diag::err_many_braces_around_scalar_init)
726 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000727 hadError = true;
728 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000729 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000730 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000731 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000732 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000733 diag::err_designator_for_scalar_init)
734 << DeclType << expr->getSourceRange();
735 hadError = true;
736 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000737 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000738 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000739 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000740
Anders Carlsson26d05642010-01-23 18:35:41 +0000741 Sema::OwningExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000742 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
743 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000744
745 Expr *ResultExpr;
746
747 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000749 else {
750 ResultExpr = Result.takeAs<Expr>();
751
752 if (ResultExpr != expr) {
753 // The type was promoted, update initializer list.
754 IList->setInit(Index, ResultExpr);
755 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000756 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 if (hadError)
758 ++StructuredIndex;
759 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000760 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000761 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000762 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000763 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000764 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000766 ++Index;
767 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000768 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000769 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000770}
771
Anders Carlsson6cabf312010-01-23 23:23:01 +0000772void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
773 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000774 unsigned &Index,
775 InitListExpr *StructuredList,
776 unsigned &StructuredIndex) {
777 if (Index < IList->getNumInits()) {
778 Expr *expr = IList->getInit(Index);
779 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000781 << DeclType << IList->getSourceRange();
782 hadError = true;
783 ++Index;
784 ++StructuredIndex;
785 return;
Mike Stump11289f42009-09-09 15:08:12 +0000786 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000787
Anders Carlssona91be642010-01-29 02:47:33 +0000788 Sema::OwningExprResult Result =
789 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
790 SemaRef.Owned(expr));
791
792 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000793 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000794
795 expr = Result.takeAs<Expr>();
796 IList->setInit(Index, expr);
797
Douglas Gregord14247a2009-01-30 22:09:00 +0000798 if (hadError)
799 ++StructuredIndex;
800 else
801 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
802 ++Index;
803 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000804 // FIXME: It would be wonderful if we could point at the actual member. In
805 // general, it would be useful to pass location information down the stack,
806 // so that we know the location (or decl) of the "current object" being
807 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000808 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000809 diag::err_init_reference_member_uninitialized)
810 << DeclType
811 << IList->getSourceRange();
812 hadError = true;
813 ++Index;
814 ++StructuredIndex;
815 return;
816 }
817}
818
Anders Carlsson6cabf312010-01-23 23:23:01 +0000819void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000820 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000821 unsigned &Index,
822 InitListExpr *StructuredList,
823 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000824 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000825 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000826 unsigned maxElements = VT->getNumElements();
827 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000828 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000829
Nate Begeman5ec4b312009-08-10 23:49:36 +0000830 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000831 InitializedEntity ElementEntity =
832 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000833
Anders Carlsson6cabf312010-01-23 23:23:01 +0000834 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
835 // Don't attempt to go past the end of the init list
836 if (Index >= IList->getNumInits())
837 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000838
Anders Carlsson6cabf312010-01-23 23:23:01 +0000839 ElementEntity.setElementIndex(Index);
840 CheckSubElementType(ElementEntity, IList, elementType, Index,
841 StructuredList, StructuredIndex);
842 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000843 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000844 InitializedEntity ElementEntity =
845 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
846
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 // OpenCL initializers allows vectors to be constructed from vectors.
848 for (unsigned i = 0; i < maxElements; ++i) {
849 // Don't attempt to go past the end of the init list
850 if (Index >= IList->getNumInits())
851 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852
853 ElementEntity.setElementIndex(Index);
854
Nate Begeman5ec4b312009-08-10 23:49:36 +0000855 QualType IType = IList->getInit(Index)->getType();
856 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000857 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000858 StructuredList, StructuredIndex);
859 ++numEltsInit;
860 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000861 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000862 unsigned numIElts = IVT->getNumElements();
863 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
864 numIElts);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000865 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000866 StructuredList, StructuredIndex);
867 numEltsInit += numIElts;
868 }
869 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000870 }
Mike Stump11289f42009-09-09 15:08:12 +0000871
Nate Begeman5ec4b312009-08-10 23:49:36 +0000872 // OpenCL & AltiVec require all elements to be initialized.
873 if (numEltsInit != maxElements)
874 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
875 SemaRef.Diag(IList->getSourceRange().getBegin(),
876 diag::err_vector_incorrect_num_initializers)
877 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000878 }
879}
880
Anders Carlsson6cabf312010-01-23 23:23:01 +0000881void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000882 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000883 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000884 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000885 unsigned &Index,
886 InitListExpr *StructuredList,
887 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000888 // Check for the special-case of initializing an array with a string.
889 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000890 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
891 SemaRef.Context)) {
892 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000893 // We place the string literal directly into the resulting
894 // initializer list. This is the only place where the structure
895 // of the structured initializer list doesn't match exactly,
896 // because doing so would involve allocating one character
897 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000898 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000899 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000900 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000901 return;
902 }
903 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000904 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000905 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000906 // Check for VLAs; in standard C it would be possible to check this
907 // earlier, but I don't know where clang accepts VLAs (gcc accepts
908 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000909 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000910 diag::err_variable_object_no_init)
911 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000912 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000913 ++Index;
914 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000915 return;
916 }
917
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000918 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000919 llvm::APSInt maxElements(elementIndex.getBitWidth(),
920 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000921 bool maxElementsKnown = false;
922 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000923 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000924 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000925 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000926 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000927 maxElementsKnown = true;
928 }
929
Chris Lattnerb0912a52009-02-24 22:50:46 +0000930 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000931 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000932 while (Index < IList->getNumInits()) {
933 Expr *Init = IList->getInit(Index);
934 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000935 // If we're not the subobject that matches up with the '{' for
936 // the designator, we shouldn't be handling the
937 // designator. Return immediately.
938 if (!SubobjectIsDesignatorContext)
939 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000940
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000941 // Handle this designated initializer. elementIndex will be
942 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000943 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000944 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000945 StructuredList, StructuredIndex, true,
946 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000947 hadError = true;
948 continue;
949 }
950
Douglas Gregor033d1252009-01-23 16:54:12 +0000951 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
952 maxElements.extend(elementIndex.getBitWidth());
953 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
954 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000955 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000956
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000957 // If the array is of incomplete type, keep track of the number of
958 // elements in the initializer.
959 if (!maxElementsKnown && elementIndex > maxElements)
960 maxElements = elementIndex;
961
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000962 continue;
963 }
964
965 // If we know the maximum number of elements, and we've already
966 // hit it, stop consuming elements in the initializer list.
967 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000968 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000969
Anders Carlsson6cabf312010-01-23 23:23:01 +0000970 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000971 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972 Entity);
973 // Check this element.
974 CheckSubElementType(ElementEntity, IList, elementType, Index,
975 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000976 ++elementIndex;
977
978 // If the array is of incomplete type, keep track of the number of
979 // elements in the initializer.
980 if (!maxElementsKnown && elementIndex > maxElements)
981 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000982 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000983 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000984 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000985 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000986 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000987 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000988 // Sizing an array implicitly to zero is not allowed by ISO C,
989 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000990 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000991 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000992 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000993
Mike Stump11289f42009-09-09 15:08:12 +0000994 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000995 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000996 }
997}
998
Anders Carlsson6cabf312010-01-23 23:23:01 +0000999void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001000 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001001 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001002 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001003 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001004 unsigned &Index,
1005 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001006 unsigned &StructuredIndex,
1007 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001008 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001009
Eli Friedman23a9e312008-05-19 19:16:24 +00001010 // If the record is invalid, some of it's members are invalid. To avoid
1011 // confusion, we forgo checking the intializer for the entire record.
1012 if (structDecl->isInvalidDecl()) {
1013 hadError = true;
1014 return;
Mike Stump11289f42009-09-09 15:08:12 +00001015 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001016
1017 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1018 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001019 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001020 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001021 Field != FieldEnd; ++Field) {
1022 if (Field->getDeclName()) {
1023 StructuredList->setInitializedFieldInUnion(*Field);
1024 break;
1025 }
1026 }
1027 return;
1028 }
1029
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001030 // If structDecl is a forward declaration, this loop won't do
1031 // anything except look at designated initializers; That's okay,
1032 // because an error should get printed out elsewhere. It might be
1033 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001035 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001036 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001037 while (Index < IList->getNumInits()) {
1038 Expr *Init = IList->getInit(Index);
1039
1040 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001041 // If we're not the subobject that matches up with the '{' for
1042 // the designator, we shouldn't be handling the
1043 // designator. Return immediately.
1044 if (!SubobjectIsDesignatorContext)
1045 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001046
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001047 // Handle this designated initializer. Field will be updated to
1048 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001049 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001050 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001051 StructuredList, StructuredIndex,
1052 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001053 hadError = true;
1054
Douglas Gregora9add4e2009-02-12 19:00:39 +00001055 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001056 continue;
1057 }
1058
1059 if (Field == FieldEnd) {
1060 // We've run out of fields. We're done.
1061 break;
1062 }
1063
Douglas Gregora9add4e2009-02-12 19:00:39 +00001064 // We've already initialized a member of a union. We're done.
1065 if (InitializedSomething && DeclType->isUnionType())
1066 break;
1067
Douglas Gregor91f84212008-12-11 16:49:14 +00001068 // If we've hit the flexible array member at the end, we're done.
1069 if (Field->getType()->isIncompleteArrayType())
1070 break;
1071
Douglas Gregor51695702009-01-29 16:53:55 +00001072 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001073 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001074 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001075 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001076 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001077
Anders Carlsson6cabf312010-01-23 23:23:01 +00001078 InitializedEntity MemberEntity =
1079 InitializedEntity::InitializeMember(*Field, &Entity);
1080 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1081 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001082 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001083
1084 if (DeclType->isUnionType()) {
1085 // Initialize the first field within the union.
1086 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001087 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001088
1089 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001090 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001091
Mike Stump11289f42009-09-09 15:08:12 +00001092 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001093 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001094 return;
1095
1096 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001098 (!isa<InitListExpr>(IList->getInit(Index)) ||
1099 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001100 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001101 diag::err_flexible_array_init_nonempty)
1102 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001103 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001104 << *Field;
1105 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001106 ++Index;
1107 return;
1108 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001109 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001110 diag::ext_flexible_array_init)
1111 << IList->getInit(Index)->getSourceRange().getBegin();
1112 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1113 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001114 }
1115
Anders Carlsson6cabf312010-01-23 23:23:01 +00001116 InitializedEntity MemberEntity =
1117 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001118
Anders Carlsson6cabf312010-01-23 23:23:01 +00001119 if (isa<InitListExpr>(IList->getInit(Index)))
1120 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1121 StructuredList, StructuredIndex);
1122 else
1123 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001124 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001125}
Steve Narofff8ecff22008-05-01 22:18:59 +00001126
Douglas Gregord5846a12009-04-15 06:41:24 +00001127/// \brief Expand a field designator that refers to a member of an
1128/// anonymous struct or union into a series of field designators that
1129/// refers to the field within the appropriate subobject.
1130///
1131/// Field/FieldIndex will be updated to point to the (new)
1132/// currently-designated field.
1133static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001134 DesignatedInitExpr *DIE,
1135 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001136 FieldDecl *Field,
1137 RecordDecl::field_iterator &FieldIter,
1138 unsigned &FieldIndex) {
1139 typedef DesignatedInitExpr::Designator Designator;
1140
1141 // Build the path from the current object to the member of the
1142 // anonymous struct/union (backwards).
1143 llvm::SmallVector<FieldDecl *, 4> Path;
1144 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregord5846a12009-04-15 06:41:24 +00001146 // Build the replacement designators.
1147 llvm::SmallVector<Designator, 4> Replacements;
1148 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1149 FI = Path.rbegin(), FIEnd = Path.rend();
1150 FI != FIEnd; ++FI) {
1151 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001152 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001153 DIE->getDesignator(DesigIdx)->getDotLoc(),
1154 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1155 else
1156 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1157 SourceLocation()));
1158 Replacements.back().setField(*FI);
1159 }
1160
1161 // Expand the current designator into the set of replacement
1162 // designators, so we have a full subobject path down to where the
1163 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001164 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001165 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001166
Douglas Gregord5846a12009-04-15 06:41:24 +00001167 // Update FieldIter/FieldIndex;
1168 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001169 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001170 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001171 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001172 FieldIter != FEnd; ++FieldIter) {
1173 if (FieldIter->isUnnamedBitfield())
1174 continue;
1175
1176 if (*FieldIter == Path.back())
1177 return;
1178
1179 ++FieldIndex;
1180 }
1181
1182 assert(false && "Unable to find anonymous struct/union field");
1183}
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185/// @brief Check the well-formedness of a C99 designated initializer.
1186///
1187/// Determines whether the designated initializer @p DIE, which
1188/// resides at the given @p Index within the initializer list @p
1189/// IList, is well-formed for a current object of type @p DeclType
1190/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001191/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001192/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193///
1194/// @param IList The initializer list in which this designated
1195/// initializer occurs.
1196///
Douglas Gregora5324162009-04-15 04:56:10 +00001197/// @param DIE The designated initializer expression.
1198///
1199/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001200///
1201/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1202/// into which the designation in @p DIE should refer.
1203///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001204/// @param NextField If non-NULL and the first designator in @p DIE is
1205/// a field, this will be set to the field declaration corresponding
1206/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001207///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001208/// @param NextElementIndex If non-NULL and the first designator in @p
1209/// DIE is an array designator or GNU array-range designator, this
1210/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001211///
1212/// @param Index Index into @p IList where the designated initializer
1213/// @p DIE occurs.
1214///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001215/// @param StructuredList The initializer list expression that
1216/// describes all of the subobject initializers in the order they'll
1217/// actually be initialized.
1218///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001219/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001220bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001221InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001222 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001223 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001224 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001225 QualType &CurrentObjectType,
1226 RecordDecl::field_iterator *NextField,
1227 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001228 unsigned &Index,
1229 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001230 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001231 bool FinishSubobjectInit,
1232 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001233 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001234 // Check the actual initialization for the designated object type.
1235 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001236
1237 // Temporarily remove the designator expression from the
1238 // initializer list that the child calls see, so that we don't try
1239 // to re-process the designator.
1240 unsigned OldIndex = Index;
1241 IList->setInit(OldIndex, DIE->getInit());
1242
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001243 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001244 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001245
1246 // Restore the designated initializer expression in the syntactic
1247 // form of the initializer list.
1248 if (IList->getInit(OldIndex) != DIE->getInit())
1249 DIE->setInit(IList->getInit(OldIndex));
1250 IList->setInit(OldIndex, DIE);
1251
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001252 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001253 }
1254
Douglas Gregora5324162009-04-15 04:56:10 +00001255 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001256 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001257 "Need a non-designated initializer list to start from");
1258
Douglas Gregora5324162009-04-15 04:56:10 +00001259 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001260 // Determine the structural initializer list that corresponds to the
1261 // current subobject.
1262 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001263 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001264 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001265 SourceRange(D->getStartLocation(),
1266 DIE->getSourceRange().getEnd()));
1267 assert(StructuredList && "Expected a structured initializer list");
1268
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001269 if (D->isFieldDesignator()) {
1270 // C99 6.7.8p7:
1271 //
1272 // If a designator has the form
1273 //
1274 // . identifier
1275 //
1276 // then the current object (defined below) shall have
1277 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001278 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001279 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001280 if (!RT) {
1281 SourceLocation Loc = D->getDotLoc();
1282 if (Loc.isInvalid())
1283 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001284 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1285 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001286 ++Index;
1287 return true;
1288 }
1289
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001290 // Note: we perform a linear search of the fields here, despite
1291 // the fact that we have a faster lookup method, because we always
1292 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001293 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001294 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001295 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001296 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001297 Field = RT->getDecl()->field_begin(),
1298 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001299 for (; Field != FieldEnd; ++Field) {
1300 if (Field->isUnnamedBitfield())
1301 continue;
1302
Douglas Gregord5846a12009-04-15 06:41:24 +00001303 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304 break;
1305
1306 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001307 }
1308
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001309 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001310 // There was no normal field in the struct with the designated
1311 // name. Perform another lookup for this name, which may find
1312 // something that we can't designate (e.g., a member function),
1313 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001314 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001315 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001316 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001318 // Name lookup didn't find anything. Determine whether this
1319 // was a typo for another field name.
1320 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1321 Sema::LookupMemberName);
1322 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1323 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1324 ReplacementField->getDeclContext()->getLookupContext()
1325 ->Equals(RT->getDecl())) {
1326 SemaRef.Diag(D->getFieldLoc(),
1327 diag::err_field_designator_unknown_suggest)
1328 << FieldName << CurrentObjectType << R.getLookupName()
1329 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1330 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001331 SemaRef.Diag(ReplacementField->getLocation(),
1332 diag::note_previous_decl)
1333 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001334 } else {
1335 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1336 << FieldName << CurrentObjectType;
1337 ++Index;
1338 return true;
1339 }
1340 } else if (!KnownField) {
1341 // Determine whether we found a field at all.
1342 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1343 }
1344
1345 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001346 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001347 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001349 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001351 ++Index;
1352 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001353 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001354
1355 if (!KnownField &&
1356 cast<RecordDecl>((ReplacementField)->getDeclContext())
1357 ->isAnonymousStructOrUnion()) {
1358 // Handle an field designator that refers to a member of an
1359 // anonymous struct or union.
1360 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1361 ReplacementField,
1362 Field, FieldIndex);
1363 D = DIE->getDesignator(DesigIdx);
1364 } else if (!KnownField) {
1365 // The replacement field comes from typo correction; find it
1366 // in the list of fields.
1367 FieldIndex = 0;
1368 Field = RT->getDecl()->field_begin();
1369 for (; Field != FieldEnd; ++Field) {
1370 if (Field->isUnnamedBitfield())
1371 continue;
1372
1373 if (ReplacementField == *Field ||
1374 Field->getIdentifier() == ReplacementField->getIdentifier())
1375 break;
1376
1377 ++FieldIndex;
1378 }
1379 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001380 } else if (!KnownField &&
1381 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001383 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1384 Field, FieldIndex);
1385 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001386 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387
1388 // All of the fields of a union are located at the same place in
1389 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001390 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001391 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001392 StructuredList->setInitializedFieldInUnion(*Field);
1393 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001395 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001398 // Make sure that our non-designated initializer list has space
1399 // for a subobject corresponding to this field.
1400 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001401 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001402
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001403 // This designator names a flexible array member.
1404 if (Field->getType()->isIncompleteArrayType()) {
1405 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001406 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001407 // We can't designate an object within the flexible array
1408 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001409 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001410 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001411 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001412 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001413 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001414 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001415 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001416 << *Field;
1417 Invalid = true;
1418 }
1419
1420 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1421 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001422 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001423 diag::err_flexible_array_init_needs_braces)
1424 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001425 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001426 << *Field;
1427 Invalid = true;
1428 }
1429
1430 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001431 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001432 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001433 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001434 diag::err_flexible_array_init_nonempty)
1435 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001436 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001437 << *Field;
1438 Invalid = true;
1439 }
1440
1441 if (Invalid) {
1442 ++Index;
1443 return true;
1444 }
1445
1446 // Initialize the array.
1447 bool prevHadError = hadError;
1448 unsigned newStructuredIndex = FieldIndex;
1449 unsigned OldIndex = Index;
1450 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001451
1452 InitializedEntity MemberEntity =
1453 InitializedEntity::InitializeMember(*Field, &Entity);
1454 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001455 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001456
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001457 IList->setInit(OldIndex, DIE);
1458 if (hadError && !prevHadError) {
1459 ++Field;
1460 ++FieldIndex;
1461 if (NextField)
1462 *NextField = Field;
1463 StructuredIndex = FieldIndex;
1464 return true;
1465 }
1466 } else {
1467 // Recurse to check later designated subobjects.
1468 QualType FieldType = (*Field)->getType();
1469 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001470
1471 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001472 InitializedEntity::InitializeMember(*Field, &Entity);
1473 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001474 FieldType, 0, 0, Index,
1475 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001476 true, false))
1477 return true;
1478 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001479
1480 // Find the position of the next field to be initialized in this
1481 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001482 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001484
1485 // If this the first designator, our caller will continue checking
1486 // the rest of this struct/class/union subobject.
1487 if (IsFirstDesignator) {
1488 if (NextField)
1489 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001490 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001491 return false;
1492 }
1493
Douglas Gregor17bd0942009-01-28 23:36:17 +00001494 if (!FinishSubobjectInit)
1495 return false;
1496
Douglas Gregord5846a12009-04-15 06:41:24 +00001497 // We've already initialized something in the union; we're done.
1498 if (RT->getDecl()->isUnion())
1499 return hadError;
1500
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001501 // Check the remaining fields within this class/struct/union subobject.
1502 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001503
Anders Carlsson6cabf312010-01-23 23:23:01 +00001504 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001505 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001506 return hadError && !prevHadError;
1507 }
1508
1509 // C99 6.7.8p6:
1510 //
1511 // If a designator has the form
1512 //
1513 // [ constant-expression ]
1514 //
1515 // then the current object (defined below) shall have array
1516 // type and the expression shall be an integer constant
1517 // expression. If the array is of unknown size, any
1518 // nonnegative value is valid.
1519 //
1520 // Additionally, cope with the GNU extension that permits
1521 // designators of the form
1522 //
1523 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001524 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001525 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001526 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527 << CurrentObjectType;
1528 ++Index;
1529 return true;
1530 }
1531
1532 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001533 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1534 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001535 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001536 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001537 DesignatedEndIndex = DesignatedStartIndex;
1538 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001539 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001540
Mike Stump11289f42009-09-09 15:08:12 +00001541
1542 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001543 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001544 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001545 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001546 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001547
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001548 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001549 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001550 }
1551
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001552 if (isa<ConstantArrayType>(AT)) {
1553 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001554 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1555 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1556 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1557 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1558 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001559 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001560 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001561 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001562 << IndexExpr->getSourceRange();
1563 ++Index;
1564 return true;
1565 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001566 } else {
1567 // Make sure the bit-widths and signedness match.
1568 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1569 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001570 else if (DesignatedStartIndex.getBitWidth() <
1571 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001572 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1573 DesignatedStartIndex.setIsUnsigned(true);
1574 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575 }
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001577 // Make sure that our non-designated initializer list has space
1578 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001579 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001580 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001582
Douglas Gregor17bd0942009-01-28 23:36:17 +00001583 // Repeatedly perform subobject initializations in the range
1584 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001585
Douglas Gregor17bd0942009-01-28 23:36:17 +00001586 // Move to the next designator
1587 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1588 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001589
1590 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001592
Douglas Gregor17bd0942009-01-28 23:36:17 +00001593 while (DesignatedStartIndex <= DesignatedEndIndex) {
1594 // Recurse to check later designated subobjects.
1595 QualType ElementType = AT->getElementType();
1596 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001597
1598 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001599 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001600 ElementType, 0, 0, Index,
1601 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001602 (DesignatedStartIndex == DesignatedEndIndex),
1603 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001604 return true;
1605
1606 // Move to the next index in the array that we'll be initializing.
1607 ++DesignatedStartIndex;
1608 ElementIndex = DesignatedStartIndex.getZExtValue();
1609 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001610
1611 // If this the first designator, our caller will continue checking
1612 // the rest of this array subobject.
1613 if (IsFirstDesignator) {
1614 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001615 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617 return false;
1618 }
Mike Stump11289f42009-09-09 15:08:12 +00001619
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 if (!FinishSubobjectInit)
1621 return false;
1622
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001623 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001624 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001625 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001626 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001627 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001628 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001629}
1630
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001631// Get the structured initializer list for a subobject of type
1632// @p CurrentObjectType.
1633InitListExpr *
1634InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1635 QualType CurrentObjectType,
1636 InitListExpr *StructuredList,
1637 unsigned StructuredIndex,
1638 SourceRange InitRange) {
1639 Expr *ExistingInit = 0;
1640 if (!StructuredList)
1641 ExistingInit = SyntacticToSemantic[IList];
1642 else if (StructuredIndex < StructuredList->getNumInits())
1643 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001645 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1646 return Result;
1647
1648 if (ExistingInit) {
1649 // We are creating an initializer list that initializes the
1650 // subobjects of the current object, but there was already an
1651 // initialization that completely initialized the current
1652 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001653 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001654 // struct X { int a, b; };
1655 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001656 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001657 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1658 // designated initializer re-initializes the whole
1659 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001660 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001661 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001663 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001665 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001666 << ExistingInit->getSourceRange();
1667 }
1668
Mike Stump11289f42009-09-09 15:08:12 +00001669 InitListExpr *Result
1670 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001671 InitRange.getEnd());
1672
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001673 Result->setType(CurrentObjectType);
1674
Douglas Gregor6d00c992009-03-20 23:58:33 +00001675 // Pre-allocate storage for the structured initializer list.
1676 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001677 unsigned NumInits = 0;
1678 if (!StructuredList)
1679 NumInits = IList->getNumInits();
1680 else if (Index < IList->getNumInits()) {
1681 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1682 NumInits = SubList->getNumInits();
1683 }
1684
Mike Stump11289f42009-09-09 15:08:12 +00001685 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001686 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1687 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1688 NumElements = CAType->getSize().getZExtValue();
1689 // Simple heuristic so that we don't allocate a very large
1690 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001691 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001692 NumElements = 0;
1693 }
John McCall9dd450b2009-09-21 23:43:11 +00001694 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001695 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001696 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001697 RecordDecl *RDecl = RType->getDecl();
1698 if (RDecl->isUnion())
1699 NumElements = 1;
1700 else
Mike Stump11289f42009-09-09 15:08:12 +00001701 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001702 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001703 }
1704
Douglas Gregor221c9a52009-03-21 18:13:52 +00001705 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001706 NumElements = IList->getNumInits();
1707
1708 Result->reserveInits(NumElements);
1709
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 // Link this new initializer list into the structured initializer
1711 // lists.
1712 if (StructuredList)
1713 StructuredList->updateInit(StructuredIndex, Result);
1714 else {
1715 Result->setSyntacticForm(IList);
1716 SyntacticToSemantic[IList] = Result;
1717 }
1718
1719 return Result;
1720}
1721
1722/// Update the initializer at index @p StructuredIndex within the
1723/// structured initializer list to the value @p expr.
1724void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1725 unsigned &StructuredIndex,
1726 Expr *expr) {
1727 // No structured initializer list to update
1728 if (!StructuredList)
1729 return;
1730
1731 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1732 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001733 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001734 diag::warn_initializer_overrides)
1735 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001736 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001738 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 << PrevInit->getSourceRange();
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001742 ++StructuredIndex;
1743}
1744
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001745/// Check that the given Index expression is a valid array designator
1746/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001747/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001748/// and produces a reasonable diagnostic if there is a
1749/// failure. Returns true if there was an error, false otherwise. If
1750/// everything went okay, Value will receive the value of the constant
1751/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001752static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001753CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001754 SourceLocation Loc = Index->getSourceRange().getBegin();
1755
1756 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001757 if (S.VerifyIntegerConstantExpression(Index, &Value))
1758 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001759
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001760 if (Value.isSigned() && Value.isNegative())
1761 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001762 << Value.toString(10) << Index->getSourceRange();
1763
Douglas Gregor51650d32009-01-23 21:04:18 +00001764 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001765 return false;
1766}
1767
1768Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1769 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001770 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771 OwningExprResult Init) {
1772 typedef DesignatedInitExpr::Designator ASTDesignator;
1773
1774 bool Invalid = false;
1775 llvm::SmallVector<ASTDesignator, 32> Designators;
1776 llvm::SmallVector<Expr *, 32> InitExpressions;
1777
1778 // Build designators and check array designator expressions.
1779 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1780 const Designator &D = Desig.getDesignator(Idx);
1781 switch (D.getKind()) {
1782 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001783 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001784 D.getFieldLoc()));
1785 break;
1786
1787 case Designator::ArrayDesignator: {
1788 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1789 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001790 if (!Index->isTypeDependent() &&
1791 !Index->isValueDependent() &&
1792 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001793 Invalid = true;
1794 else {
1795 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001796 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797 D.getRBracketLoc()));
1798 InitExpressions.push_back(Index);
1799 }
1800 break;
1801 }
1802
1803 case Designator::ArrayRangeDesignator: {
1804 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1805 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1806 llvm::APSInt StartValue;
1807 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001808 bool StartDependent = StartIndex->isTypeDependent() ||
1809 StartIndex->isValueDependent();
1810 bool EndDependent = EndIndex->isTypeDependent() ||
1811 EndIndex->isValueDependent();
1812 if ((!StartDependent &&
1813 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1814 (!EndDependent &&
1815 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001816 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001817 else {
1818 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001819 if (StartDependent || EndDependent) {
1820 // Nothing to compute.
1821 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001822 EndValue.extend(StartValue.getBitWidth());
1823 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1824 StartValue.extend(EndValue.getBitWidth());
1825
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001826 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001827 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001828 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001829 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1830 Invalid = true;
1831 } else {
1832 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001833 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001834 D.getEllipsisLoc(),
1835 D.getRBracketLoc()));
1836 InitExpressions.push_back(StartIndex);
1837 InitExpressions.push_back(EndIndex);
1838 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001839 }
1840 break;
1841 }
1842 }
1843 }
1844
1845 if (Invalid || Init.isInvalid())
1846 return ExprError();
1847
1848 // Clear out the expressions within the designation.
1849 Desig.ClearExprs(*this);
1850
1851 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001852 = DesignatedInitExpr::Create(Context,
1853 Designators.data(), Designators.size(),
1854 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001855 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001856 return Owned(DIE);
1857}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001858
Douglas Gregor723796a2009-12-16 06:35:08 +00001859bool Sema::CheckInitList(const InitializedEntity &Entity,
1860 InitListExpr *&InitList, QualType &DeclType) {
1861 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001862 if (!CheckInitList.HadError())
1863 InitList = CheckInitList.getFullyStructuredList();
1864
1865 return CheckInitList.HadError();
1866}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001867
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001868//===----------------------------------------------------------------------===//
1869// Initialization entity
1870//===----------------------------------------------------------------------===//
1871
Douglas Gregor723796a2009-12-16 06:35:08 +00001872InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1873 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001874 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001875{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001876 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1877 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001878 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001879 } else {
1880 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001881 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001882 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001883}
1884
1885InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1886 CXXBaseSpecifier *Base)
1887{
1888 InitializedEntity Result;
1889 Result.Kind = EK_Base;
1890 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001891 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001892 return Result;
1893}
1894
Douglas Gregor85dabae2009-12-16 01:38:02 +00001895DeclarationName InitializedEntity::getName() const {
1896 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001897 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001898 if (!VariableOrMember)
1899 return DeclarationName();
1900 // Fall through
1901
1902 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001903 case EK_Member:
1904 return VariableOrMember->getDeclName();
1905
1906 case EK_Result:
1907 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001908 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001909 case EK_Temporary:
1910 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001911 case EK_ArrayElement:
1912 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001913 return DeclarationName();
1914 }
1915
1916 // Silence GCC warning
1917 return DeclarationName();
1918}
1919
Douglas Gregora4b592a2009-12-19 03:01:41 +00001920DeclaratorDecl *InitializedEntity::getDecl() const {
1921 switch (getKind()) {
1922 case EK_Variable:
1923 case EK_Parameter:
1924 case EK_Member:
1925 return VariableOrMember;
1926
1927 case EK_Result:
1928 case EK_Exception:
1929 case EK_New:
1930 case EK_Temporary:
1931 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001932 case EK_ArrayElement:
1933 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001934 return 0;
1935 }
1936
1937 // Silence GCC warning
1938 return 0;
1939}
1940
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001941//===----------------------------------------------------------------------===//
1942// Initialization sequence
1943//===----------------------------------------------------------------------===//
1944
1945void InitializationSequence::Step::Destroy() {
1946 switch (Kind) {
1947 case SK_ResolveAddressOfOverloadedFunction:
1948 case SK_CastDerivedToBaseRValue:
1949 case SK_CastDerivedToBaseLValue:
1950 case SK_BindReference:
1951 case SK_BindReferenceToTemporary:
1952 case SK_UserConversion:
1953 case SK_QualificationConversionRValue:
1954 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001955 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001956 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001957 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001958 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001959 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001960 break;
1961
1962 case SK_ConversionSequence:
1963 delete ICS;
1964 }
1965}
1966
1967void InitializationSequence::AddAddressOverloadResolutionStep(
1968 FunctionDecl *Function) {
1969 Step S;
1970 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1971 S.Type = Function->getType();
1972 S.Function = Function;
1973 Steps.push_back(S);
1974}
1975
1976void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1977 bool IsLValue) {
1978 Step S;
1979 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1980 S.Type = BaseType;
1981 Steps.push_back(S);
1982}
1983
1984void InitializationSequence::AddReferenceBindingStep(QualType T,
1985 bool BindingTemporary) {
1986 Step S;
1987 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1988 S.Type = T;
1989 Steps.push_back(S);
1990}
1991
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001992void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1993 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001994 Step S;
1995 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001996 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001997 S.Function = Function;
1998 Steps.push_back(S);
1999}
2000
2001void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2002 bool IsLValue) {
2003 Step S;
2004 S.Kind = IsLValue? SK_QualificationConversionLValue
2005 : SK_QualificationConversionRValue;
2006 S.Type = Ty;
2007 Steps.push_back(S);
2008}
2009
2010void InitializationSequence::AddConversionSequenceStep(
2011 const ImplicitConversionSequence &ICS,
2012 QualType T) {
2013 Step S;
2014 S.Kind = SK_ConversionSequence;
2015 S.Type = T;
2016 S.ICS = new ImplicitConversionSequence(ICS);
2017 Steps.push_back(S);
2018}
2019
Douglas Gregor51e77d52009-12-10 17:56:55 +00002020void InitializationSequence::AddListInitializationStep(QualType T) {
2021 Step S;
2022 S.Kind = SK_ListInitialization;
2023 S.Type = T;
2024 Steps.push_back(S);
2025}
2026
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002027void
2028InitializationSequence::AddConstructorInitializationStep(
2029 CXXConstructorDecl *Constructor,
2030 QualType T) {
2031 Step S;
2032 S.Kind = SK_ConstructorInitialization;
2033 S.Type = T;
2034 S.Function = Constructor;
2035 Steps.push_back(S);
2036}
2037
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002038void InitializationSequence::AddZeroInitializationStep(QualType T) {
2039 Step S;
2040 S.Kind = SK_ZeroInitialization;
2041 S.Type = T;
2042 Steps.push_back(S);
2043}
2044
Douglas Gregore1314a62009-12-18 05:02:21 +00002045void InitializationSequence::AddCAssignmentStep(QualType T) {
2046 Step S;
2047 S.Kind = SK_CAssignment;
2048 S.Type = T;
2049 Steps.push_back(S);
2050}
2051
Eli Friedman78275202009-12-19 08:11:05 +00002052void InitializationSequence::AddStringInitStep(QualType T) {
2053 Step S;
2054 S.Kind = SK_StringInit;
2055 S.Type = T;
2056 Steps.push_back(S);
2057}
2058
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002059void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2060 OverloadingResult Result) {
2061 SequenceKind = FailedSequence;
2062 this->Failure = Failure;
2063 this->FailedOverloadResult = Result;
2064}
2065
2066//===----------------------------------------------------------------------===//
2067// Attempt initialization
2068//===----------------------------------------------------------------------===//
2069
2070/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002071static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002072 const InitializedEntity &Entity,
2073 const InitializationKind &Kind,
2074 InitListExpr *InitList,
2075 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002076 // FIXME: We only perform rudimentary checking of list
2077 // initializations at this point, then assume that any list
2078 // initialization of an array, aggregate, or scalar will be
2079 // well-formed. We we actually "perform" list initialization, we'll
2080 // do all of the necessary checking. C++0x initializer lists will
2081 // force us to perform more checking here.
2082 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2083
Douglas Gregor1b303932009-12-22 15:35:07 +00002084 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002085
2086 // C++ [dcl.init]p13:
2087 // If T is a scalar type, then a declaration of the form
2088 //
2089 // T x = { a };
2090 //
2091 // is equivalent to
2092 //
2093 // T x = a;
2094 if (DestType->isScalarType()) {
2095 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2096 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2097 return;
2098 }
2099
2100 // Assume scalar initialization from a single value works.
2101 } else if (DestType->isAggregateType()) {
2102 // Assume aggregate initialization works.
2103 } else if (DestType->isVectorType()) {
2104 // Assume vector initialization works.
2105 } else if (DestType->isReferenceType()) {
2106 // FIXME: C++0x defines behavior for this.
2107 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2108 return;
2109 } else if (DestType->isRecordType()) {
2110 // FIXME: C++0x defines behavior for this
2111 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2112 }
2113
2114 // Add a general "list initialization" step.
2115 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002116}
2117
2118/// \brief Try a reference initialization that involves calling a conversion
2119/// function.
2120///
2121/// FIXME: look intos DRs 656, 896
2122static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2123 const InitializedEntity &Entity,
2124 const InitializationKind &Kind,
2125 Expr *Initializer,
2126 bool AllowRValues,
2127 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002128 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2130 QualType T1 = cv1T1.getUnqualifiedType();
2131 QualType cv2T2 = Initializer->getType();
2132 QualType T2 = cv2T2.getUnqualifiedType();
2133
2134 bool DerivedToBase;
2135 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2136 T1, T2, DerivedToBase) &&
2137 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002138 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002139
2140 // Build the candidate set directly in the initialization sequence
2141 // structure, so that it will persist if we fail.
2142 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2143 CandidateSet.clear();
2144
2145 // Determine whether we are allowed to call explicit constructors or
2146 // explicit conversion operators.
2147 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2148
2149 const RecordType *T1RecordType = 0;
2150 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2151 // The type we're converting to is a class type. Enumerate its constructors
2152 // to see if there is a suitable conversion.
2153 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2154
2155 DeclarationName ConstructorName
2156 = S.Context.DeclarationNames.getCXXConstructorName(
2157 S.Context.getCanonicalType(T1).getUnqualifiedType());
2158 DeclContext::lookup_iterator Con, ConEnd;
2159 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2160 Con != ConEnd; ++Con) {
2161 // Find the constructor (which may be a template).
2162 CXXConstructorDecl *Constructor = 0;
2163 FunctionTemplateDecl *ConstructorTmpl
2164 = dyn_cast<FunctionTemplateDecl>(*Con);
2165 if (ConstructorTmpl)
2166 Constructor = cast<CXXConstructorDecl>(
2167 ConstructorTmpl->getTemplatedDecl());
2168 else
2169 Constructor = cast<CXXConstructorDecl>(*Con);
2170
2171 if (!Constructor->isInvalidDecl() &&
2172 Constructor->isConvertingConstructor(AllowExplicit)) {
2173 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002174 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2175 ConstructorTmpl->getAccess(),
2176 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002177 &Initializer, 1, CandidateSet);
2178 else
John McCallb89836b2010-01-26 01:37:31 +00002179 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2180 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002181 }
2182 }
2183 }
2184
2185 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2186 // The type we're converting from is a class type, enumerate its conversion
2187 // functions.
2188 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2189
2190 // Determine the type we are converting to. If we are allowed to
2191 // convert to an rvalue, take the type that the destination type
2192 // refers to.
2193 QualType ToType = AllowRValues? cv1T1 : DestType;
2194
John McCallad371252010-01-20 00:46:10 +00002195 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002196 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002197 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2198 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199 NamedDecl *D = *I;
2200 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2201 if (isa<UsingShadowDecl>(D))
2202 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2203
2204 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2205 CXXConversionDecl *Conv;
2206 if (ConvTemplate)
2207 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2208 else
2209 Conv = cast<CXXConversionDecl>(*I);
2210
2211 // If the conversion function doesn't return a reference type,
2212 // it can't be considered for this conversion unless we're allowed to
2213 // consider rvalues.
2214 // FIXME: Do we need to make sure that we only consider conversion
2215 // candidates with reference-compatible results? That might be needed to
2216 // break recursion.
2217 if ((AllowExplicit || !Conv->isExplicit()) &&
2218 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2219 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002220 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2221 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002222 ToType, CandidateSet);
2223 else
John McCallb89836b2010-01-26 01:37:31 +00002224 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2225 Initializer, cv1T1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002226 }
2227 }
2228 }
2229
2230 SourceLocation DeclLoc = Initializer->getLocStart();
2231
2232 // Perform overload resolution. If it fails, return the failed result.
2233 OverloadCandidateSet::iterator Best;
2234 if (OverloadingResult Result
2235 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2236 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002237
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002238 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002239
2240 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002241 if (isa<CXXConversionDecl>(Function))
2242 T2 = Function->getResultType();
2243 else
2244 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002245
2246 // Add the user-defined conversion step.
2247 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2248
2249 // Determine whether we need to perform derived-to-base or
2250 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002251 bool NewDerivedToBase = false;
2252 Sema::ReferenceCompareResult NewRefRelationship
2253 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2254 NewDerivedToBase);
2255 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2256 "Overload resolution picked a bad conversion function");
2257 (void)NewRefRelationship;
2258 if (NewDerivedToBase)
2259 Sequence.AddDerivedToBaseCastStep(
2260 S.Context.getQualifiedType(T1,
2261 T2.getNonReferenceType().getQualifiers()),
2262 /*isLValue=*/true);
2263
2264 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2265 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2266
2267 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2268 return OR_Success;
2269}
2270
2271/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2272static void TryReferenceInitialization(Sema &S,
2273 const InitializedEntity &Entity,
2274 const InitializationKind &Kind,
2275 Expr *Initializer,
2276 InitializationSequence &Sequence) {
2277 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2278
Douglas Gregor1b303932009-12-22 15:35:07 +00002279 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002280 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002281 Qualifiers T1Quals;
2282 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002283 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002284 Qualifiers T2Quals;
2285 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002286 SourceLocation DeclLoc = Initializer->getLocStart();
2287
2288 // If the initializer is the address of an overloaded function, try
2289 // to resolve the overloaded function. If all goes well, T2 is the
2290 // type of the resulting function.
2291 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2292 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2293 T1,
2294 false);
2295 if (!Fn) {
2296 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2297 return;
2298 }
2299
2300 Sequence.AddAddressOverloadResolutionStep(Fn);
2301 cv2T2 = Fn->getType();
2302 T2 = cv2T2.getUnqualifiedType();
2303 }
2304
2305 // FIXME: Rvalue references
2306 bool ForceRValue = false;
2307
2308 // Compute some basic properties of the types and the initializer.
2309 bool isLValueRef = DestType->isLValueReferenceType();
2310 bool isRValueRef = !isLValueRef;
2311 bool DerivedToBase = false;
2312 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2313 Initializer->isLvalue(S.Context);
2314 Sema::ReferenceCompareResult RefRelationship
2315 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2316
2317 // C++0x [dcl.init.ref]p5:
2318 // A reference to type "cv1 T1" is initialized by an expression of type
2319 // "cv2 T2" as follows:
2320 //
2321 // - If the reference is an lvalue reference and the initializer
2322 // expression
2323 OverloadingResult ConvOvlResult = OR_Success;
2324 if (isLValueRef) {
2325 if (InitLvalue == Expr::LV_Valid &&
2326 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2327 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2328 // reference-compatible with "cv2 T2," or
2329 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002330 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002331 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002332 // can occur. However, we do pay attention to whether it is a bit-field
2333 // to decide whether we're actually binding to a temporary created from
2334 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002335 if (DerivedToBase)
2336 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002337 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002338 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002339 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002340 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002341 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
2342 Initializer->getBitField();
2343 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002344 return;
2345 }
2346
2347 // - has a class type (i.e., T2 is a class type), where T1 is not
2348 // reference-related to T2, and can be implicitly converted to an
2349 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2350 // with "cv3 T3" (this conversion is selected by enumerating the
2351 // applicable conversion functions (13.3.1.6) and choosing the best
2352 // one through overload resolution (13.3)),
2353 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2354 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2355 Initializer,
2356 /*AllowRValues=*/false,
2357 Sequence);
2358 if (ConvOvlResult == OR_Success)
2359 return;
John McCall0d1da222010-01-12 00:44:57 +00002360 if (ConvOvlResult != OR_No_Viable_Function) {
2361 Sequence.SetOverloadFailure(
2362 InitializationSequence::FK_ReferenceInitOverloadFailed,
2363 ConvOvlResult);
2364 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365 }
2366 }
2367
2368 // - Otherwise, the reference shall be an lvalue reference to a
2369 // non-volatile const type (i.e., cv1 shall be const), or the reference
2370 // shall be an rvalue reference and the initializer expression shall
2371 // be an rvalue.
Douglas Gregord1e08642010-01-29 19:39:15 +00002372 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002373 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2374 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2375 Sequence.SetOverloadFailure(
2376 InitializationSequence::FK_ReferenceInitOverloadFailed,
2377 ConvOvlResult);
2378 else if (isLValueRef)
2379 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2380 ? (RefRelationship == Sema::Ref_Related
2381 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2382 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2383 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2384 else
2385 Sequence.SetFailed(
2386 InitializationSequence::FK_RValueReferenceBindingToLValue);
2387
2388 return;
2389 }
2390
2391 // - If T1 and T2 are class types and
2392 if (T1->isRecordType() && T2->isRecordType()) {
2393 // - the initializer expression is an rvalue and "cv1 T1" is
2394 // reference-compatible with "cv2 T2", or
2395 if (InitLvalue != Expr::LV_Valid &&
2396 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2397 if (DerivedToBase)
2398 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002399 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002401 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2403 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2404 return;
2405 }
2406
2407 // - T1 is not reference-related to T2 and the initializer expression
2408 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2409 // conversion is selected by enumerating the applicable conversion
2410 // functions (13.3.1.6) and choosing the best one through overload
2411 // resolution (13.3)),
2412 if (RefRelationship == Sema::Ref_Incompatible) {
2413 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2414 Kind, Initializer,
2415 /*AllowRValues=*/true,
2416 Sequence);
2417 if (ConvOvlResult)
2418 Sequence.SetOverloadFailure(
2419 InitializationSequence::FK_ReferenceInitOverloadFailed,
2420 ConvOvlResult);
2421
2422 return;
2423 }
2424
2425 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2426 return;
2427 }
2428
2429 // - If the initializer expression is an rvalue, with T2 an array type,
2430 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2431 // is bound to the object represented by the rvalue (see 3.10).
2432 // FIXME: How can an array type be reference-compatible with anything?
2433 // Don't we mean the element types of T1 and T2?
2434
2435 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2436 // from the initializer expression using the rules for a non-reference
2437 // copy initialization (8.5). The reference is then bound to the
2438 // temporary. [...]
2439 // Determine whether we are allowed to call explicit constructors or
2440 // explicit conversion operators.
2441 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2442 ImplicitConversionSequence ICS
2443 = S.TryImplicitConversion(Initializer, cv1T1,
2444 /*SuppressUserConversions=*/false, AllowExplicit,
2445 /*ForceRValue=*/false,
2446 /*FIXME:InOverloadResolution=*/false,
2447 /*UserCast=*/Kind.isExplicitCast());
2448
John McCall0d1da222010-01-12 00:44:57 +00002449 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002450 // FIXME: Use the conversion function set stored in ICS to turn
2451 // this into an overloading ambiguity diagnostic. However, we need
2452 // to keep that set as an OverloadCandidateSet rather than as some
2453 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002454 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2455 Sequence.SetOverloadFailure(
2456 InitializationSequence::FK_ReferenceInitOverloadFailed,
2457 ConvOvlResult);
2458 else
2459 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 return;
2461 }
2462
2463 // [...] If T1 is reference-related to T2, cv1 must be the
2464 // same cv-qualification as, or greater cv-qualification
2465 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002466 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2467 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002468 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002469 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2471 return;
2472 }
2473
2474 // Perform the actual conversion.
2475 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2476 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2477 return;
2478}
2479
2480/// \brief Attempt character array initialization from a string literal
2481/// (C++ [dcl.init.string], C99 6.7.8).
2482static void TryStringLiteralInitialization(Sema &S,
2483 const InitializedEntity &Entity,
2484 const InitializationKind &Kind,
2485 Expr *Initializer,
2486 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002487 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002488 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489}
2490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002491/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2492/// enumerates the constructors of the initialized entity and performs overload
2493/// resolution to select the best.
2494static void TryConstructorInitialization(Sema &S,
2495 const InitializedEntity &Entity,
2496 const InitializationKind &Kind,
2497 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002498 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002500 if (Kind.getKind() == InitializationKind::IK_Copy)
2501 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2502 else
2503 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002504
2505 // Build the candidate set directly in the initialization sequence
2506 // structure, so that it will persist if we fail.
2507 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2508 CandidateSet.clear();
2509
2510 // Determine whether we are allowed to call explicit constructors or
2511 // explicit conversion operators.
2512 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2513 Kind.getKind() == InitializationKind::IK_Value ||
2514 Kind.getKind() == InitializationKind::IK_Default);
2515
2516 // The type we're converting to is a class type. Enumerate its constructors
2517 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002518 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2519 assert(DestRecordType && "Constructor initialization requires record type");
2520 CXXRecordDecl *DestRecordDecl
2521 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2522
2523 DeclarationName ConstructorName
2524 = S.Context.DeclarationNames.getCXXConstructorName(
2525 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2526 DeclContext::lookup_iterator Con, ConEnd;
2527 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2528 Con != ConEnd; ++Con) {
2529 // Find the constructor (which may be a template).
2530 CXXConstructorDecl *Constructor = 0;
2531 FunctionTemplateDecl *ConstructorTmpl
2532 = dyn_cast<FunctionTemplateDecl>(*Con);
2533 if (ConstructorTmpl)
2534 Constructor = cast<CXXConstructorDecl>(
2535 ConstructorTmpl->getTemplatedDecl());
2536 else
2537 Constructor = cast<CXXConstructorDecl>(*Con);
2538
2539 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002540 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002541 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002542 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2543 ConstructorTmpl->getAccess(),
2544 /*ExplicitArgs*/ 0,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002545 Args, NumArgs, CandidateSet);
2546 else
John McCallb89836b2010-01-26 01:37:31 +00002547 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2548 Args, NumArgs, CandidateSet);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002549 }
2550 }
2551
2552 SourceLocation DeclLoc = Kind.getLocation();
2553
2554 // Perform overload resolution. If it fails, return the failed result.
2555 OverloadCandidateSet::iterator Best;
2556 if (OverloadingResult Result
2557 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2558 Sequence.SetOverloadFailure(
2559 InitializationSequence::FK_ConstructorOverloadFailed,
2560 Result);
2561 return;
2562 }
2563
2564 // Add the constructor initialization step. Any cv-qualification conversion is
2565 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002566 if (Kind.getKind() == InitializationKind::IK_Copy) {
2567 Sequence.AddUserConversionStep(Best->Function, DestType);
2568 } else {
2569 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002570 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002571 DestType);
2572 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002573}
2574
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002575/// \brief Attempt value initialization (C++ [dcl.init]p7).
2576static void TryValueInitialization(Sema &S,
2577 const InitializedEntity &Entity,
2578 const InitializationKind &Kind,
2579 InitializationSequence &Sequence) {
2580 // C++ [dcl.init]p5:
2581 //
2582 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002583 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002584
2585 // -- if T is an array type, then each element is value-initialized;
2586 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2587 T = AT->getElementType();
2588
2589 if (const RecordType *RT = T->getAs<RecordType>()) {
2590 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2591 // -- if T is a class type (clause 9) with a user-declared
2592 // constructor (12.1), then the default constructor for T is
2593 // called (and the initialization is ill-formed if T has no
2594 // accessible default constructor);
2595 //
2596 // FIXME: we really want to refer to a single subobject of the array,
2597 // but Entity doesn't have a way to capture that (yet).
2598 if (ClassDecl->hasUserDeclaredConstructor())
2599 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2600
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002601 // -- if T is a (possibly cv-qualified) non-union class type
2602 // without a user-provided constructor, then the object is
2603 // zero-initialized and, if T’s implicitly-declared default
2604 // constructor is non-trivial, that constructor is called.
2605 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2606 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2607 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002608 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002609 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2610 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002611 }
2612 }
2613
Douglas Gregor1b303932009-12-22 15:35:07 +00002614 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002615 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2616}
2617
Douglas Gregor85dabae2009-12-16 01:38:02 +00002618/// \brief Attempt default initialization (C++ [dcl.init]p6).
2619static void TryDefaultInitialization(Sema &S,
2620 const InitializedEntity &Entity,
2621 const InitializationKind &Kind,
2622 InitializationSequence &Sequence) {
2623 assert(Kind.getKind() == InitializationKind::IK_Default);
2624
2625 // C++ [dcl.init]p6:
2626 // To default-initialize an object of type T means:
2627 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002628 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002629 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2630 DestType = Array->getElementType();
2631
2632 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2633 // constructor for T is called (and the initialization is ill-formed if
2634 // T has no accessible default constructor);
2635 if (DestType->isRecordType()) {
2636 // FIXME: If a program calls for the default initialization of an object of
2637 // a const-qualified type T, T shall be a class type with a user-provided
2638 // default constructor.
2639 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2640 Sequence);
2641 }
2642
2643 // - otherwise, no initialization is performed.
2644 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2645
2646 // If a program calls for the default initialization of an object of
2647 // a const-qualified type T, T shall be a class type with a user-provided
2648 // default constructor.
2649 if (DestType.isConstQualified())
2650 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2651}
2652
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2654/// which enumerates all conversion functions and performs overload resolution
2655/// to select the best.
2656static void TryUserDefinedConversion(Sema &S,
2657 const InitializedEntity &Entity,
2658 const InitializationKind &Kind,
2659 Expr *Initializer,
2660 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002661 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2662
Douglas Gregor1b303932009-12-22 15:35:07 +00002663 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002664 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2665 QualType SourceType = Initializer->getType();
2666 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2667 "Must have a class type to perform a user-defined conversion");
2668
2669 // Build the candidate set directly in the initialization sequence
2670 // structure, so that it will persist if we fail.
2671 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2672 CandidateSet.clear();
2673
2674 // Determine whether we are allowed to call explicit constructors or
2675 // explicit conversion operators.
2676 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2677
2678 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2679 // The type we're converting to is a class type. Enumerate its constructors
2680 // to see if there is a suitable conversion.
2681 CXXRecordDecl *DestRecordDecl
2682 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2683
2684 DeclarationName ConstructorName
2685 = S.Context.DeclarationNames.getCXXConstructorName(
2686 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2687 DeclContext::lookup_iterator Con, ConEnd;
2688 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2689 Con != ConEnd; ++Con) {
2690 // Find the constructor (which may be a template).
2691 CXXConstructorDecl *Constructor = 0;
2692 FunctionTemplateDecl *ConstructorTmpl
2693 = dyn_cast<FunctionTemplateDecl>(*Con);
2694 if (ConstructorTmpl)
2695 Constructor = cast<CXXConstructorDecl>(
2696 ConstructorTmpl->getTemplatedDecl());
2697 else
2698 Constructor = cast<CXXConstructorDecl>(*Con);
2699
2700 if (!Constructor->isInvalidDecl() &&
2701 Constructor->isConvertingConstructor(AllowExplicit)) {
2702 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002703 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2704 ConstructorTmpl->getAccess(),
2705 /*ExplicitArgs*/ 0,
Douglas Gregor540c3b02009-12-14 17:27:33 +00002706 &Initializer, 1, CandidateSet);
2707 else
John McCallb89836b2010-01-26 01:37:31 +00002708 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2709 &Initializer, 1, CandidateSet);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002710 }
2711 }
2712 }
Eli Friedman78275202009-12-19 08:11:05 +00002713
2714 SourceLocation DeclLoc = Initializer->getLocStart();
2715
Douglas Gregor540c3b02009-12-14 17:27:33 +00002716 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2717 // The type we're converting from is a class type, enumerate its conversion
2718 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002719
Eli Friedman4afe9a32009-12-20 22:12:03 +00002720 // We can only enumerate the conversion functions for a complete type; if
2721 // the type isn't complete, simply skip this step.
2722 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2723 CXXRecordDecl *SourceRecordDecl
2724 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002725
John McCallad371252010-01-20 00:46:10 +00002726 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002727 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002728 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002729 E = Conversions->end();
2730 I != E; ++I) {
2731 NamedDecl *D = *I;
2732 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2733 if (isa<UsingShadowDecl>(D))
2734 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2735
2736 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2737 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002738 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002739 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002740 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002741 Conv = cast<CXXConversionDecl>(*I);
2742
2743 if (AllowExplicit || !Conv->isExplicit()) {
2744 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002745 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2746 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002747 CandidateSet);
2748 else
John McCallb89836b2010-01-26 01:37:31 +00002749 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2750 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002751 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002752 }
2753 }
2754 }
2755
Douglas Gregor540c3b02009-12-14 17:27:33 +00002756 // Perform overload resolution. If it fails, return the failed result.
2757 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002758 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002759 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2760 Sequence.SetOverloadFailure(
2761 InitializationSequence::FK_UserConversionOverloadFailed,
2762 Result);
2763 return;
2764 }
John McCall0d1da222010-01-12 00:44:57 +00002765
Douglas Gregor540c3b02009-12-14 17:27:33 +00002766 FunctionDecl *Function = Best->Function;
2767
2768 if (isa<CXXConstructorDecl>(Function)) {
2769 // Add the user-defined conversion step. Any cv-qualification conversion is
2770 // subsumed by the initialization.
2771 Sequence.AddUserConversionStep(Function, DestType);
2772 return;
2773 }
2774
2775 // Add the user-defined conversion step that calls the conversion function.
2776 QualType ConvType = Function->getResultType().getNonReferenceType();
2777 Sequence.AddUserConversionStep(Function, ConvType);
2778
2779 // If the conversion following the call to the conversion function is
2780 // interesting, add it as a separate step.
2781 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2782 Best->FinalConversion.Third) {
2783 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002784 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002785 ICS.Standard = Best->FinalConversion;
2786 Sequence.AddConversionSequenceStep(ICS, DestType);
2787 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002788}
2789
2790/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2791/// non-class type to another.
2792static void TryImplicitConversion(Sema &S,
2793 const InitializedEntity &Entity,
2794 const InitializationKind &Kind,
2795 Expr *Initializer,
2796 InitializationSequence &Sequence) {
2797 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002798 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 /*SuppressUserConversions=*/true,
2800 /*AllowExplicit=*/false,
2801 /*ForceRValue=*/false,
2802 /*FIXME:InOverloadResolution=*/false,
2803 /*UserCast=*/Kind.isExplicitCast());
2804
John McCall0d1da222010-01-12 00:44:57 +00002805 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002806 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2807 return;
2808 }
2809
Douglas Gregor1b303932009-12-22 15:35:07 +00002810 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811}
2812
2813InitializationSequence::InitializationSequence(Sema &S,
2814 const InitializedEntity &Entity,
2815 const InitializationKind &Kind,
2816 Expr **Args,
2817 unsigned NumArgs) {
2818 ASTContext &Context = S.Context;
2819
2820 // C++0x [dcl.init]p16:
2821 // The semantics of initializers are as follows. The destination type is
2822 // the type of the object or reference being initialized and the source
2823 // type is the type of the initializer expression. The source type is not
2824 // defined when the initializer is a braced-init-list or when it is a
2825 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002826 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002827
2828 if (DestType->isDependentType() ||
2829 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2830 SequenceKind = DependentSequence;
2831 return;
2832 }
2833
2834 QualType SourceType;
2835 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002836 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002837 Initializer = Args[0];
2838 if (!isa<InitListExpr>(Initializer))
2839 SourceType = Initializer->getType();
2840 }
2841
2842 // - If the initializer is a braced-init-list, the object is
2843 // list-initialized (8.5.4).
2844 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2845 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002846 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002847 }
2848
2849 // - If the destination type is a reference type, see 8.5.3.
2850 if (DestType->isReferenceType()) {
2851 // C++0x [dcl.init.ref]p1:
2852 // A variable declared to be a T& or T&&, that is, "reference to type T"
2853 // (8.3.2), shall be initialized by an object, or function, of type T or
2854 // by an object that can be converted into a T.
2855 // (Therefore, multiple arguments are not permitted.)
2856 if (NumArgs != 1)
2857 SetFailed(FK_TooManyInitsForReference);
2858 else
2859 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2860 return;
2861 }
2862
2863 // - If the destination type is an array of characters, an array of
2864 // char16_t, an array of char32_t, or an array of wchar_t, and the
2865 // initializer is a string literal, see 8.5.2.
2866 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2867 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2868 return;
2869 }
2870
2871 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002872 if (Kind.getKind() == InitializationKind::IK_Value ||
2873 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002874 TryValueInitialization(S, Entity, Kind, *this);
2875 return;
2876 }
2877
Douglas Gregor85dabae2009-12-16 01:38:02 +00002878 // Handle default initialization.
2879 if (Kind.getKind() == InitializationKind::IK_Default){
2880 TryDefaultInitialization(S, Entity, Kind, *this);
2881 return;
2882 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002883
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002884 // - Otherwise, if the destination type is an array, the program is
2885 // ill-formed.
2886 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2887 if (AT->getElementType()->isAnyCharacterType())
2888 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2889 else
2890 SetFailed(FK_ArrayNeedsInitList);
2891
2892 return;
2893 }
Eli Friedman78275202009-12-19 08:11:05 +00002894
2895 // Handle initialization in C
2896 if (!S.getLangOptions().CPlusPlus) {
2897 setSequenceKind(CAssignment);
2898 AddCAssignmentStep(DestType);
2899 return;
2900 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002901
2902 // - If the destination type is a (possibly cv-qualified) class type:
2903 if (DestType->isRecordType()) {
2904 // - If the initialization is direct-initialization, or if it is
2905 // copy-initialization where the cv-unqualified version of the
2906 // source type is the same class as, or a derived class of, the
2907 // class of the destination, constructors are considered. [...]
2908 if (Kind.getKind() == InitializationKind::IK_Direct ||
2909 (Kind.getKind() == InitializationKind::IK_Copy &&
2910 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2911 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002912 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002913 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002914 // - Otherwise (i.e., for the remaining copy-initialization cases),
2915 // user-defined conversion sequences that can convert from the source
2916 // type to the destination type or (when a conversion function is
2917 // used) to a derived class thereof are enumerated as described in
2918 // 13.3.1.4, and the best one is chosen through overload resolution
2919 // (13.3).
2920 else
2921 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2922 return;
2923 }
2924
Douglas Gregor85dabae2009-12-16 01:38:02 +00002925 if (NumArgs > 1) {
2926 SetFailed(FK_TooManyInitsForScalar);
2927 return;
2928 }
2929 assert(NumArgs == 1 && "Zero-argument case handled above");
2930
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002931 // - Otherwise, if the source type is a (possibly cv-qualified) class
2932 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002933 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002934 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2935 return;
2936 }
2937
2938 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002939 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002940 // conversions (Clause 4) will be used, if necessary, to convert the
2941 // initializer expression to the cv-unqualified version of the
2942 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002943 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002944 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2945}
2946
2947InitializationSequence::~InitializationSequence() {
2948 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2949 StepEnd = Steps.end();
2950 Step != StepEnd; ++Step)
2951 Step->Destroy();
2952}
2953
2954//===----------------------------------------------------------------------===//
2955// Perform initialization
2956//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002957static Sema::AssignmentAction
2958getAssignmentAction(const InitializedEntity &Entity) {
2959 switch(Entity.getKind()) {
2960 case InitializedEntity::EK_Variable:
2961 case InitializedEntity::EK_New:
2962 return Sema::AA_Initializing;
2963
2964 case InitializedEntity::EK_Parameter:
2965 // FIXME: Can we tell when we're sending vs. passing?
2966 return Sema::AA_Passing;
2967
2968 case InitializedEntity::EK_Result:
2969 return Sema::AA_Returning;
2970
2971 case InitializedEntity::EK_Exception:
2972 case InitializedEntity::EK_Base:
2973 llvm_unreachable("No assignment action for C++-specific initialization");
2974 break;
2975
2976 case InitializedEntity::EK_Temporary:
2977 // FIXME: Can we tell apart casting vs. converting?
2978 return Sema::AA_Casting;
2979
2980 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002981 case InitializedEntity::EK_ArrayElement:
2982 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00002983 return Sema::AA_Initializing;
2984 }
2985
2986 return Sema::AA_Converting;
2987}
2988
2989static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2990 bool IsCopy) {
2991 switch (Entity.getKind()) {
2992 case InitializedEntity::EK_Result:
2993 case InitializedEntity::EK_Exception:
Anders Carlsson0bd52402010-01-24 00:19:41 +00002994 case InitializedEntity::EK_ArrayElement:
2995 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00002996 return !IsCopy;
2997
2998 case InitializedEntity::EK_New:
2999 case InitializedEntity::EK_Variable:
3000 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003001 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003002 return false;
3003
3004 case InitializedEntity::EK_Parameter:
3005 case InitializedEntity::EK_Temporary:
3006 return true;
3007 }
3008
3009 llvm_unreachable("missed an InitializedEntity kind?");
3010}
3011
3012/// \brief If we need to perform an additional copy of the initialized object
3013/// for this kind of entity (e.g., the result of a function or an object being
3014/// thrown), make the copy.
3015static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3016 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003017 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003018 Sema::OwningExprResult CurInit) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003019 Expr *CurInitExpr = (Expr *)CurInit.get();
3020
Douglas Gregore1314a62009-12-18 05:02:21 +00003021 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003022
3023 switch (Entity.getKind()) {
3024 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003025 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003026 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003027 Loc = Entity.getReturnLoc();
3028 break;
3029
3030 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003031 Loc = Entity.getThrowLoc();
3032 break;
3033
3034 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003035 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003036 Kind.getKind() != InitializationKind::IK_Copy)
3037 return move(CurInit);
3038 Loc = Entity.getDecl()->getLocation();
3039 break;
3040
Anders Carlsson0bd52402010-01-24 00:19:41 +00003041 case InitializedEntity::EK_ArrayElement:
3042 case InitializedEntity::EK_Member:
3043 if (Entity.getType()->isReferenceType() ||
3044 Kind.getKind() != InitializationKind::IK_Copy)
3045 return move(CurInit);
3046 Loc = CurInitExpr->getLocStart();
3047 break;
3048
Douglas Gregore1314a62009-12-18 05:02:21 +00003049 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003050 // FIXME: Do we need this initialization for a parameter?
3051 return move(CurInit);
3052
Douglas Gregore1314a62009-12-18 05:02:21 +00003053 case InitializedEntity::EK_New:
3054 case InitializedEntity::EK_Temporary:
3055 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003056 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003057 // We don't need to copy for any of these initialized entities.
3058 return move(CurInit);
3059 }
3060
Douglas Gregore1314a62009-12-18 05:02:21 +00003061 CXXRecordDecl *Class = 0;
3062 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3063 Class = cast<CXXRecordDecl>(Record->getDecl());
3064 if (!Class)
3065 return move(CurInit);
3066
3067 // Perform overload resolution using the class's copy constructors.
3068 DeclarationName ConstructorName
3069 = S.Context.DeclarationNames.getCXXConstructorName(
3070 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3071 DeclContext::lookup_iterator Con, ConEnd;
3072 OverloadCandidateSet CandidateSet;
3073 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3074 Con != ConEnd; ++Con) {
3075 // Find the constructor (which may be a template).
3076 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3077 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003078 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003079 continue;
3080
John McCallb89836b2010-01-26 01:37:31 +00003081 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3082 &CurInitExpr, 1, CandidateSet);
Douglas Gregore1314a62009-12-18 05:02:21 +00003083 }
3084
3085 OverloadCandidateSet::iterator Best;
3086 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3087 case OR_Success:
3088 break;
3089
3090 case OR_No_Viable_Function:
3091 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003092 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003093 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003094 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3095 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003096 return S.ExprError();
3097
3098 case OR_Ambiguous:
3099 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003100 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003101 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003102 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3103 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003104 return S.ExprError();
3105
3106 case OR_Deleted:
3107 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003108 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003109 << CurInitExpr->getSourceRange();
3110 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3111 << Best->Function->isDeleted();
3112 return S.ExprError();
3113 }
3114
3115 CurInit.release();
3116 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3117 cast<CXXConstructorDecl>(Best->Function),
3118 /*Elidable=*/true,
3119 Sema::MultiExprArg(S,
3120 (void**)&CurInitExpr, 1));
3121}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122
3123Action::OwningExprResult
3124InitializationSequence::Perform(Sema &S,
3125 const InitializedEntity &Entity,
3126 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003127 Action::MultiExprArg Args,
3128 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003129 if (SequenceKind == FailedSequence) {
3130 unsigned NumArgs = Args.size();
3131 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3132 return S.ExprError();
3133 }
3134
3135 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003136 // If the declaration is a non-dependent, incomplete array type
3137 // that has an initializer, then its type will be completed once
3138 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003139 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003140 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003141 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003142 if (const IncompleteArrayType *ArrayT
3143 = S.Context.getAsIncompleteArrayType(DeclType)) {
3144 // FIXME: We don't currently have the ability to accurately
3145 // compute the length of an initializer list without
3146 // performing full type-checking of the initializer list
3147 // (since we have to determine where braces are implicitly
3148 // introduced and such). So, we fall back to making the array
3149 // type a dependently-sized array type with no specified
3150 // bound.
3151 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3152 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003153
Douglas Gregor51e77d52009-12-10 17:56:55 +00003154 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003155 if (DeclaratorDecl *DD = Entity.getDecl()) {
3156 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3157 TypeLoc TL = TInfo->getTypeLoc();
3158 if (IncompleteArrayTypeLoc *ArrayLoc
3159 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3160 Brackets = ArrayLoc->getBracketsRange();
3161 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003162 }
3163
3164 *ResultType
3165 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3166 /*NumElts=*/0,
3167 ArrayT->getSizeModifier(),
3168 ArrayT->getIndexTypeCVRQualifiers(),
3169 Brackets);
3170 }
3171
3172 }
3173 }
3174
Eli Friedmana553d4a2009-12-22 02:35:53 +00003175 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003176 return Sema::OwningExprResult(S, Args.release()[0]);
3177
3178 unsigned NumArgs = Args.size();
3179 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3180 SourceLocation(),
3181 (Expr **)Args.release(),
3182 NumArgs,
3183 SourceLocation()));
3184 }
3185
Douglas Gregor85dabae2009-12-16 01:38:02 +00003186 if (SequenceKind == NoInitialization)
3187 return S.Owned((Expr *)0);
3188
Douglas Gregor1b303932009-12-22 15:35:07 +00003189 QualType DestType = Entity.getType().getNonReferenceType();
3190 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003191 // the same as Entity.getDecl()->getType() in cases involving type merging,
3192 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003193 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003194 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003195 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003196
Douglas Gregor85dabae2009-12-16 01:38:02 +00003197 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3198
3199 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3200
3201 // For initialization steps that start with a single initializer,
3202 // grab the only argument out the Args and place it into the "current"
3203 // initializer.
3204 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003205 case SK_ResolveAddressOfOverloadedFunction:
3206 case SK_CastDerivedToBaseRValue:
3207 case SK_CastDerivedToBaseLValue:
3208 case SK_BindReference:
3209 case SK_BindReferenceToTemporary:
3210 case SK_UserConversion:
3211 case SK_QualificationConversionLValue:
3212 case SK_QualificationConversionRValue:
3213 case SK_ConversionSequence:
3214 case SK_ListInitialization:
3215 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003216 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003217 assert(Args.size() == 1);
3218 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3219 if (CurInit.isInvalid())
3220 return S.ExprError();
3221 break;
3222
3223 case SK_ConstructorInitialization:
3224 case SK_ZeroInitialization:
3225 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 }
3227
3228 // Walk through the computed steps for the initialization sequence,
3229 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003230 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 for (step_iterator Step = step_begin(), StepEnd = step_end();
3232 Step != StepEnd; ++Step) {
3233 if (CurInit.isInvalid())
3234 return S.ExprError();
3235
3236 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003237 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238
3239 switch (Step->Kind) {
3240 case SK_ResolveAddressOfOverloadedFunction:
3241 // Overload resolution determined which function invoke; update the
3242 // initializer to reflect that choice.
3243 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3244 break;
3245
3246 case SK_CastDerivedToBaseRValue:
3247 case SK_CastDerivedToBaseLValue: {
3248 // We have a derived-to-base cast that produces either an rvalue or an
3249 // lvalue. Perform that cast.
3250
3251 // Casts to inaccessible base classes are allowed with C-style casts.
3252 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3253 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3254 CurInitExpr->getLocStart(),
3255 CurInitExpr->getSourceRange(),
3256 IgnoreBaseAccess))
3257 return S.ExprError();
3258
3259 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3260 CastExpr::CK_DerivedToBase,
3261 (Expr*)CurInit.release(),
3262 Step->Kind == SK_CastDerivedToBaseLValue));
3263 break;
3264 }
3265
3266 case SK_BindReference:
3267 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3268 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3269 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003270 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 << BitField->getDeclName()
3272 << CurInitExpr->getSourceRange();
3273 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3274 return S.ExprError();
3275 }
Anders Carlssona91be642010-01-29 02:47:33 +00003276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277 // Reference binding does not have any corresponding ASTs.
3278
3279 // Check exception specifications
3280 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3281 return S.ExprError();
3282 break;
3283
3284 case SK_BindReferenceToTemporary:
3285 // Check exception specifications
3286 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3287 return S.ExprError();
3288
3289 // FIXME: At present, we have no AST to describe when we need to make a
3290 // temporary to bind a reference to. We should.
3291 break;
3292
3293 case SK_UserConversion: {
3294 // We have a user-defined conversion that invokes either a constructor
3295 // or a conversion function.
3296 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003297 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003298 if (CXXConstructorDecl *Constructor
3299 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3300 // Build a call to the selected constructor.
3301 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3302 SourceLocation Loc = CurInitExpr->getLocStart();
3303 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3304
3305 // Determine the arguments required to actually perform the constructor
3306 // call.
3307 if (S.CompleteConstructorCall(Constructor,
3308 Sema::MultiExprArg(S,
3309 (void **)&CurInitExpr,
3310 1),
3311 Loc, ConstructorArgs))
3312 return S.ExprError();
3313
3314 // Build the an expression that constructs a temporary.
3315 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3316 move_arg(ConstructorArgs));
3317 if (CurInit.isInvalid())
3318 return S.ExprError();
3319
3320 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003321 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3322 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3323 S.IsDerivedFrom(SourceType, Class))
3324 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003325 } else {
3326 // Build a call to the conversion function.
3327 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003328
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 // FIXME: Should we move this initialization into a separate
3330 // derived-to-base conversion? I believe the answer is "no", because
3331 // we don't want to turn off access control here for c-style casts.
3332 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3333 return S.ExprError();
3334
3335 // Do a little dance to make sure that CurInit has the proper
3336 // pointer.
3337 CurInit.release();
3338
3339 // Build the actual call to the conversion function.
3340 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3341 if (CurInit.isInvalid() || !CurInit.get())
3342 return S.ExprError();
3343
3344 CastKind = CastExpr::CK_UserDefinedConversion;
3345 }
3346
Douglas Gregore1314a62009-12-18 05:02:21 +00003347 if (shouldBindAsTemporary(Entity, IsCopy))
3348 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3349
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003350 CurInitExpr = CurInit.takeAs<Expr>();
3351 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3352 CastKind,
3353 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003354 false));
3355
3356 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003357 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003358 break;
3359 }
3360
3361 case SK_QualificationConversionLValue:
3362 case SK_QualificationConversionRValue:
3363 // Perform a qualification conversion; these can never go wrong.
3364 S.ImpCastExprToType(CurInitExpr, Step->Type,
3365 CastExpr::CK_NoOp,
3366 Step->Kind == SK_QualificationConversionLValue);
3367 CurInit.release();
3368 CurInit = S.Owned(CurInitExpr);
3369 break;
3370
3371 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003372 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003373 false, false, *Step->ICS))
3374 return S.ExprError();
3375
3376 CurInit.release();
3377 CurInit = S.Owned(CurInitExpr);
3378 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003379
3380 case SK_ListInitialization: {
3381 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3382 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003383 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003384 return S.ExprError();
3385
3386 CurInit.release();
3387 CurInit = S.Owned(InitList);
3388 break;
3389 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003390
3391 case SK_ConstructorInitialization: {
3392 CXXConstructorDecl *Constructor
3393 = cast<CXXConstructorDecl>(Step->Function);
3394
3395 // Build a call to the selected constructor.
3396 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3397 SourceLocation Loc = Kind.getLocation();
3398
3399 // Determine the arguments required to actually perform the constructor
3400 // call.
3401 if (S.CompleteConstructorCall(Constructor, move(Args),
3402 Loc, ConstructorArgs))
3403 return S.ExprError();
3404
3405 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003406 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003407 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003408 move_arg(ConstructorArgs),
3409 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003410 if (CurInit.isInvalid())
3411 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003412
3413 bool Elidable
3414 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3415 if (shouldBindAsTemporary(Entity, Elidable))
3416 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3417
3418 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003419 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003420 break;
3421 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003422
3423 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003424 step_iterator NextStep = Step;
3425 ++NextStep;
3426 if (NextStep != StepEnd &&
3427 NextStep->Kind == SK_ConstructorInitialization) {
3428 // The need for zero-initialization is recorded directly into
3429 // the call to the object's constructor within the next step.
3430 ConstructorInitRequiresZeroInit = true;
3431 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3432 S.getLangOptions().CPlusPlus &&
3433 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003434 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3435 Kind.getRange().getBegin(),
3436 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003437 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003438 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003439 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003440 break;
3441 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003442
3443 case SK_CAssignment: {
3444 QualType SourceType = CurInitExpr->getType();
3445 Sema::AssignConvertType ConvTy =
3446 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003447
3448 // If this is a call, allow conversion to a transparent union.
3449 if (ConvTy != Sema::Compatible &&
3450 Entity.getKind() == InitializedEntity::EK_Parameter &&
3451 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3452 == Sema::Compatible)
3453 ConvTy = Sema::Compatible;
3454
Douglas Gregore1314a62009-12-18 05:02:21 +00003455 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3456 Step->Type, SourceType,
3457 CurInitExpr, getAssignmentAction(Entity)))
3458 return S.ExprError();
3459
3460 CurInit.release();
3461 CurInit = S.Owned(CurInitExpr);
3462 break;
3463 }
Eli Friedman78275202009-12-19 08:11:05 +00003464
3465 case SK_StringInit: {
3466 QualType Ty = Step->Type;
3467 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3468 break;
3469 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003470 }
3471 }
3472
3473 return move(CurInit);
3474}
3475
3476//===----------------------------------------------------------------------===//
3477// Diagnose initialization failures
3478//===----------------------------------------------------------------------===//
3479bool InitializationSequence::Diagnose(Sema &S,
3480 const InitializedEntity &Entity,
3481 const InitializationKind &Kind,
3482 Expr **Args, unsigned NumArgs) {
3483 if (SequenceKind != FailedSequence)
3484 return false;
3485
Douglas Gregor1b303932009-12-22 15:35:07 +00003486 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003487 switch (Failure) {
3488 case FK_TooManyInitsForReference:
3489 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3490 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3491 break;
3492
3493 case FK_ArrayNeedsInitList:
3494 case FK_ArrayNeedsInitListOrStringLiteral:
3495 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3496 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3497 break;
3498
3499 case FK_AddressOfOverloadFailed:
3500 S.ResolveAddressOfOverloadedFunction(Args[0],
3501 DestType.getNonReferenceType(),
3502 true);
3503 break;
3504
3505 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003506 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 switch (FailedOverloadResult) {
3508 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003509 if (Failure == FK_UserConversionOverloadFailed)
3510 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3511 << Args[0]->getType() << DestType
3512 << Args[0]->getSourceRange();
3513 else
3514 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3515 << DestType << Args[0]->getType()
3516 << Args[0]->getSourceRange();
3517
John McCallad907772010-01-12 07:18:19 +00003518 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3519 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003520 break;
3521
3522 case OR_No_Viable_Function:
3523 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3524 << Args[0]->getType() << DestType.getNonReferenceType()
3525 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003526 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3527 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003528 break;
3529
3530 case OR_Deleted: {
3531 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3532 << Args[0]->getType() << DestType.getNonReferenceType()
3533 << Args[0]->getSourceRange();
3534 OverloadCandidateSet::iterator Best;
3535 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3536 Kind.getLocation(),
3537 Best);
3538 if (Ovl == OR_Deleted) {
3539 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3540 << Best->Function->isDeleted();
3541 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003542 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 }
3544 break;
3545 }
3546
3547 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003548 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 break;
3550 }
3551 break;
3552
3553 case FK_NonConstLValueReferenceBindingToTemporary:
3554 case FK_NonConstLValueReferenceBindingToUnrelated:
3555 S.Diag(Kind.getLocation(),
3556 Failure == FK_NonConstLValueReferenceBindingToTemporary
3557 ? diag::err_lvalue_reference_bind_to_temporary
3558 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00003559 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 << DestType.getNonReferenceType()
3561 << Args[0]->getType()
3562 << Args[0]->getSourceRange();
3563 break;
3564
3565 case FK_RValueReferenceBindingToLValue:
3566 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3567 << Args[0]->getSourceRange();
3568 break;
3569
3570 case FK_ReferenceInitDropsQualifiers:
3571 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3572 << DestType.getNonReferenceType()
3573 << Args[0]->getType()
3574 << Args[0]->getSourceRange();
3575 break;
3576
3577 case FK_ReferenceInitFailed:
3578 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3579 << DestType.getNonReferenceType()
3580 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3581 << Args[0]->getType()
3582 << Args[0]->getSourceRange();
3583 break;
3584
3585 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003586 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3587 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003588 << DestType
3589 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3590 << Args[0]->getType()
3591 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003592 break;
3593
3594 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003595 SourceRange R;
3596
3597 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3598 R = SourceRange(InitList->getInit(1)->getLocStart(),
3599 InitList->getLocEnd());
3600 else
3601 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003602
3603 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003604 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003605 break;
3606 }
3607
3608 case FK_ReferenceBindingToInitList:
3609 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3610 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3611 break;
3612
3613 case FK_InitListBadDestinationType:
3614 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3615 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3616 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003617
3618 case FK_ConstructorOverloadFailed: {
3619 SourceRange ArgsRange;
3620 if (NumArgs)
3621 ArgsRange = SourceRange(Args[0]->getLocStart(),
3622 Args[NumArgs - 1]->getLocEnd());
3623
3624 // FIXME: Using "DestType" for the entity we're printing is probably
3625 // bad.
3626 switch (FailedOverloadResult) {
3627 case OR_Ambiguous:
3628 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3629 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003630 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003631 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003632 break;
3633
3634 case OR_No_Viable_Function:
3635 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3636 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003637 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3638 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003639 break;
3640
3641 case OR_Deleted: {
3642 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3643 << true << DestType << ArgsRange;
3644 OverloadCandidateSet::iterator Best;
3645 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3646 Kind.getLocation(),
3647 Best);
3648 if (Ovl == OR_Deleted) {
3649 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3650 << Best->Function->isDeleted();
3651 } else {
3652 llvm_unreachable("Inconsistent overload resolution?");
3653 }
3654 break;
3655 }
3656
3657 case OR_Success:
3658 llvm_unreachable("Conversion did not fail!");
3659 break;
3660 }
3661 break;
3662 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003663
3664 case FK_DefaultInitOfConst:
3665 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3666 << DestType;
3667 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003668 }
3669
3670 return true;
3671}
Douglas Gregore1314a62009-12-18 05:02:21 +00003672
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003673void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3674 switch (SequenceKind) {
3675 case FailedSequence: {
3676 OS << "Failed sequence: ";
3677 switch (Failure) {
3678 case FK_TooManyInitsForReference:
3679 OS << "too many initializers for reference";
3680 break;
3681
3682 case FK_ArrayNeedsInitList:
3683 OS << "array requires initializer list";
3684 break;
3685
3686 case FK_ArrayNeedsInitListOrStringLiteral:
3687 OS << "array requires initializer list or string literal";
3688 break;
3689
3690 case FK_AddressOfOverloadFailed:
3691 OS << "address of overloaded function failed";
3692 break;
3693
3694 case FK_ReferenceInitOverloadFailed:
3695 OS << "overload resolution for reference initialization failed";
3696 break;
3697
3698 case FK_NonConstLValueReferenceBindingToTemporary:
3699 OS << "non-const lvalue reference bound to temporary";
3700 break;
3701
3702 case FK_NonConstLValueReferenceBindingToUnrelated:
3703 OS << "non-const lvalue reference bound to unrelated type";
3704 break;
3705
3706 case FK_RValueReferenceBindingToLValue:
3707 OS << "rvalue reference bound to an lvalue";
3708 break;
3709
3710 case FK_ReferenceInitDropsQualifiers:
3711 OS << "reference initialization drops qualifiers";
3712 break;
3713
3714 case FK_ReferenceInitFailed:
3715 OS << "reference initialization failed";
3716 break;
3717
3718 case FK_ConversionFailed:
3719 OS << "conversion failed";
3720 break;
3721
3722 case FK_TooManyInitsForScalar:
3723 OS << "too many initializers for scalar";
3724 break;
3725
3726 case FK_ReferenceBindingToInitList:
3727 OS << "referencing binding to initializer list";
3728 break;
3729
3730 case FK_InitListBadDestinationType:
3731 OS << "initializer list for non-aggregate, non-scalar type";
3732 break;
3733
3734 case FK_UserConversionOverloadFailed:
3735 OS << "overloading failed for user-defined conversion";
3736 break;
3737
3738 case FK_ConstructorOverloadFailed:
3739 OS << "constructor overloading failed";
3740 break;
3741
3742 case FK_DefaultInitOfConst:
3743 OS << "default initialization of a const variable";
3744 break;
3745 }
3746 OS << '\n';
3747 return;
3748 }
3749
3750 case DependentSequence:
3751 OS << "Dependent sequence: ";
3752 return;
3753
3754 case UserDefinedConversion:
3755 OS << "User-defined conversion sequence: ";
3756 break;
3757
3758 case ConstructorInitialization:
3759 OS << "Constructor initialization sequence: ";
3760 break;
3761
3762 case ReferenceBinding:
3763 OS << "Reference binding: ";
3764 break;
3765
3766 case ListInitialization:
3767 OS << "List initialization: ";
3768 break;
3769
3770 case ZeroInitialization:
3771 OS << "Zero initialization\n";
3772 return;
3773
3774 case NoInitialization:
3775 OS << "No initialization\n";
3776 return;
3777
3778 case StandardConversion:
3779 OS << "Standard conversion: ";
3780 break;
3781
3782 case CAssignment:
3783 OS << "C assignment: ";
3784 break;
3785
3786 case StringInit:
3787 OS << "String initialization: ";
3788 break;
3789 }
3790
3791 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3792 if (S != step_begin()) {
3793 OS << " -> ";
3794 }
3795
3796 switch (S->Kind) {
3797 case SK_ResolveAddressOfOverloadedFunction:
3798 OS << "resolve address of overloaded function";
3799 break;
3800
3801 case SK_CastDerivedToBaseRValue:
3802 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
3803 break;
3804
3805 case SK_CastDerivedToBaseLValue:
3806 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
3807 break;
3808
3809 case SK_BindReference:
3810 OS << "bind reference to lvalue";
3811 break;
3812
3813 case SK_BindReferenceToTemporary:
3814 OS << "bind reference to a temporary";
3815 break;
3816
3817 case SK_UserConversion:
3818 OS << "user-defined conversion via " << S->Function->getNameAsString();
3819 break;
3820
3821 case SK_QualificationConversionRValue:
3822 OS << "qualification conversion (rvalue)";
3823
3824 case SK_QualificationConversionLValue:
3825 OS << "qualification conversion (lvalue)";
3826 break;
3827
3828 case SK_ConversionSequence:
3829 OS << "implicit conversion sequence (";
3830 S->ICS->DebugPrint(); // FIXME: use OS
3831 OS << ")";
3832 break;
3833
3834 case SK_ListInitialization:
3835 OS << "list initialization";
3836 break;
3837
3838 case SK_ConstructorInitialization:
3839 OS << "constructor initialization";
3840 break;
3841
3842 case SK_ZeroInitialization:
3843 OS << "zero initialization";
3844 break;
3845
3846 case SK_CAssignment:
3847 OS << "C assignment";
3848 break;
3849
3850 case SK_StringInit:
3851 OS << "string initialization";
3852 break;
3853 }
3854 }
3855}
3856
3857void InitializationSequence::dump() const {
3858 dump(llvm::errs());
3859}
3860
Douglas Gregore1314a62009-12-18 05:02:21 +00003861//===----------------------------------------------------------------------===//
3862// Initialization helper functions
3863//===----------------------------------------------------------------------===//
3864Sema::OwningExprResult
3865Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3866 SourceLocation EqualLoc,
3867 OwningExprResult Init) {
3868 if (Init.isInvalid())
3869 return ExprError();
3870
3871 Expr *InitE = (Expr *)Init.get();
3872 assert(InitE && "No initialization expression?");
3873
3874 if (EqualLoc.isInvalid())
3875 EqualLoc = InitE->getLocStart();
3876
3877 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3878 EqualLoc);
3879 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3880 Init.release();
3881 return Seq.Perform(*this, Entity, Kind,
3882 MultiExprArg(*this, (void**)&InitE, 1));
3883}