blob: 29209d97ff782c1f2832f197ea921f8ed766b6ed [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
Mike Stump11289f42009-09-09 15:08:12 +000069static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner94d2f682009-02-24 22:46:58 +000070 bool DirectInit, Sema &S) {
Chris Lattner0cb78032009-02-24 22:27:37 +000071 // Get the type before calling CheckSingleAssignmentConstraints(), since
72 // it can promote the expression.
Mike Stump11289f42009-09-09 15:08:12 +000073 QualType InitType = Init->getType();
74
Chris Lattner94d2f682009-02-24 22:46:58 +000075 if (S.getLangOptions().CPlusPlus) {
Chris Lattner0cb78032009-02-24 22:27:37 +000076 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000077 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000078 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000079 ImplicitConversionSequence ICS;
80 OverloadCandidateSet CandidateSet;
81 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
82 CandidateSet,
Douglas Gregor3e1e5272009-12-09 23:02:17 +000083 true, false, false) != OR_Ambiguous)
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000084 return S.Diag(Init->getSourceRange().getBegin(),
85 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000086 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000087 << Init->getSourceRange();
88 S.Diag(Init->getSourceRange().getBegin(),
89 diag::err_typecheck_convert_ambiguous)
90 << DeclType << Init->getType() << Init->getSourceRange();
John McCallad907772010-01-12 07:18:19 +000091 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates, &Init, 1);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000092 return true;
93 }
Chris Lattner0cb78032009-02-24 22:27:37 +000094 return false;
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Chris Lattner94d2f682009-02-24 22:46:58 +000097 Sema::AssignConvertType ConvTy =
98 S.CheckSingleAssignmentConstraints(DeclType, Init);
99 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000100 InitType, Init, Sema::AA_Initializing);
Chris Lattner0cb78032009-02-24 22:27:37 +0000101}
102
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000103static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
104 // Get the length of the string as parsed.
105 uint64_t StrLength =
106 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
107
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000109 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000110 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000111 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000112 // being initialized to a string literal.
113 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000114 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000115 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000116 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
117 ConstVal,
118 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000119 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Eli Friedman893abe42009-05-29 18:22:49 +0000122 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000123
Eli Friedman893abe42009-05-29 18:22:49 +0000124 // C99 6.7.8p14. We have an array of character type with known size. However,
125 // the size may be smaller or larger than the string we are initializing.
126 // FIXME: Avoid truncation for 64-bit length strings.
127 if (StrLength-1 > CAT->getSize().getZExtValue())
128 S.Diag(Str->getSourceRange().getBegin(),
129 diag::warn_initializer_string_for_char_array_too_long)
130 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
157/// arguments, which contains the current the "structured" (semantic)
158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
177 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000179 unsigned &StructuredIndex,
180 bool TopLevelObject = false);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000181 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000185 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
186 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000187 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000191 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000192 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000193 InitListExpr *StructuredList,
194 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000195 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000199 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000206 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
207 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000208 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000210 unsigned &StructuredIndex,
211 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000212 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
213 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000214 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000217 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000218 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000219 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 RecordDecl::field_iterator *NextField,
221 llvm::APSInt *NextElementIndex,
222 unsigned &Index,
223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000225 bool FinishSubobjectInit,
226 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
228 QualType CurrentObjectType,
229 InitListExpr *StructuredList,
230 unsigned StructuredIndex,
231 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000232 void UpdateStructuredListElement(InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 Expr *expr);
235 int numArrayElements(QualType DeclType);
236 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000237
Douglas Gregor2bb07652009-12-22 00:05:34 +0000238 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
239 const InitializedEntity &ParentEntity,
240 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000241 void FillInValueInitializations(const InitializedEntity &Entity,
242 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000244 InitListChecker(Sema &S, const InitializedEntity &Entity,
245 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000246 bool HadError() { return hadError; }
247
248 // @brief Retrieves the fully-structured initializer list used for
249 // semantic analysis and code generation.
250 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
251};
Chris Lattner9ececce2009-02-24 22:48:58 +0000252} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE,
257 bool &RequiresSecondPass) {
258 SourceLocation Loc = ILE->getSourceRange().getBegin();
259 unsigned NumInits = ILE->getNumInits();
260 InitializedEntity MemberEntity
261 = InitializedEntity::InitializeMember(Field, &ParentEntity);
262 if (Init >= NumInits || !ILE->getInit(Init)) {
263 // FIXME: We probably don't need to handle references
264 // specially here, since value-initialization of references is
265 // handled in InitializationSequence.
266 if (Field->getType()->isReferenceType()) {
267 // C++ [dcl.init.aggr]p9:
268 // If an incomplete or empty initializer-list leaves a
269 // member of reference type uninitialized, the program is
270 // ill-formed.
271 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
272 << Field->getType()
273 << ILE->getSyntacticForm()->getSourceRange();
274 SemaRef.Diag(Field->getLocation(),
275 diag::note_uninit_reference_member);
276 hadError = true;
277 return;
278 }
279
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
283 if (!InitSeq) {
284 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
285 hadError = true;
286 return;
287 }
288
289 Sema::OwningExprResult MemberInit
290 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
291 Sema::MultiExprArg(SemaRef, 0, 0));
292 if (MemberInit.isInvalid()) {
293 hadError = true;
294 return;
295 }
296
297 if (hadError) {
298 // Do nothing
299 } else if (Init < NumInits) {
300 ILE->setInit(Init, MemberInit.takeAs<Expr>());
301 } else if (InitSeq.getKind()
302 == InitializationSequence::ConstructorInitialization) {
303 // Value-initialization requires a constructor call, so
304 // extend the initializer list to include the constructor
305 // call and make a note that we'll need to take another pass
306 // through the initializer list.
307 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
308 RequiresSecondPass = true;
309 }
310 } else if (InitListExpr *InnerILE
311 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
312 FillInValueInitializations(MemberEntity, InnerILE,
313 RequiresSecondPass);
314}
315
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000316/// Recursively replaces NULL values within the given initializer list
317/// with expressions that perform value-initialization of the
318/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000319void
320InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
321 InitListExpr *ILE,
322 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000323 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000324 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 SourceLocation Loc = ILE->getSourceRange().getBegin();
326 if (ILE->getSyntacticForm())
327 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000329 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (RType->getDecl()->isUnion() &&
331 ILE->getInitializedFieldInUnion())
332 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
333 Entity, ILE, RequiresSecondPass);
334 else {
335 unsigned Init = 0;
336 for (RecordDecl::field_iterator
337 Field = RType->getDecl()->field_begin(),
338 FieldEnd = RType->getDecl()->field_end();
339 Field != FieldEnd; ++Field) {
340 if (Field->isUnnamedBitfield())
341 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000342
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000345
346 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
347 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000348 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000351
Douglas Gregor2bb07652009-12-22 00:05:34 +0000352 // Only look at the first initialization of a union.
353 if (RType->getDecl()->isUnion())
354 break;
355 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356 }
357
358 return;
Mike Stump11289f42009-09-09 15:08:12 +0000359 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000360
361 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000362
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000364 unsigned NumInits = ILE->getNumInits();
365 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000366 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000367 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000368 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
369 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000370 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
371 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000372 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000373 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000374 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000375 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
376 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000377 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000378 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000379
Douglas Gregor723796a2009-12-16 06:35:08 +0000380
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000382 if (hadError)
383 return;
384
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
386 ElementEntity.setElementIndex(Init);
387
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000389 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
390 true);
391 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
392 if (!InitSeq) {
393 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 hadError = true;
395 return;
396 }
397
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 Sema::OwningExprResult ElementInit
399 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
400 Sema::MultiExprArg(SemaRef, 0, 0));
401 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000402 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 return;
404 }
405
406 if (hadError) {
407 // Do nothing
408 } else if (Init < NumInits) {
409 ILE->setInit(Init, ElementInit.takeAs<Expr>());
410 } else if (InitSeq.getKind()
411 == InitializationSequence::ConstructorInitialization) {
412 // Value-initialization requires a constructor call, so
413 // extend the initializer list to include the constructor
414 // call and make a note that we'll need to take another pass
415 // through the initializer list.
416 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
417 RequiresSecondPass = true;
418 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000419 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
421 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000422 }
423}
424
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000425
Douglas Gregor723796a2009-12-16 06:35:08 +0000426InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
427 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000428 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000429 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000430
Eli Friedman23a9e312008-05-19 19:16:24 +0000431 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000432 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000434 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000435 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
436 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000437
Douglas Gregor723796a2009-12-16 06:35:08 +0000438 if (!hadError) {
439 bool RequiresSecondPass = false;
440 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000441 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000442 FillInValueInitializations(Entity, FullyStructuredList,
443 RequiresSecondPass);
444 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000445}
446
447int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000448 // FIXME: use a proper constant
449 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000450 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000451 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000452 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
453 }
454 return maxElements;
455}
456
457int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000458 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000459 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000460 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000461 Field = structDecl->field_begin(),
462 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000463 Field != FieldEnd; ++Field) {
464 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
465 ++InitializableMembers;
466 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000467 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000468 return std::min(InitializableMembers, 1);
469 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000470}
471
Mike Stump11289f42009-09-09 15:08:12 +0000472void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 QualType T, unsigned &Index,
474 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000475 unsigned &StructuredIndex,
476 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000477 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Steve Narofff8ecff22008-05-01 22:18:59 +0000479 if (T->isArrayType())
480 maxElements = numArrayElements(T);
481 else if (T->isStructureType() || T->isUnionType())
482 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000483 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000484 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000485 else
486 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000487
Eli Friedmane0f832b2008-05-25 13:49:22 +0000488 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000489 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000490 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000491 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000492 hadError = true;
493 return;
494 }
495
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000496 // Build a structured initializer list corresponding to this subobject.
497 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000498 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
499 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000500 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
501 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000503
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000505 unsigned StartIndex = Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000507 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000508 StructuredSubobjectInitIndex,
509 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000510 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000511 StructuredSubobjectInitList->setType(T);
512
Douglas Gregor5741efb2009-03-01 17:12:46 +0000513 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000514 // range corresponds with the end of the last initializer it used.
515 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000516 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000517 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
518 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
519 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000520}
521
Steve Naroff125d73d2008-05-06 00:23:44 +0000522void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 unsigned &Index,
524 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000525 unsigned &StructuredIndex,
526 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000527 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000528 SyntacticToSemantic[IList] = StructuredList;
529 StructuredList->setSyntacticForm(IList);
Mike Stump11289f42009-09-09 15:08:12 +0000530 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000531 StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000532 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000533 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000534 if (hadError)
535 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000536
Eli Friedman85f54972008-05-25 13:22:35 +0000537 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000538 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000539 if (StructuredIndex == 1 &&
540 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000541 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000543 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000544 hadError = true;
545 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000546 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000547 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000548 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000549 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000550 // Don't complain for incomplete types, since we'll get an error
551 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000553 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000554 CurrentObjectType->isArrayType()? 0 :
555 CurrentObjectType->isVectorType()? 1 :
556 CurrentObjectType->isScalarType()? 2 :
557 CurrentObjectType->isUnionType()? 3 :
558 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000559
560 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000561 if (SemaRef.getLangOptions().CPlusPlus) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Nate Begeman425038c2009-07-07 21:53:06 +0000565 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
566 DK = diag::err_excess_initializers;
567 hadError = true;
568 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000569
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000571 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000572 }
573 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000574
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000575 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000577 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000578 << CodeModificationHint::CreateRemoval(IList->getLocStart())
579 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000580}
581
Eli Friedman23a9e312008-05-19 19:16:24 +0000582void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000583 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000584 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000585 unsigned &Index,
586 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000587 unsigned &StructuredIndex,
588 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 if (DeclType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000590 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000591 } else if (DeclType->isVectorType()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000593 } else if (DeclType->isAggregateType()) {
594 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000595 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000596 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000597 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000598 StructuredList, StructuredIndex,
599 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000600 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000601 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000602 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000603 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000604 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
605 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
627 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000628 } else {
629 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000630 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000631 assert(0 && "Unsupported initializer type");
632 }
633}
634
Eli Friedman23a9e312008-05-19 19:16:24 +0000635void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000636 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000640 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000641 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
642 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000644 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000645 = getStructuredSubobjectInit(IList, Index, ElemType,
646 StructuredList, StructuredIndex,
647 SubInitList->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +0000648 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 newStructuredList, newStructuredIndex);
650 ++StructuredIndex;
651 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000652 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
653 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000654 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000656 } else if (ElemType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000657 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000658 } else if (ElemType->isReferenceType()) {
659 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000660 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000661 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000662 // C++ [dcl.init.aggr]p12:
663 // All implicit type conversions (clause 4) are considered when
664 // initializing the aggregate member with an ini- tializer from
665 // an initializer-list. If the initializer can initialize a
666 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000667 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000668 = SemaRef.TryCopyInitialization(expr, ElemType,
669 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000670 /*ForceRValue=*/false,
671 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000672
John McCall0d1da222010-01-12 00:44:57 +0000673 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000674 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000675 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000676 hadError = true;
677 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
678 ++Index;
679 return;
680 }
681
682 // Fall through for subaggregate initialization
683 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000684 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 //
686 // The initializer for a structure or union object that has
687 // automatic storage duration shall be either an initializer
688 // list as described below, or a single expression that has
689 // compatible structure or union type. In the latter case, the
690 // initial value of the object, including unnamed members, is
691 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000692 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000693 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
695 ++Index;
696 return;
697 }
698
699 // Fall through for subaggregate initialization
700 }
701
702 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000703 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000704 // [...] Otherwise, if the member is itself a non-empty
705 // subaggregate, brace elision is assumed and the initializer is
706 // considered for the initialization of the first member of
707 // the subaggregate.
708 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000709 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000710 StructuredIndex);
711 ++StructuredIndex;
712 } else {
713 // We cannot initialize this element, so let
714 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000715 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 hadError = true;
717 ++Index;
718 ++StructuredIndex;
719 }
720 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000721}
722
Douglas Gregord14247a2009-01-30 22:09:00 +0000723void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000724 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000725 InitListExpr *StructuredList,
726 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000727 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000728 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000729 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000730 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000731 diag::err_many_braces_around_scalar_init)
732 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000733 hadError = true;
734 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000735 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000736 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000737 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000738 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000739 diag::err_designator_for_scalar_init)
740 << DeclType << expr->getSourceRange();
741 hadError = true;
742 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000744 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000745 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000746
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000748 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000749 hadError = true; // types weren't compatible.
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000750 else if (savExpr != expr) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000751 // The type was promoted, update initializer list.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000752 IList->setInit(Index, expr);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000753 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000754 if (hadError)
755 ++StructuredIndex;
756 else
757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000758 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000759 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000760 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000761 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000762 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000763 ++Index;
764 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000766 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000767}
768
Douglas Gregord14247a2009-01-30 22:09:00 +0000769void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
770 unsigned &Index,
771 InitListExpr *StructuredList,
772 unsigned &StructuredIndex) {
773 if (Index < IList->getNumInits()) {
774 Expr *expr = IList->getInit(Index);
775 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000776 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 << DeclType << IList->getSourceRange();
778 hadError = true;
779 ++Index;
780 ++StructuredIndex;
781 return;
Mike Stump11289f42009-09-09 15:08:12 +0000782 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000783
784 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000785 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000786 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000787 /*SuppressUserConversions=*/false,
788 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000789 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000790 hadError = true;
791 else if (savExpr != expr) {
792 // The type was promoted, update initializer list.
793 IList->setInit(Index, expr);
794 }
795 if (hadError)
796 ++StructuredIndex;
797 else
798 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
799 ++Index;
800 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000801 // FIXME: It would be wonderful if we could point at the actual member. In
802 // general, it would be useful to pass location information down the stack,
803 // so that we know the location (or decl) of the "current object" being
804 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000805 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000806 diag::err_init_reference_member_uninitialized)
807 << DeclType
808 << IList->getSourceRange();
809 hadError = true;
810 ++Index;
811 ++StructuredIndex;
812 return;
813 }
814}
815
Mike Stump11289f42009-09-09 15:08:12 +0000816void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000817 unsigned &Index,
818 InitListExpr *StructuredList,
819 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000820 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000821 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000822 unsigned maxElements = VT->getNumElements();
823 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000824 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000825
Nate Begeman5ec4b312009-08-10 23:49:36 +0000826 if (!SemaRef.getLangOptions().OpenCL) {
827 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
828 // Don't attempt to go past the end of the init list
829 if (Index >= IList->getNumInits())
830 break;
831 CheckSubElementType(IList, elementType, Index,
832 StructuredList, StructuredIndex);
833 }
834 } else {
835 // OpenCL initializers allows vectors to be constructed from vectors.
836 for (unsigned i = 0; i < maxElements; ++i) {
837 // Don't attempt to go past the end of the init list
838 if (Index >= IList->getNumInits())
839 break;
840 QualType IType = IList->getInit(Index)->getType();
841 if (!IType->isVectorType()) {
842 CheckSubElementType(IList, elementType, Index,
843 StructuredList, StructuredIndex);
844 ++numEltsInit;
845 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000846 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 unsigned numIElts = IVT->getNumElements();
848 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
849 numIElts);
850 CheckSubElementType(IList, VecType, Index,
851 StructuredList, StructuredIndex);
852 numEltsInit += numIElts;
853 }
854 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Nate Begeman5ec4b312009-08-10 23:49:36 +0000857 // OpenCL & AltiVec require all elements to be initialized.
858 if (numEltsInit != maxElements)
859 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
860 SemaRef.Diag(IList->getSourceRange().getBegin(),
861 diag::err_vector_incorrect_num_initializers)
862 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000863 }
864}
865
Mike Stump11289f42009-09-09 15:08:12 +0000866void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000867 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000868 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000869 unsigned &Index,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000872 // Check for the special-case of initializing an array with a string.
873 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000874 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
875 SemaRef.Context)) {
876 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000877 // We place the string literal directly into the resulting
878 // initializer list. This is the only place where the structure
879 // of the structured initializer list doesn't match exactly,
880 // because doing so would involve allocating one character
881 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000882 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000883 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000884 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000885 return;
886 }
887 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000888 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000889 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000890 // Check for VLAs; in standard C it would be possible to check this
891 // earlier, but I don't know where clang accepts VLAs (gcc accepts
892 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000893 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000894 diag::err_variable_object_no_init)
895 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000896 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000897 ++Index;
898 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000899 return;
900 }
901
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000902 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 llvm::APSInt maxElements(elementIndex.getBitWidth(),
904 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000905 bool maxElementsKnown = false;
906 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000907 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000908 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000909 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000910 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000911 maxElementsKnown = true;
912 }
913
Chris Lattnerb0912a52009-02-24 22:50:46 +0000914 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000915 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000916 while (Index < IList->getNumInits()) {
917 Expr *Init = IList->getInit(Index);
918 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000919 // If we're not the subobject that matches up with the '{' for
920 // the designator, we shouldn't be handling the
921 // designator. Return immediately.
922 if (!SubobjectIsDesignatorContext)
923 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000924
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000925 // Handle this designated initializer. elementIndex will be
926 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000928 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000929 StructuredList, StructuredIndex, true,
930 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000931 hadError = true;
932 continue;
933 }
934
Douglas Gregor033d1252009-01-23 16:54:12 +0000935 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
936 maxElements.extend(elementIndex.getBitWidth());
937 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
938 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000939 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000940
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000941 // If the array is of incomplete type, keep track of the number of
942 // elements in the initializer.
943 if (!maxElementsKnown && elementIndex > maxElements)
944 maxElements = elementIndex;
945
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000946 continue;
947 }
948
949 // If we know the maximum number of elements, and we've already
950 // hit it, stop consuming elements in the initializer list.
951 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000952 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000953
954 // Check this element.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000955 CheckSubElementType(IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000956 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000957 ++elementIndex;
958
959 // If the array is of incomplete type, keep track of the number of
960 // elements in the initializer.
961 if (!maxElementsKnown && elementIndex > maxElements)
962 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000963 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000964 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000965 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000966 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000967 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000968 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000969 // Sizing an array implicitly to zero is not allowed by ISO C,
970 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000971 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000972 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000973 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000974
Mike Stump11289f42009-09-09 15:08:12 +0000975 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000976 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000977 }
978}
979
Mike Stump11289f42009-09-09 15:08:12 +0000980void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
981 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000982 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +0000983 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000984 unsigned &Index,
985 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000986 unsigned &StructuredIndex,
987 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000988 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000989
Eli Friedman23a9e312008-05-19 19:16:24 +0000990 // If the record is invalid, some of it's members are invalid. To avoid
991 // confusion, we forgo checking the intializer for the entire record.
992 if (structDecl->isInvalidDecl()) {
993 hadError = true;
994 return;
Mike Stump11289f42009-09-09 15:08:12 +0000995 }
Douglas Gregor0202cb42009-01-29 17:44:32 +0000996
997 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
998 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000999 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001000 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001001 Field != FieldEnd; ++Field) {
1002 if (Field->getDeclName()) {
1003 StructuredList->setInitializedFieldInUnion(*Field);
1004 break;
1005 }
1006 }
1007 return;
1008 }
1009
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001010 // If structDecl is a forward declaration, this loop won't do
1011 // anything except look at designated initializers; That's okay,
1012 // because an error should get printed out elsewhere. It might be
1013 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001014 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001015 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001016 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001017 while (Index < IList->getNumInits()) {
1018 Expr *Init = IList->getInit(Index);
1019
1020 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001021 // If we're not the subobject that matches up with the '{' for
1022 // the designator, we shouldn't be handling the
1023 // designator. Return immediately.
1024 if (!SubobjectIsDesignatorContext)
1025 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001027 // Handle this designated initializer. Field will be updated to
1028 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001029 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001030 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001031 StructuredList, StructuredIndex,
1032 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001033 hadError = true;
1034
Douglas Gregora9add4e2009-02-12 19:00:39 +00001035 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001036 continue;
1037 }
1038
1039 if (Field == FieldEnd) {
1040 // We've run out of fields. We're done.
1041 break;
1042 }
1043
Douglas Gregora9add4e2009-02-12 19:00:39 +00001044 // We've already initialized a member of a union. We're done.
1045 if (InitializedSomething && DeclType->isUnionType())
1046 break;
1047
Douglas Gregor91f84212008-12-11 16:49:14 +00001048 // If we've hit the flexible array member at the end, we're done.
1049 if (Field->getType()->isIncompleteArrayType())
1050 break;
1051
Douglas Gregor51695702009-01-29 16:53:55 +00001052 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001053 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001054 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001055 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001056 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001057
Douglas Gregorf6d27522009-01-29 00:39:20 +00001058 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001059 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001060 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001061
1062 if (DeclType->isUnionType()) {
1063 // Initialize the first field within the union.
1064 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001065 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001066
1067 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001068 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001069
Mike Stump11289f42009-09-09 15:08:12 +00001070 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001071 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001072 return;
1073
1074 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001075 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001076 (!isa<InitListExpr>(IList->getInit(Index)) ||
1077 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001078 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001079 diag::err_flexible_array_init_nonempty)
1080 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001081 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001082 << *Field;
1083 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001084 ++Index;
1085 return;
1086 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001087 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001088 diag::ext_flexible_array_init)
1089 << IList->getInit(Index)->getSourceRange().getBegin();
1090 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1091 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001092 }
1093
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001094 if (isa<InitListExpr>(IList->getInit(Index)))
1095 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1096 StructuredIndex);
1097 else
1098 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1099 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001100}
Steve Narofff8ecff22008-05-01 22:18:59 +00001101
Douglas Gregord5846a12009-04-15 06:41:24 +00001102/// \brief Expand a field designator that refers to a member of an
1103/// anonymous struct or union into a series of field designators that
1104/// refers to the field within the appropriate subobject.
1105///
1106/// Field/FieldIndex will be updated to point to the (new)
1107/// currently-designated field.
1108static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001109 DesignatedInitExpr *DIE,
1110 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001111 FieldDecl *Field,
1112 RecordDecl::field_iterator &FieldIter,
1113 unsigned &FieldIndex) {
1114 typedef DesignatedInitExpr::Designator Designator;
1115
1116 // Build the path from the current object to the member of the
1117 // anonymous struct/union (backwards).
1118 llvm::SmallVector<FieldDecl *, 4> Path;
1119 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregord5846a12009-04-15 06:41:24 +00001121 // Build the replacement designators.
1122 llvm::SmallVector<Designator, 4> Replacements;
1123 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1124 FI = Path.rbegin(), FIEnd = Path.rend();
1125 FI != FIEnd; ++FI) {
1126 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001127 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001128 DIE->getDesignator(DesigIdx)->getDotLoc(),
1129 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1130 else
1131 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1132 SourceLocation()));
1133 Replacements.back().setField(*FI);
1134 }
1135
1136 // Expand the current designator into the set of replacement
1137 // designators, so we have a full subobject path down to where the
1138 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001139 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001140 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregord5846a12009-04-15 06:41:24 +00001142 // Update FieldIter/FieldIndex;
1143 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001144 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001145 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001146 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001147 FieldIter != FEnd; ++FieldIter) {
1148 if (FieldIter->isUnnamedBitfield())
1149 continue;
1150
1151 if (*FieldIter == Path.back())
1152 return;
1153
1154 ++FieldIndex;
1155 }
1156
1157 assert(false && "Unable to find anonymous struct/union field");
1158}
1159
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001160/// @brief Check the well-formedness of a C99 designated initializer.
1161///
1162/// Determines whether the designated initializer @p DIE, which
1163/// resides at the given @p Index within the initializer list @p
1164/// IList, is well-formed for a current object of type @p DeclType
1165/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001166/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001167/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001168///
1169/// @param IList The initializer list in which this designated
1170/// initializer occurs.
1171///
Douglas Gregora5324162009-04-15 04:56:10 +00001172/// @param DIE The designated initializer expression.
1173///
1174/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001175///
1176/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1177/// into which the designation in @p DIE should refer.
1178///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001179/// @param NextField If non-NULL and the first designator in @p DIE is
1180/// a field, this will be set to the field declaration corresponding
1181/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001182///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001183/// @param NextElementIndex If non-NULL and the first designator in @p
1184/// DIE is an array designator or GNU array-range designator, this
1185/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001186///
1187/// @param Index Index into @p IList where the designated initializer
1188/// @p DIE occurs.
1189///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001190/// @param StructuredList The initializer list expression that
1191/// describes all of the subobject initializers in the order they'll
1192/// actually be initialized.
1193///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001194/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001195bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001196InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001197 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001198 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001199 QualType &CurrentObjectType,
1200 RecordDecl::field_iterator *NextField,
1201 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001202 unsigned &Index,
1203 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001204 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001205 bool FinishSubobjectInit,
1206 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001207 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001208 // Check the actual initialization for the designated object type.
1209 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001210
1211 // Temporarily remove the designator expression from the
1212 // initializer list that the child calls see, so that we don't try
1213 // to re-process the designator.
1214 unsigned OldIndex = Index;
1215 IList->setInit(OldIndex, DIE->getInit());
1216
1217 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001218 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001219
1220 // Restore the designated initializer expression in the syntactic
1221 // form of the initializer list.
1222 if (IList->getInit(OldIndex) != DIE->getInit())
1223 DIE->setInit(IList->getInit(OldIndex));
1224 IList->setInit(OldIndex, DIE);
1225
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001226 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 }
1228
Douglas Gregora5324162009-04-15 04:56:10 +00001229 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001230 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001231 "Need a non-designated initializer list to start from");
1232
Douglas Gregora5324162009-04-15 04:56:10 +00001233 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001234 // Determine the structural initializer list that corresponds to the
1235 // current subobject.
1236 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001237 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001238 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001239 SourceRange(D->getStartLocation(),
1240 DIE->getSourceRange().getEnd()));
1241 assert(StructuredList && "Expected a structured initializer list");
1242
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001243 if (D->isFieldDesignator()) {
1244 // C99 6.7.8p7:
1245 //
1246 // If a designator has the form
1247 //
1248 // . identifier
1249 //
1250 // then the current object (defined below) shall have
1251 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001252 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001254 if (!RT) {
1255 SourceLocation Loc = D->getDotLoc();
1256 if (Loc.isInvalid())
1257 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001258 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1259 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001260 ++Index;
1261 return true;
1262 }
1263
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001264 // Note: we perform a linear search of the fields here, despite
1265 // the fact that we have a faster lookup method, because we always
1266 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001267 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001269 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001270 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001271 Field = RT->getDecl()->field_begin(),
1272 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001273 for (; Field != FieldEnd; ++Field) {
1274 if (Field->isUnnamedBitfield())
1275 continue;
1276
Douglas Gregord5846a12009-04-15 06:41:24 +00001277 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001278 break;
1279
1280 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001281 }
1282
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001283 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001284 // There was no normal field in the struct with the designated
1285 // name. Perform another lookup for this name, which may find
1286 // something that we can't designate (e.g., a member function),
1287 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001288 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001289 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001290 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001291 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001292 // Name lookup didn't find anything. Determine whether this
1293 // was a typo for another field name.
1294 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1295 Sema::LookupMemberName);
1296 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1297 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1298 ReplacementField->getDeclContext()->getLookupContext()
1299 ->Equals(RT->getDecl())) {
1300 SemaRef.Diag(D->getFieldLoc(),
1301 diag::err_field_designator_unknown_suggest)
1302 << FieldName << CurrentObjectType << R.getLookupName()
1303 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1304 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001305 SemaRef.Diag(ReplacementField->getLocation(),
1306 diag::note_previous_decl)
1307 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001308 } else {
1309 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1310 << FieldName << CurrentObjectType;
1311 ++Index;
1312 return true;
1313 }
1314 } else if (!KnownField) {
1315 // Determine whether we found a field at all.
1316 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1317 }
1318
1319 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001320 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001321 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001322 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001323 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001324 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001325 ++Index;
1326 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001327 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001328
1329 if (!KnownField &&
1330 cast<RecordDecl>((ReplacementField)->getDeclContext())
1331 ->isAnonymousStructOrUnion()) {
1332 // Handle an field designator that refers to a member of an
1333 // anonymous struct or union.
1334 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1335 ReplacementField,
1336 Field, FieldIndex);
1337 D = DIE->getDesignator(DesigIdx);
1338 } else if (!KnownField) {
1339 // The replacement field comes from typo correction; find it
1340 // in the list of fields.
1341 FieldIndex = 0;
1342 Field = RT->getDecl()->field_begin();
1343 for (; Field != FieldEnd; ++Field) {
1344 if (Field->isUnnamedBitfield())
1345 continue;
1346
1347 if (ReplacementField == *Field ||
1348 Field->getIdentifier() == ReplacementField->getIdentifier())
1349 break;
1350
1351 ++FieldIndex;
1352 }
1353 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001354 } else if (!KnownField &&
1355 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001356 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001357 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1358 Field, FieldIndex);
1359 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001360 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001361
1362 // All of the fields of a union are located at the same place in
1363 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001364 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001366 StructuredList->setInitializedFieldInUnion(*Field);
1367 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001368
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001369 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001370 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001372 // Make sure that our non-designated initializer list has space
1373 // for a subobject corresponding to this field.
1374 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001375 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001376
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001377 // This designator names a flexible array member.
1378 if (Field->getType()->isIncompleteArrayType()) {
1379 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001380 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001381 // We can't designate an object within the flexible array
1382 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001383 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001384 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001385 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001386 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001387 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001388 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001389 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001390 << *Field;
1391 Invalid = true;
1392 }
1393
1394 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1395 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001396 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001397 diag::err_flexible_array_init_needs_braces)
1398 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001399 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001400 << *Field;
1401 Invalid = true;
1402 }
1403
1404 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001405 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001406 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001407 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001408 diag::err_flexible_array_init_nonempty)
1409 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001410 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001411 << *Field;
1412 Invalid = true;
1413 }
1414
1415 if (Invalid) {
1416 ++Index;
1417 return true;
1418 }
1419
1420 // Initialize the array.
1421 bool prevHadError = hadError;
1422 unsigned newStructuredIndex = FieldIndex;
1423 unsigned OldIndex = Index;
1424 IList->setInit(Index, DIE->getInit());
Mike Stump11289f42009-09-09 15:08:12 +00001425 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001426 StructuredList, newStructuredIndex);
1427 IList->setInit(OldIndex, DIE);
1428 if (hadError && !prevHadError) {
1429 ++Field;
1430 ++FieldIndex;
1431 if (NextField)
1432 *NextField = Field;
1433 StructuredIndex = FieldIndex;
1434 return true;
1435 }
1436 } else {
1437 // Recurse to check later designated subobjects.
1438 QualType FieldType = (*Field)->getType();
1439 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001440 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1441 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001442 true, false))
1443 return true;
1444 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001445
1446 // Find the position of the next field to be initialized in this
1447 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001448 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001449 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001450
1451 // If this the first designator, our caller will continue checking
1452 // the rest of this struct/class/union subobject.
1453 if (IsFirstDesignator) {
1454 if (NextField)
1455 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001456 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001457 return false;
1458 }
1459
Douglas Gregor17bd0942009-01-28 23:36:17 +00001460 if (!FinishSubobjectInit)
1461 return false;
1462
Douglas Gregord5846a12009-04-15 06:41:24 +00001463 // We've already initialized something in the union; we're done.
1464 if (RT->getDecl()->isUnion())
1465 return hadError;
1466
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001467 // Check the remaining fields within this class/struct/union subobject.
1468 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001469 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1470 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001471 return hadError && !prevHadError;
1472 }
1473
1474 // C99 6.7.8p6:
1475 //
1476 // If a designator has the form
1477 //
1478 // [ constant-expression ]
1479 //
1480 // then the current object (defined below) shall have array
1481 // type and the expression shall be an integer constant
1482 // expression. If the array is of unknown size, any
1483 // nonnegative value is valid.
1484 //
1485 // Additionally, cope with the GNU extension that permits
1486 // designators of the form
1487 //
1488 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001489 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001490 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001491 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001492 << CurrentObjectType;
1493 ++Index;
1494 return true;
1495 }
1496
1497 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001498 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1499 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001500 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001501 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001502 DesignatedEndIndex = DesignatedStartIndex;
1503 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001504 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001505
Mike Stump11289f42009-09-09 15:08:12 +00001506
1507 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001508 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001509 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001510 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001511 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001512
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001513 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001514 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001515 }
1516
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001517 if (isa<ConstantArrayType>(AT)) {
1518 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001519 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1520 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1521 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1522 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1523 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001524 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001525 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001526 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527 << IndexExpr->getSourceRange();
1528 ++Index;
1529 return true;
1530 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001531 } else {
1532 // Make sure the bit-widths and signedness match.
1533 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1534 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001535 else if (DesignatedStartIndex.getBitWidth() <
1536 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001537 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1538 DesignatedStartIndex.setIsUnsigned(true);
1539 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001542 // Make sure that our non-designated initializer list has space
1543 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001544 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001545 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001546 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001547
Douglas Gregor17bd0942009-01-28 23:36:17 +00001548 // Repeatedly perform subobject initializations in the range
1549 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001550
Douglas Gregor17bd0942009-01-28 23:36:17 +00001551 // Move to the next designator
1552 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1553 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001554 while (DesignatedStartIndex <= DesignatedEndIndex) {
1555 // Recurse to check later designated subobjects.
1556 QualType ElementType = AT->getElementType();
1557 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001558 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1559 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001560 (DesignatedStartIndex == DesignatedEndIndex),
1561 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001562 return true;
1563
1564 // Move to the next index in the array that we'll be initializing.
1565 ++DesignatedStartIndex;
1566 ElementIndex = DesignatedStartIndex.getZExtValue();
1567 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001568
1569 // If this the first designator, our caller will continue checking
1570 // the rest of this array subobject.
1571 if (IsFirstDesignator) {
1572 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001573 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001574 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575 return false;
1576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Douglas Gregor17bd0942009-01-28 23:36:17 +00001578 if (!FinishSubobjectInit)
1579 return false;
1580
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001582 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001583 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001584 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001585 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001586}
1587
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001588// Get the structured initializer list for a subobject of type
1589// @p CurrentObjectType.
1590InitListExpr *
1591InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1592 QualType CurrentObjectType,
1593 InitListExpr *StructuredList,
1594 unsigned StructuredIndex,
1595 SourceRange InitRange) {
1596 Expr *ExistingInit = 0;
1597 if (!StructuredList)
1598 ExistingInit = SyntacticToSemantic[IList];
1599 else if (StructuredIndex < StructuredList->getNumInits())
1600 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001602 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1603 return Result;
1604
1605 if (ExistingInit) {
1606 // We are creating an initializer list that initializes the
1607 // subobjects of the current object, but there was already an
1608 // initialization that completely initialized the current
1609 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001610 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 // struct X { int a, b; };
1612 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001613 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001614 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1615 // designated initializer re-initializes the whole
1616 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001617 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001618 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001619 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001620 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001621 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001622 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 << ExistingInit->getSourceRange();
1624 }
1625
Mike Stump11289f42009-09-09 15:08:12 +00001626 InitListExpr *Result
1627 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001628 InitRange.getEnd());
1629
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630 Result->setType(CurrentObjectType);
1631
Douglas Gregor6d00c992009-03-20 23:58:33 +00001632 // Pre-allocate storage for the structured initializer list.
1633 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001634 unsigned NumInits = 0;
1635 if (!StructuredList)
1636 NumInits = IList->getNumInits();
1637 else if (Index < IList->getNumInits()) {
1638 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1639 NumInits = SubList->getNumInits();
1640 }
1641
Mike Stump11289f42009-09-09 15:08:12 +00001642 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001643 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1644 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1645 NumElements = CAType->getSize().getZExtValue();
1646 // Simple heuristic so that we don't allocate a very large
1647 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001648 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001649 NumElements = 0;
1650 }
John McCall9dd450b2009-09-21 23:43:11 +00001651 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001652 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001653 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001654 RecordDecl *RDecl = RType->getDecl();
1655 if (RDecl->isUnion())
1656 NumElements = 1;
1657 else
Mike Stump11289f42009-09-09 15:08:12 +00001658 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001659 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001660 }
1661
Douglas Gregor221c9a52009-03-21 18:13:52 +00001662 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001663 NumElements = IList->getNumInits();
1664
1665 Result->reserveInits(NumElements);
1666
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 // Link this new initializer list into the structured initializer
1668 // lists.
1669 if (StructuredList)
1670 StructuredList->updateInit(StructuredIndex, Result);
1671 else {
1672 Result->setSyntacticForm(IList);
1673 SyntacticToSemantic[IList] = Result;
1674 }
1675
1676 return Result;
1677}
1678
1679/// Update the initializer at index @p StructuredIndex within the
1680/// structured initializer list to the value @p expr.
1681void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1682 unsigned &StructuredIndex,
1683 Expr *expr) {
1684 // No structured initializer list to update
1685 if (!StructuredList)
1686 return;
1687
1688 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1689 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001690 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 diag::warn_initializer_overrides)
1692 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001693 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001695 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 << PrevInit->getSourceRange();
1697 }
Mike Stump11289f42009-09-09 15:08:12 +00001698
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001699 ++StructuredIndex;
1700}
1701
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001702/// Check that the given Index expression is a valid array designator
1703/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001704/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001705/// and produces a reasonable diagnostic if there is a
1706/// failure. Returns true if there was an error, false otherwise. If
1707/// everything went okay, Value will receive the value of the constant
1708/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001709static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001710CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001711 SourceLocation Loc = Index->getSourceRange().getBegin();
1712
1713 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001714 if (S.VerifyIntegerConstantExpression(Index, &Value))
1715 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001716
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001717 if (Value.isSigned() && Value.isNegative())
1718 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001719 << Value.toString(10) << Index->getSourceRange();
1720
Douglas Gregor51650d32009-01-23 21:04:18 +00001721 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001722 return false;
1723}
1724
1725Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1726 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001727 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001728 OwningExprResult Init) {
1729 typedef DesignatedInitExpr::Designator ASTDesignator;
1730
1731 bool Invalid = false;
1732 llvm::SmallVector<ASTDesignator, 32> Designators;
1733 llvm::SmallVector<Expr *, 32> InitExpressions;
1734
1735 // Build designators and check array designator expressions.
1736 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1737 const Designator &D = Desig.getDesignator(Idx);
1738 switch (D.getKind()) {
1739 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001740 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001741 D.getFieldLoc()));
1742 break;
1743
1744 case Designator::ArrayDesignator: {
1745 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1746 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001747 if (!Index->isTypeDependent() &&
1748 !Index->isValueDependent() &&
1749 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001750 Invalid = true;
1751 else {
1752 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001753 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001754 D.getRBracketLoc()));
1755 InitExpressions.push_back(Index);
1756 }
1757 break;
1758 }
1759
1760 case Designator::ArrayRangeDesignator: {
1761 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1762 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1763 llvm::APSInt StartValue;
1764 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001765 bool StartDependent = StartIndex->isTypeDependent() ||
1766 StartIndex->isValueDependent();
1767 bool EndDependent = EndIndex->isTypeDependent() ||
1768 EndIndex->isValueDependent();
1769 if ((!StartDependent &&
1770 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1771 (!EndDependent &&
1772 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001773 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001774 else {
1775 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001776 if (StartDependent || EndDependent) {
1777 // Nothing to compute.
1778 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001779 EndValue.extend(StartValue.getBitWidth());
1780 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1781 StartValue.extend(EndValue.getBitWidth());
1782
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001783 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001784 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001785 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001786 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1787 Invalid = true;
1788 } else {
1789 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001790 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001791 D.getEllipsisLoc(),
1792 D.getRBracketLoc()));
1793 InitExpressions.push_back(StartIndex);
1794 InitExpressions.push_back(EndIndex);
1795 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796 }
1797 break;
1798 }
1799 }
1800 }
1801
1802 if (Invalid || Init.isInvalid())
1803 return ExprError();
1804
1805 // Clear out the expressions within the designation.
1806 Desig.ClearExprs(*this);
1807
1808 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001809 = DesignatedInitExpr::Create(Context,
1810 Designators.data(), Designators.size(),
1811 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001812 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813 return Owned(DIE);
1814}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001815
Douglas Gregor723796a2009-12-16 06:35:08 +00001816bool Sema::CheckInitList(const InitializedEntity &Entity,
1817 InitListExpr *&InitList, QualType &DeclType) {
1818 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001819 if (!CheckInitList.HadError())
1820 InitList = CheckInitList.getFullyStructuredList();
1821
1822 return CheckInitList.HadError();
1823}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001824
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001825//===----------------------------------------------------------------------===//
1826// Initialization entity
1827//===----------------------------------------------------------------------===//
1828
Douglas Gregor723796a2009-12-16 06:35:08 +00001829InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1830 const InitializedEntity &Parent)
1831 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1832{
Douglas Gregor1b303932009-12-22 15:35:07 +00001833 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType()))
1834 Type = AT->getElementType();
Douglas Gregor723796a2009-12-16 06:35:08 +00001835 else
Douglas Gregor1b303932009-12-22 15:35:07 +00001836 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001837}
1838
1839InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1840 CXXBaseSpecifier *Base)
1841{
1842 InitializedEntity Result;
1843 Result.Kind = EK_Base;
1844 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001845 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001846 return Result;
1847}
1848
Douglas Gregor85dabae2009-12-16 01:38:02 +00001849DeclarationName InitializedEntity::getName() const {
1850 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001851 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001852 if (!VariableOrMember)
1853 return DeclarationName();
1854 // Fall through
1855
1856 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001857 case EK_Member:
1858 return VariableOrMember->getDeclName();
1859
1860 case EK_Result:
1861 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001862 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001863 case EK_Temporary:
1864 case EK_Base:
Douglas Gregor723796a2009-12-16 06:35:08 +00001865 case EK_ArrayOrVectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001866 return DeclarationName();
1867 }
1868
1869 // Silence GCC warning
1870 return DeclarationName();
1871}
1872
Douglas Gregora4b592a2009-12-19 03:01:41 +00001873DeclaratorDecl *InitializedEntity::getDecl() const {
1874 switch (getKind()) {
1875 case EK_Variable:
1876 case EK_Parameter:
1877 case EK_Member:
1878 return VariableOrMember;
1879
1880 case EK_Result:
1881 case EK_Exception:
1882 case EK_New:
1883 case EK_Temporary:
1884 case EK_Base:
1885 case EK_ArrayOrVectorElement:
1886 return 0;
1887 }
1888
1889 // Silence GCC warning
1890 return 0;
1891}
1892
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001893//===----------------------------------------------------------------------===//
1894// Initialization sequence
1895//===----------------------------------------------------------------------===//
1896
1897void InitializationSequence::Step::Destroy() {
1898 switch (Kind) {
1899 case SK_ResolveAddressOfOverloadedFunction:
1900 case SK_CastDerivedToBaseRValue:
1901 case SK_CastDerivedToBaseLValue:
1902 case SK_BindReference:
1903 case SK_BindReferenceToTemporary:
1904 case SK_UserConversion:
1905 case SK_QualificationConversionRValue:
1906 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001907 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001908 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001909 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001910 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001911 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001912 break;
1913
1914 case SK_ConversionSequence:
1915 delete ICS;
1916 }
1917}
1918
1919void InitializationSequence::AddAddressOverloadResolutionStep(
1920 FunctionDecl *Function) {
1921 Step S;
1922 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1923 S.Type = Function->getType();
1924 S.Function = Function;
1925 Steps.push_back(S);
1926}
1927
1928void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1929 bool IsLValue) {
1930 Step S;
1931 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1932 S.Type = BaseType;
1933 Steps.push_back(S);
1934}
1935
1936void InitializationSequence::AddReferenceBindingStep(QualType T,
1937 bool BindingTemporary) {
1938 Step S;
1939 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1940 S.Type = T;
1941 Steps.push_back(S);
1942}
1943
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001944void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1945 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001946 Step S;
1947 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001948 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001949 S.Function = Function;
1950 Steps.push_back(S);
1951}
1952
1953void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1954 bool IsLValue) {
1955 Step S;
1956 S.Kind = IsLValue? SK_QualificationConversionLValue
1957 : SK_QualificationConversionRValue;
1958 S.Type = Ty;
1959 Steps.push_back(S);
1960}
1961
1962void InitializationSequence::AddConversionSequenceStep(
1963 const ImplicitConversionSequence &ICS,
1964 QualType T) {
1965 Step S;
1966 S.Kind = SK_ConversionSequence;
1967 S.Type = T;
1968 S.ICS = new ImplicitConversionSequence(ICS);
1969 Steps.push_back(S);
1970}
1971
Douglas Gregor51e77d52009-12-10 17:56:55 +00001972void InitializationSequence::AddListInitializationStep(QualType T) {
1973 Step S;
1974 S.Kind = SK_ListInitialization;
1975 S.Type = T;
1976 Steps.push_back(S);
1977}
1978
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001979void
1980InitializationSequence::AddConstructorInitializationStep(
1981 CXXConstructorDecl *Constructor,
1982 QualType T) {
1983 Step S;
1984 S.Kind = SK_ConstructorInitialization;
1985 S.Type = T;
1986 S.Function = Constructor;
1987 Steps.push_back(S);
1988}
1989
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001990void InitializationSequence::AddZeroInitializationStep(QualType T) {
1991 Step S;
1992 S.Kind = SK_ZeroInitialization;
1993 S.Type = T;
1994 Steps.push_back(S);
1995}
1996
Douglas Gregore1314a62009-12-18 05:02:21 +00001997void InitializationSequence::AddCAssignmentStep(QualType T) {
1998 Step S;
1999 S.Kind = SK_CAssignment;
2000 S.Type = T;
2001 Steps.push_back(S);
2002}
2003
Eli Friedman78275202009-12-19 08:11:05 +00002004void InitializationSequence::AddStringInitStep(QualType T) {
2005 Step S;
2006 S.Kind = SK_StringInit;
2007 S.Type = T;
2008 Steps.push_back(S);
2009}
2010
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002011void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2012 OverloadingResult Result) {
2013 SequenceKind = FailedSequence;
2014 this->Failure = Failure;
2015 this->FailedOverloadResult = Result;
2016}
2017
2018//===----------------------------------------------------------------------===//
2019// Attempt initialization
2020//===----------------------------------------------------------------------===//
2021
2022/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002023static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002024 const InitializedEntity &Entity,
2025 const InitializationKind &Kind,
2026 InitListExpr *InitList,
2027 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002028 // FIXME: We only perform rudimentary checking of list
2029 // initializations at this point, then assume that any list
2030 // initialization of an array, aggregate, or scalar will be
2031 // well-formed. We we actually "perform" list initialization, we'll
2032 // do all of the necessary checking. C++0x initializer lists will
2033 // force us to perform more checking here.
2034 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2035
Douglas Gregor1b303932009-12-22 15:35:07 +00002036 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002037
2038 // C++ [dcl.init]p13:
2039 // If T is a scalar type, then a declaration of the form
2040 //
2041 // T x = { a };
2042 //
2043 // is equivalent to
2044 //
2045 // T x = a;
2046 if (DestType->isScalarType()) {
2047 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2048 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2049 return;
2050 }
2051
2052 // Assume scalar initialization from a single value works.
2053 } else if (DestType->isAggregateType()) {
2054 // Assume aggregate initialization works.
2055 } else if (DestType->isVectorType()) {
2056 // Assume vector initialization works.
2057 } else if (DestType->isReferenceType()) {
2058 // FIXME: C++0x defines behavior for this.
2059 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2060 return;
2061 } else if (DestType->isRecordType()) {
2062 // FIXME: C++0x defines behavior for this
2063 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2064 }
2065
2066 // Add a general "list initialization" step.
2067 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002068}
2069
2070/// \brief Try a reference initialization that involves calling a conversion
2071/// function.
2072///
2073/// FIXME: look intos DRs 656, 896
2074static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2075 const InitializedEntity &Entity,
2076 const InitializationKind &Kind,
2077 Expr *Initializer,
2078 bool AllowRValues,
2079 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002080 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002081 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2082 QualType T1 = cv1T1.getUnqualifiedType();
2083 QualType cv2T2 = Initializer->getType();
2084 QualType T2 = cv2T2.getUnqualifiedType();
2085
2086 bool DerivedToBase;
2087 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2088 T1, T2, DerivedToBase) &&
2089 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002090 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002091
2092 // Build the candidate set directly in the initialization sequence
2093 // structure, so that it will persist if we fail.
2094 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2095 CandidateSet.clear();
2096
2097 // Determine whether we are allowed to call explicit constructors or
2098 // explicit conversion operators.
2099 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2100
2101 const RecordType *T1RecordType = 0;
2102 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2103 // The type we're converting to is a class type. Enumerate its constructors
2104 // to see if there is a suitable conversion.
2105 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2106
2107 DeclarationName ConstructorName
2108 = S.Context.DeclarationNames.getCXXConstructorName(
2109 S.Context.getCanonicalType(T1).getUnqualifiedType());
2110 DeclContext::lookup_iterator Con, ConEnd;
2111 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2112 Con != ConEnd; ++Con) {
2113 // Find the constructor (which may be a template).
2114 CXXConstructorDecl *Constructor = 0;
2115 FunctionTemplateDecl *ConstructorTmpl
2116 = dyn_cast<FunctionTemplateDecl>(*Con);
2117 if (ConstructorTmpl)
2118 Constructor = cast<CXXConstructorDecl>(
2119 ConstructorTmpl->getTemplatedDecl());
2120 else
2121 Constructor = cast<CXXConstructorDecl>(*Con);
2122
2123 if (!Constructor->isInvalidDecl() &&
2124 Constructor->isConvertingConstructor(AllowExplicit)) {
2125 if (ConstructorTmpl)
2126 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2127 &Initializer, 1, CandidateSet);
2128 else
2129 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2130 }
2131 }
2132 }
2133
2134 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2135 // The type we're converting from is a class type, enumerate its conversion
2136 // functions.
2137 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2138
2139 // Determine the type we are converting to. If we are allowed to
2140 // convert to an rvalue, take the type that the destination type
2141 // refers to.
2142 QualType ToType = AllowRValues? cv1T1 : DestType;
2143
John McCallad371252010-01-20 00:46:10 +00002144 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002146 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2147 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002148 NamedDecl *D = *I;
2149 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2150 if (isa<UsingShadowDecl>(D))
2151 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2152
2153 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2154 CXXConversionDecl *Conv;
2155 if (ConvTemplate)
2156 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2157 else
2158 Conv = cast<CXXConversionDecl>(*I);
2159
2160 // If the conversion function doesn't return a reference type,
2161 // it can't be considered for this conversion unless we're allowed to
2162 // consider rvalues.
2163 // FIXME: Do we need to make sure that we only consider conversion
2164 // candidates with reference-compatible results? That might be needed to
2165 // break recursion.
2166 if ((AllowExplicit || !Conv->isExplicit()) &&
2167 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2168 if (ConvTemplate)
2169 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2170 ToType, CandidateSet);
2171 else
2172 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2173 CandidateSet);
2174 }
2175 }
2176 }
2177
2178 SourceLocation DeclLoc = Initializer->getLocStart();
2179
2180 // Perform overload resolution. If it fails, return the failed result.
2181 OverloadCandidateSet::iterator Best;
2182 if (OverloadingResult Result
2183 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2184 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002185
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002186 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002187
2188 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002189 if (isa<CXXConversionDecl>(Function))
2190 T2 = Function->getResultType();
2191 else
2192 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002193
2194 // Add the user-defined conversion step.
2195 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2196
2197 // Determine whether we need to perform derived-to-base or
2198 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199 bool NewDerivedToBase = false;
2200 Sema::ReferenceCompareResult NewRefRelationship
2201 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2202 NewDerivedToBase);
2203 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2204 "Overload resolution picked a bad conversion function");
2205 (void)NewRefRelationship;
2206 if (NewDerivedToBase)
2207 Sequence.AddDerivedToBaseCastStep(
2208 S.Context.getQualifiedType(T1,
2209 T2.getNonReferenceType().getQualifiers()),
2210 /*isLValue=*/true);
2211
2212 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2213 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2214
2215 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2216 return OR_Success;
2217}
2218
2219/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2220static void TryReferenceInitialization(Sema &S,
2221 const InitializedEntity &Entity,
2222 const InitializationKind &Kind,
2223 Expr *Initializer,
2224 InitializationSequence &Sequence) {
2225 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2226
Douglas Gregor1b303932009-12-22 15:35:07 +00002227 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002228 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002229 Qualifiers T1Quals;
2230 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002231 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002232 Qualifiers T2Quals;
2233 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002234 SourceLocation DeclLoc = Initializer->getLocStart();
2235
2236 // If the initializer is the address of an overloaded function, try
2237 // to resolve the overloaded function. If all goes well, T2 is the
2238 // type of the resulting function.
2239 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2240 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2241 T1,
2242 false);
2243 if (!Fn) {
2244 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2245 return;
2246 }
2247
2248 Sequence.AddAddressOverloadResolutionStep(Fn);
2249 cv2T2 = Fn->getType();
2250 T2 = cv2T2.getUnqualifiedType();
2251 }
2252
2253 // FIXME: Rvalue references
2254 bool ForceRValue = false;
2255
2256 // Compute some basic properties of the types and the initializer.
2257 bool isLValueRef = DestType->isLValueReferenceType();
2258 bool isRValueRef = !isLValueRef;
2259 bool DerivedToBase = false;
2260 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2261 Initializer->isLvalue(S.Context);
2262 Sema::ReferenceCompareResult RefRelationship
2263 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2264
2265 // C++0x [dcl.init.ref]p5:
2266 // A reference to type "cv1 T1" is initialized by an expression of type
2267 // "cv2 T2" as follows:
2268 //
2269 // - If the reference is an lvalue reference and the initializer
2270 // expression
2271 OverloadingResult ConvOvlResult = OR_Success;
2272 if (isLValueRef) {
2273 if (InitLvalue == Expr::LV_Valid &&
2274 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2275 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2276 // reference-compatible with "cv2 T2," or
2277 //
2278 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2279 // bit-field when we're determining whether the reference initialization
2280 // can occur. This property will be checked by PerformInitialization.
2281 if (DerivedToBase)
2282 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002283 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002284 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002285 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002286 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2287 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2288 return;
2289 }
2290
2291 // - has a class type (i.e., T2 is a class type), where T1 is not
2292 // reference-related to T2, and can be implicitly converted to an
2293 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2294 // with "cv3 T3" (this conversion is selected by enumerating the
2295 // applicable conversion functions (13.3.1.6) and choosing the best
2296 // one through overload resolution (13.3)),
2297 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2298 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2299 Initializer,
2300 /*AllowRValues=*/false,
2301 Sequence);
2302 if (ConvOvlResult == OR_Success)
2303 return;
John McCall0d1da222010-01-12 00:44:57 +00002304 if (ConvOvlResult != OR_No_Viable_Function) {
2305 Sequence.SetOverloadFailure(
2306 InitializationSequence::FK_ReferenceInitOverloadFailed,
2307 ConvOvlResult);
2308 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 }
2310 }
2311
2312 // - Otherwise, the reference shall be an lvalue reference to a
2313 // non-volatile const type (i.e., cv1 shall be const), or the reference
2314 // shall be an rvalue reference and the initializer expression shall
2315 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002316 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2318 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2319 Sequence.SetOverloadFailure(
2320 InitializationSequence::FK_ReferenceInitOverloadFailed,
2321 ConvOvlResult);
2322 else if (isLValueRef)
2323 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2324 ? (RefRelationship == Sema::Ref_Related
2325 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2326 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2327 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2328 else
2329 Sequence.SetFailed(
2330 InitializationSequence::FK_RValueReferenceBindingToLValue);
2331
2332 return;
2333 }
2334
2335 // - If T1 and T2 are class types and
2336 if (T1->isRecordType() && T2->isRecordType()) {
2337 // - the initializer expression is an rvalue and "cv1 T1" is
2338 // reference-compatible with "cv2 T2", or
2339 if (InitLvalue != Expr::LV_Valid &&
2340 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2341 if (DerivedToBase)
2342 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002343 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002344 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002345 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002346 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2347 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2348 return;
2349 }
2350
2351 // - T1 is not reference-related to T2 and the initializer expression
2352 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2353 // conversion is selected by enumerating the applicable conversion
2354 // functions (13.3.1.6) and choosing the best one through overload
2355 // resolution (13.3)),
2356 if (RefRelationship == Sema::Ref_Incompatible) {
2357 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2358 Kind, Initializer,
2359 /*AllowRValues=*/true,
2360 Sequence);
2361 if (ConvOvlResult)
2362 Sequence.SetOverloadFailure(
2363 InitializationSequence::FK_ReferenceInitOverloadFailed,
2364 ConvOvlResult);
2365
2366 return;
2367 }
2368
2369 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2370 return;
2371 }
2372
2373 // - If the initializer expression is an rvalue, with T2 an array type,
2374 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2375 // is bound to the object represented by the rvalue (see 3.10).
2376 // FIXME: How can an array type be reference-compatible with anything?
2377 // Don't we mean the element types of T1 and T2?
2378
2379 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2380 // from the initializer expression using the rules for a non-reference
2381 // copy initialization (8.5). The reference is then bound to the
2382 // temporary. [...]
2383 // Determine whether we are allowed to call explicit constructors or
2384 // explicit conversion operators.
2385 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2386 ImplicitConversionSequence ICS
2387 = S.TryImplicitConversion(Initializer, cv1T1,
2388 /*SuppressUserConversions=*/false, AllowExplicit,
2389 /*ForceRValue=*/false,
2390 /*FIXME:InOverloadResolution=*/false,
2391 /*UserCast=*/Kind.isExplicitCast());
2392
John McCall0d1da222010-01-12 00:44:57 +00002393 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002394 // FIXME: Use the conversion function set stored in ICS to turn
2395 // this into an overloading ambiguity diagnostic. However, we need
2396 // to keep that set as an OverloadCandidateSet rather than as some
2397 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002398 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2399 Sequence.SetOverloadFailure(
2400 InitializationSequence::FK_ReferenceInitOverloadFailed,
2401 ConvOvlResult);
2402 else
2403 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002404 return;
2405 }
2406
2407 // [...] If T1 is reference-related to T2, cv1 must be the
2408 // same cv-qualification as, or greater cv-qualification
2409 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002410 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2411 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002412 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002413 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002414 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2415 return;
2416 }
2417
2418 // Perform the actual conversion.
2419 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2420 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2421 return;
2422}
2423
2424/// \brief Attempt character array initialization from a string literal
2425/// (C++ [dcl.init.string], C99 6.7.8).
2426static void TryStringLiteralInitialization(Sema &S,
2427 const InitializedEntity &Entity,
2428 const InitializationKind &Kind,
2429 Expr *Initializer,
2430 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002431 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002432 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002433}
2434
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2436/// enumerates the constructors of the initialized entity and performs overload
2437/// resolution to select the best.
2438static void TryConstructorInitialization(Sema &S,
2439 const InitializedEntity &Entity,
2440 const InitializationKind &Kind,
2441 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002442 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002444 if (Kind.getKind() == InitializationKind::IK_Copy)
2445 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2446 else
2447 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002448
2449 // Build the candidate set directly in the initialization sequence
2450 // structure, so that it will persist if we fail.
2451 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2452 CandidateSet.clear();
2453
2454 // Determine whether we are allowed to call explicit constructors or
2455 // explicit conversion operators.
2456 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2457 Kind.getKind() == InitializationKind::IK_Value ||
2458 Kind.getKind() == InitializationKind::IK_Default);
2459
2460 // The type we're converting to is a class type. Enumerate its constructors
2461 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002462 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2463 assert(DestRecordType && "Constructor initialization requires record type");
2464 CXXRecordDecl *DestRecordDecl
2465 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2466
2467 DeclarationName ConstructorName
2468 = S.Context.DeclarationNames.getCXXConstructorName(
2469 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2470 DeclContext::lookup_iterator Con, ConEnd;
2471 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2472 Con != ConEnd; ++Con) {
2473 // Find the constructor (which may be a template).
2474 CXXConstructorDecl *Constructor = 0;
2475 FunctionTemplateDecl *ConstructorTmpl
2476 = dyn_cast<FunctionTemplateDecl>(*Con);
2477 if (ConstructorTmpl)
2478 Constructor = cast<CXXConstructorDecl>(
2479 ConstructorTmpl->getTemplatedDecl());
2480 else
2481 Constructor = cast<CXXConstructorDecl>(*Con);
2482
2483 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002484 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002485 if (ConstructorTmpl)
2486 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2487 Args, NumArgs, CandidateSet);
2488 else
2489 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2490 }
2491 }
2492
2493 SourceLocation DeclLoc = Kind.getLocation();
2494
2495 // Perform overload resolution. If it fails, return the failed result.
2496 OverloadCandidateSet::iterator Best;
2497 if (OverloadingResult Result
2498 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2499 Sequence.SetOverloadFailure(
2500 InitializationSequence::FK_ConstructorOverloadFailed,
2501 Result);
2502 return;
2503 }
2504
2505 // Add the constructor initialization step. Any cv-qualification conversion is
2506 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002507 if (Kind.getKind() == InitializationKind::IK_Copy) {
2508 Sequence.AddUserConversionStep(Best->Function, DestType);
2509 } else {
2510 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002511 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002512 DestType);
2513 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002514}
2515
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002516/// \brief Attempt value initialization (C++ [dcl.init]p7).
2517static void TryValueInitialization(Sema &S,
2518 const InitializedEntity &Entity,
2519 const InitializationKind &Kind,
2520 InitializationSequence &Sequence) {
2521 // C++ [dcl.init]p5:
2522 //
2523 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002524 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002525
2526 // -- if T is an array type, then each element is value-initialized;
2527 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2528 T = AT->getElementType();
2529
2530 if (const RecordType *RT = T->getAs<RecordType>()) {
2531 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2532 // -- if T is a class type (clause 9) with a user-declared
2533 // constructor (12.1), then the default constructor for T is
2534 // called (and the initialization is ill-formed if T has no
2535 // accessible default constructor);
2536 //
2537 // FIXME: we really want to refer to a single subobject of the array,
2538 // but Entity doesn't have a way to capture that (yet).
2539 if (ClassDecl->hasUserDeclaredConstructor())
2540 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2541
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002542 // -- if T is a (possibly cv-qualified) non-union class type
2543 // without a user-provided constructor, then the object is
2544 // zero-initialized and, if T’s implicitly-declared default
2545 // constructor is non-trivial, that constructor is called.
2546 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2547 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2548 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002549 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002550 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2551 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002552 }
2553 }
2554
Douglas Gregor1b303932009-12-22 15:35:07 +00002555 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002556 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2557}
2558
Douglas Gregor85dabae2009-12-16 01:38:02 +00002559/// \brief Attempt default initialization (C++ [dcl.init]p6).
2560static void TryDefaultInitialization(Sema &S,
2561 const InitializedEntity &Entity,
2562 const InitializationKind &Kind,
2563 InitializationSequence &Sequence) {
2564 assert(Kind.getKind() == InitializationKind::IK_Default);
2565
2566 // C++ [dcl.init]p6:
2567 // To default-initialize an object of type T means:
2568 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002569 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002570 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2571 DestType = Array->getElementType();
2572
2573 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2574 // constructor for T is called (and the initialization is ill-formed if
2575 // T has no accessible default constructor);
2576 if (DestType->isRecordType()) {
2577 // FIXME: If a program calls for the default initialization of an object of
2578 // a const-qualified type T, T shall be a class type with a user-provided
2579 // default constructor.
2580 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2581 Sequence);
2582 }
2583
2584 // - otherwise, no initialization is performed.
2585 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2586
2587 // If a program calls for the default initialization of an object of
2588 // a const-qualified type T, T shall be a class type with a user-provided
2589 // default constructor.
2590 if (DestType.isConstQualified())
2591 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2592}
2593
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002594/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2595/// which enumerates all conversion functions and performs overload resolution
2596/// to select the best.
2597static void TryUserDefinedConversion(Sema &S,
2598 const InitializedEntity &Entity,
2599 const InitializationKind &Kind,
2600 Expr *Initializer,
2601 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002602 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2603
Douglas Gregor1b303932009-12-22 15:35:07 +00002604 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002605 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2606 QualType SourceType = Initializer->getType();
2607 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2608 "Must have a class type to perform a user-defined conversion");
2609
2610 // Build the candidate set directly in the initialization sequence
2611 // structure, so that it will persist if we fail.
2612 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2613 CandidateSet.clear();
2614
2615 // Determine whether we are allowed to call explicit constructors or
2616 // explicit conversion operators.
2617 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2618
2619 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2620 // The type we're converting to is a class type. Enumerate its constructors
2621 // to see if there is a suitable conversion.
2622 CXXRecordDecl *DestRecordDecl
2623 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2624
2625 DeclarationName ConstructorName
2626 = S.Context.DeclarationNames.getCXXConstructorName(
2627 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2628 DeclContext::lookup_iterator Con, ConEnd;
2629 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2630 Con != ConEnd; ++Con) {
2631 // Find the constructor (which may be a template).
2632 CXXConstructorDecl *Constructor = 0;
2633 FunctionTemplateDecl *ConstructorTmpl
2634 = dyn_cast<FunctionTemplateDecl>(*Con);
2635 if (ConstructorTmpl)
2636 Constructor = cast<CXXConstructorDecl>(
2637 ConstructorTmpl->getTemplatedDecl());
2638 else
2639 Constructor = cast<CXXConstructorDecl>(*Con);
2640
2641 if (!Constructor->isInvalidDecl() &&
2642 Constructor->isConvertingConstructor(AllowExplicit)) {
2643 if (ConstructorTmpl)
2644 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2645 &Initializer, 1, CandidateSet);
2646 else
2647 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2648 }
2649 }
2650 }
Eli Friedman78275202009-12-19 08:11:05 +00002651
2652 SourceLocation DeclLoc = Initializer->getLocStart();
2653
Douglas Gregor540c3b02009-12-14 17:27:33 +00002654 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2655 // The type we're converting from is a class type, enumerate its conversion
2656 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002657
Eli Friedman4afe9a32009-12-20 22:12:03 +00002658 // We can only enumerate the conversion functions for a complete type; if
2659 // the type isn't complete, simply skip this step.
2660 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2661 CXXRecordDecl *SourceRecordDecl
2662 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002663
John McCallad371252010-01-20 00:46:10 +00002664 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002665 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002666 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002667 E = Conversions->end();
2668 I != E; ++I) {
2669 NamedDecl *D = *I;
2670 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2671 if (isa<UsingShadowDecl>(D))
2672 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2673
2674 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2675 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002676 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002677 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002678 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002679 Conv = cast<CXXConversionDecl>(*I);
2680
2681 if (AllowExplicit || !Conv->isExplicit()) {
2682 if (ConvTemplate)
2683 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2684 Initializer, DestType,
2685 CandidateSet);
2686 else
2687 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2688 CandidateSet);
2689 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002690 }
2691 }
2692 }
2693
Douglas Gregor540c3b02009-12-14 17:27:33 +00002694 // Perform overload resolution. If it fails, return the failed result.
2695 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002696 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002697 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2698 Sequence.SetOverloadFailure(
2699 InitializationSequence::FK_UserConversionOverloadFailed,
2700 Result);
2701 return;
2702 }
John McCall0d1da222010-01-12 00:44:57 +00002703
Douglas Gregor540c3b02009-12-14 17:27:33 +00002704 FunctionDecl *Function = Best->Function;
2705
2706 if (isa<CXXConstructorDecl>(Function)) {
2707 // Add the user-defined conversion step. Any cv-qualification conversion is
2708 // subsumed by the initialization.
2709 Sequence.AddUserConversionStep(Function, DestType);
2710 return;
2711 }
2712
2713 // Add the user-defined conversion step that calls the conversion function.
2714 QualType ConvType = Function->getResultType().getNonReferenceType();
2715 Sequence.AddUserConversionStep(Function, ConvType);
2716
2717 // If the conversion following the call to the conversion function is
2718 // interesting, add it as a separate step.
2719 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2720 Best->FinalConversion.Third) {
2721 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002722 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002723 ICS.Standard = Best->FinalConversion;
2724 Sequence.AddConversionSequenceStep(ICS, DestType);
2725 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726}
2727
2728/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2729/// non-class type to another.
2730static void TryImplicitConversion(Sema &S,
2731 const InitializedEntity &Entity,
2732 const InitializationKind &Kind,
2733 Expr *Initializer,
2734 InitializationSequence &Sequence) {
2735 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002736 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002737 /*SuppressUserConversions=*/true,
2738 /*AllowExplicit=*/false,
2739 /*ForceRValue=*/false,
2740 /*FIXME:InOverloadResolution=*/false,
2741 /*UserCast=*/Kind.isExplicitCast());
2742
John McCall0d1da222010-01-12 00:44:57 +00002743 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002744 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2745 return;
2746 }
2747
Douglas Gregor1b303932009-12-22 15:35:07 +00002748 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002749}
2750
2751InitializationSequence::InitializationSequence(Sema &S,
2752 const InitializedEntity &Entity,
2753 const InitializationKind &Kind,
2754 Expr **Args,
2755 unsigned NumArgs) {
2756 ASTContext &Context = S.Context;
2757
2758 // C++0x [dcl.init]p16:
2759 // The semantics of initializers are as follows. The destination type is
2760 // the type of the object or reference being initialized and the source
2761 // type is the type of the initializer expression. The source type is not
2762 // defined when the initializer is a braced-init-list or when it is a
2763 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002764 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002765
2766 if (DestType->isDependentType() ||
2767 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2768 SequenceKind = DependentSequence;
2769 return;
2770 }
2771
2772 QualType SourceType;
2773 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002774 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002775 Initializer = Args[0];
2776 if (!isa<InitListExpr>(Initializer))
2777 SourceType = Initializer->getType();
2778 }
2779
2780 // - If the initializer is a braced-init-list, the object is
2781 // list-initialized (8.5.4).
2782 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2783 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002784 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 }
2786
2787 // - If the destination type is a reference type, see 8.5.3.
2788 if (DestType->isReferenceType()) {
2789 // C++0x [dcl.init.ref]p1:
2790 // A variable declared to be a T& or T&&, that is, "reference to type T"
2791 // (8.3.2), shall be initialized by an object, or function, of type T or
2792 // by an object that can be converted into a T.
2793 // (Therefore, multiple arguments are not permitted.)
2794 if (NumArgs != 1)
2795 SetFailed(FK_TooManyInitsForReference);
2796 else
2797 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2798 return;
2799 }
2800
2801 // - If the destination type is an array of characters, an array of
2802 // char16_t, an array of char32_t, or an array of wchar_t, and the
2803 // initializer is a string literal, see 8.5.2.
2804 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2805 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2806 return;
2807 }
2808
2809 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002810 if (Kind.getKind() == InitializationKind::IK_Value ||
2811 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002812 TryValueInitialization(S, Entity, Kind, *this);
2813 return;
2814 }
2815
Douglas Gregor85dabae2009-12-16 01:38:02 +00002816 // Handle default initialization.
2817 if (Kind.getKind() == InitializationKind::IK_Default){
2818 TryDefaultInitialization(S, Entity, Kind, *this);
2819 return;
2820 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002821
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002822 // - Otherwise, if the destination type is an array, the program is
2823 // ill-formed.
2824 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2825 if (AT->getElementType()->isAnyCharacterType())
2826 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2827 else
2828 SetFailed(FK_ArrayNeedsInitList);
2829
2830 return;
2831 }
Eli Friedman78275202009-12-19 08:11:05 +00002832
2833 // Handle initialization in C
2834 if (!S.getLangOptions().CPlusPlus) {
2835 setSequenceKind(CAssignment);
2836 AddCAssignmentStep(DestType);
2837 return;
2838 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002839
2840 // - If the destination type is a (possibly cv-qualified) class type:
2841 if (DestType->isRecordType()) {
2842 // - If the initialization is direct-initialization, or if it is
2843 // copy-initialization where the cv-unqualified version of the
2844 // source type is the same class as, or a derived class of, the
2845 // class of the destination, constructors are considered. [...]
2846 if (Kind.getKind() == InitializationKind::IK_Direct ||
2847 (Kind.getKind() == InitializationKind::IK_Copy &&
2848 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2849 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002850 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002851 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002852 // - Otherwise (i.e., for the remaining copy-initialization cases),
2853 // user-defined conversion sequences that can convert from the source
2854 // type to the destination type or (when a conversion function is
2855 // used) to a derived class thereof are enumerated as described in
2856 // 13.3.1.4, and the best one is chosen through overload resolution
2857 // (13.3).
2858 else
2859 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2860 return;
2861 }
2862
Douglas Gregor85dabae2009-12-16 01:38:02 +00002863 if (NumArgs > 1) {
2864 SetFailed(FK_TooManyInitsForScalar);
2865 return;
2866 }
2867 assert(NumArgs == 1 && "Zero-argument case handled above");
2868
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002869 // - Otherwise, if the source type is a (possibly cv-qualified) class
2870 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002871 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002872 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2873 return;
2874 }
2875
2876 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002877 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002878 // conversions (Clause 4) will be used, if necessary, to convert the
2879 // initializer expression to the cv-unqualified version of the
2880 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002881 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2883}
2884
2885InitializationSequence::~InitializationSequence() {
2886 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2887 StepEnd = Steps.end();
2888 Step != StepEnd; ++Step)
2889 Step->Destroy();
2890}
2891
2892//===----------------------------------------------------------------------===//
2893// Perform initialization
2894//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002895static Sema::AssignmentAction
2896getAssignmentAction(const InitializedEntity &Entity) {
2897 switch(Entity.getKind()) {
2898 case InitializedEntity::EK_Variable:
2899 case InitializedEntity::EK_New:
2900 return Sema::AA_Initializing;
2901
2902 case InitializedEntity::EK_Parameter:
2903 // FIXME: Can we tell when we're sending vs. passing?
2904 return Sema::AA_Passing;
2905
2906 case InitializedEntity::EK_Result:
2907 return Sema::AA_Returning;
2908
2909 case InitializedEntity::EK_Exception:
2910 case InitializedEntity::EK_Base:
2911 llvm_unreachable("No assignment action for C++-specific initialization");
2912 break;
2913
2914 case InitializedEntity::EK_Temporary:
2915 // FIXME: Can we tell apart casting vs. converting?
2916 return Sema::AA_Casting;
2917
2918 case InitializedEntity::EK_Member:
2919 case InitializedEntity::EK_ArrayOrVectorElement:
2920 return Sema::AA_Initializing;
2921 }
2922
2923 return Sema::AA_Converting;
2924}
2925
2926static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2927 bool IsCopy) {
2928 switch (Entity.getKind()) {
2929 case InitializedEntity::EK_Result:
2930 case InitializedEntity::EK_Exception:
2931 return !IsCopy;
2932
2933 case InitializedEntity::EK_New:
2934 case InitializedEntity::EK_Variable:
2935 case InitializedEntity::EK_Base:
2936 case InitializedEntity::EK_Member:
2937 case InitializedEntity::EK_ArrayOrVectorElement:
2938 return false;
2939
2940 case InitializedEntity::EK_Parameter:
2941 case InitializedEntity::EK_Temporary:
2942 return true;
2943 }
2944
2945 llvm_unreachable("missed an InitializedEntity kind?");
2946}
2947
2948/// \brief If we need to perform an additional copy of the initialized object
2949/// for this kind of entity (e.g., the result of a function or an object being
2950/// thrown), make the copy.
2951static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2952 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00002953 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00002954 Sema::OwningExprResult CurInit) {
2955 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00002956
2957 switch (Entity.getKind()) {
2958 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00002959 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00002960 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00002961 Loc = Entity.getReturnLoc();
2962 break;
2963
2964 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002965 Loc = Entity.getThrowLoc();
2966 break;
2967
2968 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00002969 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00002970 Kind.getKind() != InitializationKind::IK_Copy)
2971 return move(CurInit);
2972 Loc = Entity.getDecl()->getLocation();
2973 break;
2974
Douglas Gregore1314a62009-12-18 05:02:21 +00002975 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002976 // FIXME: Do we need this initialization for a parameter?
2977 return move(CurInit);
2978
Douglas Gregore1314a62009-12-18 05:02:21 +00002979 case InitializedEntity::EK_New:
2980 case InitializedEntity::EK_Temporary:
2981 case InitializedEntity::EK_Base:
2982 case InitializedEntity::EK_Member:
2983 case InitializedEntity::EK_ArrayOrVectorElement:
2984 // We don't need to copy for any of these initialized entities.
2985 return move(CurInit);
2986 }
2987
2988 Expr *CurInitExpr = (Expr *)CurInit.get();
2989 CXXRecordDecl *Class = 0;
2990 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
2991 Class = cast<CXXRecordDecl>(Record->getDecl());
2992 if (!Class)
2993 return move(CurInit);
2994
2995 // Perform overload resolution using the class's copy constructors.
2996 DeclarationName ConstructorName
2997 = S.Context.DeclarationNames.getCXXConstructorName(
2998 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
2999 DeclContext::lookup_iterator Con, ConEnd;
3000 OverloadCandidateSet CandidateSet;
3001 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3002 Con != ConEnd; ++Con) {
3003 // Find the constructor (which may be a template).
3004 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3005 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003006 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003007 continue;
3008
3009 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3010 }
3011
3012 OverloadCandidateSet::iterator Best;
3013 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3014 case OR_Success:
3015 break;
3016
3017 case OR_No_Viable_Function:
3018 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003019 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003020 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003021 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3022 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003023 return S.ExprError();
3024
3025 case OR_Ambiguous:
3026 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003027 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003028 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003029 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3030 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003031 return S.ExprError();
3032
3033 case OR_Deleted:
3034 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003035 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003036 << CurInitExpr->getSourceRange();
3037 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3038 << Best->Function->isDeleted();
3039 return S.ExprError();
3040 }
3041
3042 CurInit.release();
3043 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3044 cast<CXXConstructorDecl>(Best->Function),
3045 /*Elidable=*/true,
3046 Sema::MultiExprArg(S,
3047 (void**)&CurInitExpr, 1));
3048}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003049
3050Action::OwningExprResult
3051InitializationSequence::Perform(Sema &S,
3052 const InitializedEntity &Entity,
3053 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003054 Action::MultiExprArg Args,
3055 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003056 if (SequenceKind == FailedSequence) {
3057 unsigned NumArgs = Args.size();
3058 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3059 return S.ExprError();
3060 }
3061
3062 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003063 // If the declaration is a non-dependent, incomplete array type
3064 // that has an initializer, then its type will be completed once
3065 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003066 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003067 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003068 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003069 if (const IncompleteArrayType *ArrayT
3070 = S.Context.getAsIncompleteArrayType(DeclType)) {
3071 // FIXME: We don't currently have the ability to accurately
3072 // compute the length of an initializer list without
3073 // performing full type-checking of the initializer list
3074 // (since we have to determine where braces are implicitly
3075 // introduced and such). So, we fall back to making the array
3076 // type a dependently-sized array type with no specified
3077 // bound.
3078 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3079 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003080
Douglas Gregor51e77d52009-12-10 17:56:55 +00003081 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003082 if (DeclaratorDecl *DD = Entity.getDecl()) {
3083 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3084 TypeLoc TL = TInfo->getTypeLoc();
3085 if (IncompleteArrayTypeLoc *ArrayLoc
3086 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3087 Brackets = ArrayLoc->getBracketsRange();
3088 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003089 }
3090
3091 *ResultType
3092 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3093 /*NumElts=*/0,
3094 ArrayT->getSizeModifier(),
3095 ArrayT->getIndexTypeCVRQualifiers(),
3096 Brackets);
3097 }
3098
3099 }
3100 }
3101
Eli Friedmana553d4a2009-12-22 02:35:53 +00003102 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 return Sema::OwningExprResult(S, Args.release()[0]);
3104
3105 unsigned NumArgs = Args.size();
3106 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3107 SourceLocation(),
3108 (Expr **)Args.release(),
3109 NumArgs,
3110 SourceLocation()));
3111 }
3112
Douglas Gregor85dabae2009-12-16 01:38:02 +00003113 if (SequenceKind == NoInitialization)
3114 return S.Owned((Expr *)0);
3115
Douglas Gregor1b303932009-12-22 15:35:07 +00003116 QualType DestType = Entity.getType().getNonReferenceType();
3117 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003118 // the same as Entity.getDecl()->getType() in cases involving type merging,
3119 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003120 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003121 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003122 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123
Douglas Gregor85dabae2009-12-16 01:38:02 +00003124 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3125
3126 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3127
3128 // For initialization steps that start with a single initializer,
3129 // grab the only argument out the Args and place it into the "current"
3130 // initializer.
3131 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003132 case SK_ResolveAddressOfOverloadedFunction:
3133 case SK_CastDerivedToBaseRValue:
3134 case SK_CastDerivedToBaseLValue:
3135 case SK_BindReference:
3136 case SK_BindReferenceToTemporary:
3137 case SK_UserConversion:
3138 case SK_QualificationConversionLValue:
3139 case SK_QualificationConversionRValue:
3140 case SK_ConversionSequence:
3141 case SK_ListInitialization:
3142 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003143 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003144 assert(Args.size() == 1);
3145 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3146 if (CurInit.isInvalid())
3147 return S.ExprError();
3148 break;
3149
3150 case SK_ConstructorInitialization:
3151 case SK_ZeroInitialization:
3152 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153 }
3154
3155 // Walk through the computed steps for the initialization sequence,
3156 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003157 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158 for (step_iterator Step = step_begin(), StepEnd = step_end();
3159 Step != StepEnd; ++Step) {
3160 if (CurInit.isInvalid())
3161 return S.ExprError();
3162
3163 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003164 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003165
3166 switch (Step->Kind) {
3167 case SK_ResolveAddressOfOverloadedFunction:
3168 // Overload resolution determined which function invoke; update the
3169 // initializer to reflect that choice.
3170 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3171 break;
3172
3173 case SK_CastDerivedToBaseRValue:
3174 case SK_CastDerivedToBaseLValue: {
3175 // We have a derived-to-base cast that produces either an rvalue or an
3176 // lvalue. Perform that cast.
3177
3178 // Casts to inaccessible base classes are allowed with C-style casts.
3179 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3180 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3181 CurInitExpr->getLocStart(),
3182 CurInitExpr->getSourceRange(),
3183 IgnoreBaseAccess))
3184 return S.ExprError();
3185
3186 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3187 CastExpr::CK_DerivedToBase,
3188 (Expr*)CurInit.release(),
3189 Step->Kind == SK_CastDerivedToBaseLValue));
3190 break;
3191 }
3192
3193 case SK_BindReference:
3194 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3195 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3196 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003197 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003198 << BitField->getDeclName()
3199 << CurInitExpr->getSourceRange();
3200 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3201 return S.ExprError();
3202 }
3203
3204 // Reference binding does not have any corresponding ASTs.
3205
3206 // Check exception specifications
3207 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3208 return S.ExprError();
3209 break;
3210
3211 case SK_BindReferenceToTemporary:
3212 // Check exception specifications
3213 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3214 return S.ExprError();
3215
3216 // FIXME: At present, we have no AST to describe when we need to make a
3217 // temporary to bind a reference to. We should.
3218 break;
3219
3220 case SK_UserConversion: {
3221 // We have a user-defined conversion that invokes either a constructor
3222 // or a conversion function.
3223 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003224 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003225 if (CXXConstructorDecl *Constructor
3226 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3227 // Build a call to the selected constructor.
3228 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3229 SourceLocation Loc = CurInitExpr->getLocStart();
3230 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3231
3232 // Determine the arguments required to actually perform the constructor
3233 // call.
3234 if (S.CompleteConstructorCall(Constructor,
3235 Sema::MultiExprArg(S,
3236 (void **)&CurInitExpr,
3237 1),
3238 Loc, ConstructorArgs))
3239 return S.ExprError();
3240
3241 // Build the an expression that constructs a temporary.
3242 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3243 move_arg(ConstructorArgs));
3244 if (CurInit.isInvalid())
3245 return S.ExprError();
3246
3247 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003248 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3249 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3250 S.IsDerivedFrom(SourceType, Class))
3251 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003252 } else {
3253 // Build a call to the conversion function.
3254 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003256 // FIXME: Should we move this initialization into a separate
3257 // derived-to-base conversion? I believe the answer is "no", because
3258 // we don't want to turn off access control here for c-style casts.
3259 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3260 return S.ExprError();
3261
3262 // Do a little dance to make sure that CurInit has the proper
3263 // pointer.
3264 CurInit.release();
3265
3266 // Build the actual call to the conversion function.
3267 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3268 if (CurInit.isInvalid() || !CurInit.get())
3269 return S.ExprError();
3270
3271 CastKind = CastExpr::CK_UserDefinedConversion;
3272 }
3273
Douglas Gregore1314a62009-12-18 05:02:21 +00003274 if (shouldBindAsTemporary(Entity, IsCopy))
3275 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277 CurInitExpr = CurInit.takeAs<Expr>();
3278 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3279 CastKind,
3280 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003281 false));
3282
3283 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003284 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003285 break;
3286 }
3287
3288 case SK_QualificationConversionLValue:
3289 case SK_QualificationConversionRValue:
3290 // Perform a qualification conversion; these can never go wrong.
3291 S.ImpCastExprToType(CurInitExpr, Step->Type,
3292 CastExpr::CK_NoOp,
3293 Step->Kind == SK_QualificationConversionLValue);
3294 CurInit.release();
3295 CurInit = S.Owned(CurInitExpr);
3296 break;
3297
3298 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003299 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003300 false, false, *Step->ICS))
3301 return S.ExprError();
3302
3303 CurInit.release();
3304 CurInit = S.Owned(CurInitExpr);
3305 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003306
3307 case SK_ListInitialization: {
3308 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3309 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003310 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003311 return S.ExprError();
3312
3313 CurInit.release();
3314 CurInit = S.Owned(InitList);
3315 break;
3316 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003317
3318 case SK_ConstructorInitialization: {
3319 CXXConstructorDecl *Constructor
3320 = cast<CXXConstructorDecl>(Step->Function);
3321
3322 // Build a call to the selected constructor.
3323 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3324 SourceLocation Loc = Kind.getLocation();
3325
3326 // Determine the arguments required to actually perform the constructor
3327 // call.
3328 if (S.CompleteConstructorCall(Constructor, move(Args),
3329 Loc, ConstructorArgs))
3330 return S.ExprError();
3331
3332 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003333 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003334 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003335 move_arg(ConstructorArgs),
3336 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003337 if (CurInit.isInvalid())
3338 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003339
3340 bool Elidable
3341 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3342 if (shouldBindAsTemporary(Entity, Elidable))
3343 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3344
3345 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003346 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003347 break;
3348 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003349
3350 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003351 step_iterator NextStep = Step;
3352 ++NextStep;
3353 if (NextStep != StepEnd &&
3354 NextStep->Kind == SK_ConstructorInitialization) {
3355 // The need for zero-initialization is recorded directly into
3356 // the call to the object's constructor within the next step.
3357 ConstructorInitRequiresZeroInit = true;
3358 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3359 S.getLangOptions().CPlusPlus &&
3360 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003361 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3362 Kind.getRange().getBegin(),
3363 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003364 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003365 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003366 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003367 break;
3368 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003369
3370 case SK_CAssignment: {
3371 QualType SourceType = CurInitExpr->getType();
3372 Sema::AssignConvertType ConvTy =
3373 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003374
3375 // If this is a call, allow conversion to a transparent union.
3376 if (ConvTy != Sema::Compatible &&
3377 Entity.getKind() == InitializedEntity::EK_Parameter &&
3378 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3379 == Sema::Compatible)
3380 ConvTy = Sema::Compatible;
3381
Douglas Gregore1314a62009-12-18 05:02:21 +00003382 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3383 Step->Type, SourceType,
3384 CurInitExpr, getAssignmentAction(Entity)))
3385 return S.ExprError();
3386
3387 CurInit.release();
3388 CurInit = S.Owned(CurInitExpr);
3389 break;
3390 }
Eli Friedman78275202009-12-19 08:11:05 +00003391
3392 case SK_StringInit: {
3393 QualType Ty = Step->Type;
3394 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3395 break;
3396 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003397 }
3398 }
3399
3400 return move(CurInit);
3401}
3402
3403//===----------------------------------------------------------------------===//
3404// Diagnose initialization failures
3405//===----------------------------------------------------------------------===//
3406bool InitializationSequence::Diagnose(Sema &S,
3407 const InitializedEntity &Entity,
3408 const InitializationKind &Kind,
3409 Expr **Args, unsigned NumArgs) {
3410 if (SequenceKind != FailedSequence)
3411 return false;
3412
Douglas Gregor1b303932009-12-22 15:35:07 +00003413 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003414 switch (Failure) {
3415 case FK_TooManyInitsForReference:
3416 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3417 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3418 break;
3419
3420 case FK_ArrayNeedsInitList:
3421 case FK_ArrayNeedsInitListOrStringLiteral:
3422 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3423 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3424 break;
3425
3426 case FK_AddressOfOverloadFailed:
3427 S.ResolveAddressOfOverloadedFunction(Args[0],
3428 DestType.getNonReferenceType(),
3429 true);
3430 break;
3431
3432 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003433 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003434 switch (FailedOverloadResult) {
3435 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003436 if (Failure == FK_UserConversionOverloadFailed)
3437 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3438 << Args[0]->getType() << DestType
3439 << Args[0]->getSourceRange();
3440 else
3441 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3442 << DestType << Args[0]->getType()
3443 << Args[0]->getSourceRange();
3444
John McCallad907772010-01-12 07:18:19 +00003445 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3446 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003447 break;
3448
3449 case OR_No_Viable_Function:
3450 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3451 << Args[0]->getType() << DestType.getNonReferenceType()
3452 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003453 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3454 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003455 break;
3456
3457 case OR_Deleted: {
3458 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3459 << Args[0]->getType() << DestType.getNonReferenceType()
3460 << Args[0]->getSourceRange();
3461 OverloadCandidateSet::iterator Best;
3462 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3463 Kind.getLocation(),
3464 Best);
3465 if (Ovl == OR_Deleted) {
3466 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3467 << Best->Function->isDeleted();
3468 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003469 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003470 }
3471 break;
3472 }
3473
3474 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003475 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003476 break;
3477 }
3478 break;
3479
3480 case FK_NonConstLValueReferenceBindingToTemporary:
3481 case FK_NonConstLValueReferenceBindingToUnrelated:
3482 S.Diag(Kind.getLocation(),
3483 Failure == FK_NonConstLValueReferenceBindingToTemporary
3484 ? diag::err_lvalue_reference_bind_to_temporary
3485 : diag::err_lvalue_reference_bind_to_unrelated)
3486 << DestType.getNonReferenceType()
3487 << Args[0]->getType()
3488 << Args[0]->getSourceRange();
3489 break;
3490
3491 case FK_RValueReferenceBindingToLValue:
3492 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3493 << Args[0]->getSourceRange();
3494 break;
3495
3496 case FK_ReferenceInitDropsQualifiers:
3497 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3498 << DestType.getNonReferenceType()
3499 << Args[0]->getType()
3500 << Args[0]->getSourceRange();
3501 break;
3502
3503 case FK_ReferenceInitFailed:
3504 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3505 << DestType.getNonReferenceType()
3506 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3507 << Args[0]->getType()
3508 << Args[0]->getSourceRange();
3509 break;
3510
3511 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003512 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3513 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003514 << DestType
3515 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3516 << Args[0]->getType()
3517 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003518 break;
3519
3520 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003521 SourceRange R;
3522
3523 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3524 R = SourceRange(InitList->getInit(1)->getLocStart(),
3525 InitList->getLocEnd());
3526 else
3527 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003528
3529 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003530 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003531 break;
3532 }
3533
3534 case FK_ReferenceBindingToInitList:
3535 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3536 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3537 break;
3538
3539 case FK_InitListBadDestinationType:
3540 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3541 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3542 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003543
3544 case FK_ConstructorOverloadFailed: {
3545 SourceRange ArgsRange;
3546 if (NumArgs)
3547 ArgsRange = SourceRange(Args[0]->getLocStart(),
3548 Args[NumArgs - 1]->getLocEnd());
3549
3550 // FIXME: Using "DestType" for the entity we're printing is probably
3551 // bad.
3552 switch (FailedOverloadResult) {
3553 case OR_Ambiguous:
3554 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3555 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003556 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003557 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003558 break;
3559
3560 case OR_No_Viable_Function:
3561 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3562 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003563 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3564 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003565 break;
3566
3567 case OR_Deleted: {
3568 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3569 << true << DestType << ArgsRange;
3570 OverloadCandidateSet::iterator Best;
3571 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3572 Kind.getLocation(),
3573 Best);
3574 if (Ovl == OR_Deleted) {
3575 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3576 << Best->Function->isDeleted();
3577 } else {
3578 llvm_unreachable("Inconsistent overload resolution?");
3579 }
3580 break;
3581 }
3582
3583 case OR_Success:
3584 llvm_unreachable("Conversion did not fail!");
3585 break;
3586 }
3587 break;
3588 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003589
3590 case FK_DefaultInitOfConst:
3591 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3592 << DestType;
3593 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003594 }
3595
3596 return true;
3597}
Douglas Gregore1314a62009-12-18 05:02:21 +00003598
3599//===----------------------------------------------------------------------===//
3600// Initialization helper functions
3601//===----------------------------------------------------------------------===//
3602Sema::OwningExprResult
3603Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3604 SourceLocation EqualLoc,
3605 OwningExprResult Init) {
3606 if (Init.isInvalid())
3607 return ExprError();
3608
3609 Expr *InitE = (Expr *)Init.get();
3610 assert(InitE && "No initialization expression?");
3611
3612 if (EqualLoc.isInvalid())
3613 EqualLoc = InitE->getLocStart();
3614
3615 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3616 EqualLoc);
3617 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3618 Init.release();
3619 return Seq.Perform(*this, Entity, Kind,
3620 MultiExprArg(*this, (void**)&InitE, 1));
3621}