blob: c5a10b54fd763fad7ee239d31987e375441a1d8f [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlssonc07b8c02010-01-23 18:35:41 +000069static Sema::OwningExprResult
70CheckSingleInitializer(const InitializedEntity *Entity,
71 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
72 Expr *InitExpr = Init.takeAs<Expr>();
73
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // Get the type before calling CheckSingleAssignmentConstraints(), since
75 // it can promote the expression.
Anders Carlssonc07b8c02010-01-23 18:35:41 +000076 QualType InitType = InitExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner95e8d652009-02-24 22:46:58 +000078 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 // FIXME: I dislike this error message. A lot.
Anders Carlssonc07b8c02010-01-23 18:35:41 +000080 if (S.PerformImplicitConversion(InitExpr, DeclType,
81 Sema::AA_Initializing,
82 /*DirectInit=*/false)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000083 ImplicitConversionSequence ICS;
84 OverloadCandidateSet CandidateSet;
Anders Carlssonc07b8c02010-01-23 18:35:41 +000085 if (S.IsUserDefinedConversion(InitExpr, DeclType, ICS.UserDefined,
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000086 CandidateSet,
Anders Carlssonc07b8c02010-01-23 18:35:41 +000087 true, false, false) != OR_Ambiguous) {
88 S.Diag(InitExpr->getSourceRange().getBegin(),
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000089 diag::err_typecheck_convert_incompatible)
Anders Carlssonc07b8c02010-01-23 18:35:41 +000090 << DeclType << InitExpr->getType() << Sema::AA_Initializing
91 << InitExpr->getSourceRange();
92 return S.ExprError();
93 }
94 S.Diag(InitExpr->getSourceRange().getBegin(),
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000095 diag::err_typecheck_convert_ambiguous)
Anders Carlssonc07b8c02010-01-23 18:35:41 +000096 << DeclType << InitExpr->getType() << InitExpr->getSourceRange();
97 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
98 &InitExpr, 1);
99
100 return S.ExprError();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +0000101 }
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000102
103 Init.release();
104 return S.Owned(InitExpr);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105 }
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner95e8d652009-02-24 22:46:58 +0000107 Sema::AssignConvertType ConvTy =
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000108 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
109 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
110 InitType, InitExpr, Sema::AA_Initializing))
111 return S.ExprError();
112
113 Init.release();
114 return S.Owned(InitExpr);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000115}
116
Chris Lattner79e079d2009-02-24 23:10:27 +0000117static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
118 // Get the length of the string as parsed.
119 uint64_t StrLength =
120 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
121
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Chris Lattner79e079d2009-02-24 23:10:27 +0000123 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000124 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000125 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000126 // being initialized to a string literal.
127 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000128 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000129 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000130 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
131 ConstVal,
132 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000133 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000134 }
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Eli Friedman8718a6a2009-05-29 18:22:49 +0000136 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Eli Friedman8718a6a2009-05-29 18:22:49 +0000138 // C99 6.7.8p14. We have an array of character type with known size. However,
139 // the size may be smaller or larger than the string we are initializing.
140 // FIXME: Avoid truncation for 64-bit length strings.
141 if (StrLength-1 > CAT->getSize().getZExtValue())
142 S.Diag(Str->getSourceRange().getBegin(),
143 diag::warn_initializer_string_for_char_array_too_long)
144 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Eli Friedman8718a6a2009-05-29 18:22:49 +0000146 // Set the type to the actual size that we are initializing. If we have
147 // something like:
148 // char x[1] = "foo";
149 // then this will set the string literal's type to char[1].
150 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000151}
152
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000153//===----------------------------------------------------------------------===//
154// Semantic checking for initializer lists.
155//===----------------------------------------------------------------------===//
156
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// @brief Semantic checking for initializer lists.
158///
159/// The InitListChecker class contains a set of routines that each
160/// handle the initialization of a certain kind of entity, e.g.,
161/// arrays, vectors, struct/union types, scalars, etc. The
162/// InitListChecker itself performs a recursive walk of the subobject
163/// structure of the type to be initialized, while stepping through
164/// the initializer list one element at a time. The IList and Index
165/// parameters to each of the Check* routines contain the active
166/// (syntactic) initializer list and the index into that initializer
167/// list that represents the current initializer. Each routine is
168/// responsible for moving that Index forward as it consumes elements.
169///
170/// Each Check* routine also has a StructuredList/StructuredIndex
171/// arguments, which contains the current the "structured" (semantic)
172/// initializer list and the index into that initializer list where we
173/// are copying initializers as we map them over to the semantic
174/// list. Once we have completed our recursive walk of the subobject
175/// structure, we will have constructed a full semantic initializer
176/// list.
177///
178/// C99 designators cause changes in the initializer list traversal,
179/// because they make the initialization "jump" into a specific
180/// subobject and then continue the initialization from that
181/// point. CheckDesignatedInitializer() recursively steps into the
182/// designated subobject and manages backing out the recursion to
183/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000184namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000185class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000186 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000187 bool hadError;
188 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
189 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000190
191 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000197 unsigned &StructuredIndex,
198 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000199 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
200 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000201 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000202 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000203 unsigned &StructuredIndex,
204 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000205 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000209 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000210 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000213 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000214 unsigned &Index,
215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000217 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000218 InitListExpr *StructuredList,
219 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000220 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
221 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000226 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000231 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
242 QualType CurrentObjectType,
243 InitListExpr *StructuredList,
244 unsigned StructuredIndex,
245 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000251
Douglas Gregord6d37de2009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000257public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000258 InitListChecker(Sema &S, const InitializedEntity &Entity,
259 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000260 bool HadError() { return hadError; }
261
262 // @brief Retrieves the fully-structured initializer list used for
263 // semantic analysis and code generation.
264 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
265};
Chris Lattner8b419b92009-02-24 22:48:58 +0000266} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000267
Douglas Gregord6d37de2009-12-22 00:05:34 +0000268void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
269 const InitializedEntity &ParentEntity,
270 InitListExpr *ILE,
271 bool &RequiresSecondPass) {
272 SourceLocation Loc = ILE->getSourceRange().getBegin();
273 unsigned NumInits = ILE->getNumInits();
274 InitializedEntity MemberEntity
275 = InitializedEntity::InitializeMember(Field, &ParentEntity);
276 if (Init >= NumInits || !ILE->getInit(Init)) {
277 // FIXME: We probably don't need to handle references
278 // specially here, since value-initialization of references is
279 // handled in InitializationSequence.
280 if (Field->getType()->isReferenceType()) {
281 // C++ [dcl.init.aggr]p9:
282 // If an incomplete or empty initializer-list leaves a
283 // member of reference type uninitialized, the program is
284 // ill-formed.
285 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
286 << Field->getType()
287 << ILE->getSyntacticForm()->getSourceRange();
288 SemaRef.Diag(Field->getLocation(),
289 diag::note_uninit_reference_member);
290 hadError = true;
291 return;
292 }
293
294 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
295 true);
296 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
297 if (!InitSeq) {
298 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
299 hadError = true;
300 return;
301 }
302
303 Sema::OwningExprResult MemberInit
304 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
305 Sema::MultiExprArg(SemaRef, 0, 0));
306 if (MemberInit.isInvalid()) {
307 hadError = true;
308 return;
309 }
310
311 if (hadError) {
312 // Do nothing
313 } else if (Init < NumInits) {
314 ILE->setInit(Init, MemberInit.takeAs<Expr>());
315 } else if (InitSeq.getKind()
316 == InitializationSequence::ConstructorInitialization) {
317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
321 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
322 RequiresSecondPass = true;
323 }
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
326 FillInValueInitializations(MemberEntity, InnerILE,
327 RequiresSecondPass);
328}
329
Douglas Gregor4c678342009-01-28 21:54:33 +0000330/// Recursively replaces NULL values within the given initializer list
331/// with expressions that perform value-initialization of the
332/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000333void
334InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335 InitListExpr *ILE,
336 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremenek6217b802009-07-29 21:53:49 +0000343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
348 else {
349 unsigned Init = 0;
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000356
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000359
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000362 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000363
Douglas Gregord6d37de2009-12-22 00:05:34 +0000364 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365
Douglas Gregord6d37de2009-12-22 00:05:34 +0000366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
368 break;
369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 }
371
372 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000373 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
375 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000377 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
385 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
390 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000396 if (hadError)
397 return;
398
Anders Carlssond3d824d2010-01-23 04:34:47 +0000399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 ElementEntity.setElementIndex(Init);
402
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405 true);
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407 if (!InitSeq) {
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000413 Sema::OwningExprResult ElementInit
414 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
415 Sema::MultiExprArg(SemaRef, 0, 0));
416 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000417 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 return;
419 }
420
421 if (hadError) {
422 // Do nothing
423 } else if (Init < NumInits) {
424 ILE->setInit(Init, ElementInit.takeAs<Expr>());
425 } else if (InitSeq.getKind()
426 == InitializationSequence::ConstructorInitialization) {
427 // Value-initialization requires a constructor call, so
428 // extend the initializer list to include the constructor
429 // call and make a note that we'll need to take another pass
430 // through the initializer list.
431 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
432 RequiresSecondPass = true;
433 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000434 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
436 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000437 }
438}
439
Chris Lattner68355a52009-01-29 05:10:57 +0000440
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
442 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000443 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000444 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000445
Eli Friedmanb85f7072008-05-19 19:16:24 +0000446 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000447 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000448 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000449 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000450 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
451 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000452
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000453 if (!hadError) {
454 bool RequiresSecondPass = false;
455 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000456 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000457 FillInValueInitializations(Entity, FullyStructuredList,
458 RequiresSecondPass);
459 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000460}
461
462int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000463 // FIXME: use a proper constant
464 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000465 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000466 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000467 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
468 }
469 return maxElements;
470}
471
472int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000473 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000474 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000475 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000476 Field = structDecl->field_begin(),
477 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 Field != FieldEnd; ++Field) {
479 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
480 ++InitializableMembers;
481 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000482 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000483 return std::min(InitializableMembers, 1);
484 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000485}
486
Mike Stump1eb44332009-09-09 15:08:12 +0000487void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 QualType T, unsigned &Index,
489 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000490 unsigned &StructuredIndex,
491 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000492 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Steve Naroff0cca7492008-05-01 22:18:59 +0000494 if (T->isArrayType())
495 maxElements = numArrayElements(T);
496 else if (T->isStructureType() || T->isUnionType())
497 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000498 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000499 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 else
501 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000502
Eli Friedman402256f2008-05-25 13:49:22 +0000503 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000504 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000505 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000507 hadError = true;
508 return;
509 }
510
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 // Build a structured initializer list corresponding to this subobject.
512 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000513 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
514 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000515 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
516 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000518
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000520 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000522 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000523 StructuredSubobjectInitIndex,
524 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000525 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000526 StructuredSubobjectInitList->setType(T);
527
Douglas Gregored8a93d2009-03-01 17:12:46 +0000528 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000529 // range corresponds with the end of the last initializer it used.
530 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000531 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000532 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
533 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
534 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000535}
536
Steve Naroffa647caa2008-05-06 00:23:44 +0000537void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000538 unsigned &Index,
539 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000540 unsigned &StructuredIndex,
541 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000542 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000543 SyntacticToSemantic[IList] = StructuredList;
544 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000545 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000547 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000548 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000549 if (hadError)
550 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000551
Eli Friedman638e1442008-05-25 13:22:35 +0000552 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000553 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000554 if (StructuredIndex == 1 &&
555 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000556 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000558 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000559 hadError = true;
560 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000561 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000563 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000564 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000565 // Don't complain for incomplete types, since we'll get an error
566 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000567 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000568 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000569 CurrentObjectType->isArrayType()? 0 :
570 CurrentObjectType->isVectorType()? 1 :
571 CurrentObjectType->isScalarType()? 2 :
572 CurrentObjectType->isUnionType()? 3 :
573 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000574
575 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000576 if (SemaRef.getLangOptions().CPlusPlus) {
577 DK = diag::err_excess_initializers;
578 hadError = true;
579 }
Nate Begeman08634522009-07-07 21:53:06 +0000580 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
581 DK = diag::err_excess_initializers;
582 hadError = true;
583 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000584
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000586 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 }
588 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000589
Eli Friedman759f2522009-05-16 11:45:48 +0000590 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000591 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000592 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000593 << CodeModificationHint::CreateRemoval(IList->getLocStart())
594 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000595}
596
Eli Friedmanb85f7072008-05-19 19:16:24 +0000597void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000598 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000599 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000600 unsigned &Index,
601 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000602 unsigned &StructuredIndex,
603 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000604 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000605 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000606 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000607 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000608 } else if (DeclType->isAggregateType()) {
609 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000610 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000611 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000613 StructuredList, StructuredIndex,
614 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000615 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000616 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000617 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000618 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000619 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
620 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000621 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000622 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000623 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
624 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000625 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000626 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000627 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000628 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000629 } else if (DeclType->isRecordType()) {
630 // C++ [dcl.init]p14:
631 // [...] If the class is an aggregate (8.5.1), and the initializer
632 // is a brace-enclosed list, see 8.5.1.
633 //
634 // Note: 8.5.1 is handled below; here, we diagnose the case where
635 // we have an initializer list and a destination type that is not
636 // an aggregate.
637 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000638 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000639 << DeclType << IList->getSourceRange();
640 hadError = true;
641 } else if (DeclType->isReferenceType()) {
642 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000643 } else {
644 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000645 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000646 assert(0 && "Unsupported initializer type");
647 }
648}
649
Eli Friedmanb85f7072008-05-19 19:16:24 +0000650void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000651 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 unsigned &Index,
653 InitListExpr *StructuredList,
654 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000655 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000656 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
657 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000658 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000659 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000660 = getStructuredSubobjectInit(IList, Index, ElemType,
661 StructuredList, StructuredIndex,
662 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000663 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000664 newStructuredList, newStructuredIndex);
665 ++StructuredIndex;
666 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000667 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
668 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000669 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000670 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000671 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000672 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000673 } else if (ElemType->isReferenceType()) {
674 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000675 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000676 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000677 // C++ [dcl.init.aggr]p12:
678 // All implicit type conversions (clause 4) are considered when
679 // initializing the aggregate member with an ini- tializer from
680 // an initializer-list. If the initializer can initialize a
681 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000682 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000683 = SemaRef.TryCopyInitialization(expr, ElemType,
684 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000685 /*ForceRValue=*/false,
686 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000687
John McCall1d318332010-01-12 00:44:57 +0000688 if (!ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000689 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000690 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000691 hadError = true;
692 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
693 ++Index;
694 return;
695 }
696
697 // Fall through for subaggregate initialization
698 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000699 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000700 //
701 // The initializer for a structure or union object that has
702 // automatic storage duration shall be either an initializer
703 // list as described below, or a single expression that has
704 // compatible structure or union type. In the latter case, the
705 // initial value of the object, including unnamed members, is
706 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000707 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000708 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000709 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
710 ++Index;
711 return;
712 }
713
714 // Fall through for subaggregate initialization
715 }
716
717 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000718 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 // [...] Otherwise, if the member is itself a non-empty
720 // subaggregate, brace elision is assumed and the initializer is
721 // considered for the initialization of the first member of
722 // the subaggregate.
723 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000724 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000725 StructuredIndex);
726 ++StructuredIndex;
727 } else {
728 // We cannot initialize this element, so let
729 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000730 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000731 hadError = true;
732 ++Index;
733 ++StructuredIndex;
734 }
735 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000736}
737
Douglas Gregor930d8b52009-01-30 22:09:00 +0000738void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000739 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000740 InitListExpr *StructuredList,
741 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000742 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000743 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000744 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000745 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000746 diag::err_many_braces_around_scalar_init)
747 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000748 hadError = true;
749 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000750 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000751 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000752 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000753 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000754 diag::err_designator_for_scalar_init)
755 << DeclType << expr->getSourceRange();
756 hadError = true;
757 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000758 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000759 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000760 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000761
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000762 Sema::OwningExprResult Result =
763 CheckSingleInitializer(0, SemaRef.Owned(expr), DeclType, SemaRef);
764
765 Expr *ResultExpr;
766
767 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000768 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000769 else {
770 ResultExpr = Result.takeAs<Expr>();
771
772 if (ResultExpr != expr) {
773 // The type was promoted, update initializer list.
774 IList->setInit(Index, ResultExpr);
775 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000776 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000777 if (hadError)
778 ++StructuredIndex;
779 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000780 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000781 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000782 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000783 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000784 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000785 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000786 ++Index;
787 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000788 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000789 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000790}
791
Douglas Gregor930d8b52009-01-30 22:09:00 +0000792void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
793 unsigned &Index,
794 InitListExpr *StructuredList,
795 unsigned &StructuredIndex) {
796 if (Index < IList->getNumInits()) {
797 Expr *expr = IList->getInit(Index);
798 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000799 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 << DeclType << IList->getSourceRange();
801 hadError = true;
802 ++Index;
803 ++StructuredIndex;
804 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000805 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000806
807 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000808 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000809 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000810 /*SuppressUserConversions=*/false,
811 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000812 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000813 hadError = true;
814 else if (savExpr != expr) {
815 // The type was promoted, update initializer list.
816 IList->setInit(Index, expr);
817 }
818 if (hadError)
819 ++StructuredIndex;
820 else
821 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
822 ++Index;
823 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000824 // FIXME: It would be wonderful if we could point at the actual member. In
825 // general, it would be useful to pass location information down the stack,
826 // so that we know the location (or decl) of the "current object" being
827 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000828 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000829 diag::err_init_reference_member_uninitialized)
830 << DeclType
831 << IList->getSourceRange();
832 hadError = true;
833 ++Index;
834 ++StructuredIndex;
835 return;
836 }
837}
838
Mike Stump1eb44332009-09-09 15:08:12 +0000839void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000840 unsigned &Index,
841 InitListExpr *StructuredList,
842 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000843 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000844 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000845 unsigned maxElements = VT->getNumElements();
846 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000847 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Nate Begeman2ef13e52009-08-10 23:49:36 +0000849 if (!SemaRef.getLangOptions().OpenCL) {
850 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
851 // Don't attempt to go past the end of the init list
852 if (Index >= IList->getNumInits())
853 break;
854 CheckSubElementType(IList, elementType, Index,
855 StructuredList, StructuredIndex);
856 }
857 } else {
858 // OpenCL initializers allows vectors to be constructed from vectors.
859 for (unsigned i = 0; i < maxElements; ++i) {
860 // Don't attempt to go past the end of the init list
861 if (Index >= IList->getNumInits())
862 break;
863 QualType IType = IList->getInit(Index)->getType();
864 if (!IType->isVectorType()) {
865 CheckSubElementType(IList, elementType, Index,
866 StructuredList, StructuredIndex);
867 ++numEltsInit;
868 } else {
John McCall183700f2009-09-21 23:43:11 +0000869 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000870 unsigned numIElts = IVT->getNumElements();
871 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
872 numIElts);
873 CheckSubElementType(IList, VecType, Index,
874 StructuredList, StructuredIndex);
875 numEltsInit += numIElts;
876 }
877 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Nate Begeman2ef13e52009-08-10 23:49:36 +0000880 // OpenCL & AltiVec require all elements to be initialized.
881 if (numEltsInit != maxElements)
882 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
883 SemaRef.Diag(IList->getSourceRange().getBegin(),
884 diag::err_vector_incorrect_num_initializers)
885 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000886 }
887}
888
Mike Stump1eb44332009-09-09 15:08:12 +0000889void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000890 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000891 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000892 unsigned &Index,
893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 // Check for the special-case of initializing an array with a string.
896 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000897 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
898 SemaRef.Context)) {
899 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000900 // We place the string literal directly into the resulting
901 // initializer list. This is the only place where the structure
902 // of the structured initializer list doesn't match exactly,
903 // because doing so would involve allocating one character
904 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000905 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000906 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000907 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000908 return;
909 }
910 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000911 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000912 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000913 // Check for VLAs; in standard C it would be possible to check this
914 // earlier, but I don't know where clang accepts VLAs (gcc accepts
915 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000916 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000917 diag::err_variable_object_no_init)
918 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000919 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000920 ++Index;
921 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000922 return;
923 }
924
Douglas Gregor05c13a32009-01-22 00:58:24 +0000925 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000926 llvm::APSInt maxElements(elementIndex.getBitWidth(),
927 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000928 bool maxElementsKnown = false;
929 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000930 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000931 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000932 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000933 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000934 maxElementsKnown = true;
935 }
936
Chris Lattner08202542009-02-24 22:50:46 +0000937 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000938 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000939 while (Index < IList->getNumInits()) {
940 Expr *Init = IList->getInit(Index);
941 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000942 // If we're not the subobject that matches up with the '{' for
943 // the designator, we shouldn't be handling the
944 // designator. Return immediately.
945 if (!SubobjectIsDesignatorContext)
946 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000947
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000948 // Handle this designated initializer. elementIndex will be
949 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +0000950 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000951 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000952 StructuredList, StructuredIndex, true,
953 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000954 hadError = true;
955 continue;
956 }
957
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000958 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
959 maxElements.extend(elementIndex.getBitWidth());
960 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
961 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000962 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000963
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000964 // If the array is of incomplete type, keep track of the number of
965 // elements in the initializer.
966 if (!maxElementsKnown && elementIndex > maxElements)
967 maxElements = elementIndex;
968
Douglas Gregor05c13a32009-01-22 00:58:24 +0000969 continue;
970 }
971
972 // If we know the maximum number of elements, and we've already
973 // hit it, stop consuming elements in the initializer list.
974 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000975 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000976
977 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000978 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000979 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000980 ++elementIndex;
981
982 // If the array is of incomplete type, keep track of the number of
983 // elements in the initializer.
984 if (!maxElementsKnown && elementIndex > maxElements)
985 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000986 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000987 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000988 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000989 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000990 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000991 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000992 // Sizing an array implicitly to zero is not allowed by ISO C,
993 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000994 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000995 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000996 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000997
Mike Stump1eb44332009-09-09 15:08:12 +0000998 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000999 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 }
1001}
1002
Mike Stump1eb44332009-09-09 15:08:12 +00001003void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1004 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001005 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001006 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001007 unsigned &Index,
1008 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001009 unsigned &StructuredIndex,
1010 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001011 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Eli Friedmanb85f7072008-05-19 19:16:24 +00001013 // If the record is invalid, some of it's members are invalid. To avoid
1014 // confusion, we forgo checking the intializer for the entire record.
1015 if (structDecl->isInvalidDecl()) {
1016 hadError = true;
1017 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001018 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001019
1020 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1021 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001022 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001023 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001024 Field != FieldEnd; ++Field) {
1025 if (Field->getDeclName()) {
1026 StructuredList->setInitializedFieldInUnion(*Field);
1027 break;
1028 }
1029 }
1030 return;
1031 }
1032
Douglas Gregor05c13a32009-01-22 00:58:24 +00001033 // If structDecl is a forward declaration, this loop won't do
1034 // anything except look at designated initializers; That's okay,
1035 // because an error should get printed out elsewhere. It might be
1036 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001037 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001038 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001039 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 while (Index < IList->getNumInits()) {
1041 Expr *Init = IList->getInit(Index);
1042
1043 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001044 // If we're not the subobject that matches up with the '{' for
1045 // the designator, we shouldn't be handling the
1046 // designator. Return immediately.
1047 if (!SubobjectIsDesignatorContext)
1048 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001049
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001050 // Handle this designated initializer. Field will be updated to
1051 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001052 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001053 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001054 StructuredList, StructuredIndex,
1055 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001056 hadError = true;
1057
Douglas Gregordfb5e592009-02-12 19:00:39 +00001058 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001059 continue;
1060 }
1061
1062 if (Field == FieldEnd) {
1063 // We've run out of fields. We're done.
1064 break;
1065 }
1066
Douglas Gregordfb5e592009-02-12 19:00:39 +00001067 // We've already initialized a member of a union. We're done.
1068 if (InitializedSomething && DeclType->isUnionType())
1069 break;
1070
Douglas Gregor44b43212008-12-11 16:49:14 +00001071 // If we've hit the flexible array member at the end, we're done.
1072 if (Field->getType()->isIncompleteArrayType())
1073 break;
1074
Douglas Gregor0bb76892009-01-29 16:53:55 +00001075 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001076 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001077 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001078 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001079 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001080
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001081 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001082 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001083 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001084
1085 if (DeclType->isUnionType()) {
1086 // Initialize the first field within the union.
1087 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001088 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
1090 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001091 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001092
Mike Stump1eb44332009-09-09 15:08:12 +00001093 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001094 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001095 return;
1096
1097 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001098 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001099 (!isa<InitListExpr>(IList->getInit(Index)) ||
1100 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001101 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001102 diag::err_flexible_array_init_nonempty)
1103 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001104 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001105 << *Field;
1106 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001107 ++Index;
1108 return;
1109 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001110 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001111 diag::ext_flexible_array_init)
1112 << IList->getInit(Index)->getSourceRange().getBegin();
1113 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1114 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001115 }
1116
Douglas Gregora6457962009-03-20 00:32:56 +00001117 if (isa<InitListExpr>(IList->getInit(Index)))
1118 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1119 StructuredIndex);
1120 else
1121 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1122 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001123}
Steve Naroff0cca7492008-05-01 22:18:59 +00001124
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001125/// \brief Expand a field designator that refers to a member of an
1126/// anonymous struct or union into a series of field designators that
1127/// refers to the field within the appropriate subobject.
1128///
1129/// Field/FieldIndex will be updated to point to the (new)
1130/// currently-designated field.
1131static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001132 DesignatedInitExpr *DIE,
1133 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001134 FieldDecl *Field,
1135 RecordDecl::field_iterator &FieldIter,
1136 unsigned &FieldIndex) {
1137 typedef DesignatedInitExpr::Designator Designator;
1138
1139 // Build the path from the current object to the member of the
1140 // anonymous struct/union (backwards).
1141 llvm::SmallVector<FieldDecl *, 4> Path;
1142 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001144 // Build the replacement designators.
1145 llvm::SmallVector<Designator, 4> Replacements;
1146 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1147 FI = Path.rbegin(), FIEnd = Path.rend();
1148 FI != FIEnd; ++FI) {
1149 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001150 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001151 DIE->getDesignator(DesigIdx)->getDotLoc(),
1152 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1153 else
1154 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1155 SourceLocation()));
1156 Replacements.back().setField(*FI);
1157 }
1158
1159 // Expand the current designator into the set of replacement
1160 // designators, so we have a full subobject path down to where the
1161 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001162 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001163 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001165 // Update FieldIter/FieldIndex;
1166 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001167 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001168 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001169 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001170 FieldIter != FEnd; ++FieldIter) {
1171 if (FieldIter->isUnnamedBitfield())
1172 continue;
1173
1174 if (*FieldIter == Path.back())
1175 return;
1176
1177 ++FieldIndex;
1178 }
1179
1180 assert(false && "Unable to find anonymous struct/union field");
1181}
1182
Douglas Gregor05c13a32009-01-22 00:58:24 +00001183/// @brief Check the well-formedness of a C99 designated initializer.
1184///
1185/// Determines whether the designated initializer @p DIE, which
1186/// resides at the given @p Index within the initializer list @p
1187/// IList, is well-formed for a current object of type @p DeclType
1188/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001189/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001190/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001191///
1192/// @param IList The initializer list in which this designated
1193/// initializer occurs.
1194///
Douglas Gregor71199712009-04-15 04:56:10 +00001195/// @param DIE The designated initializer expression.
1196///
1197/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001198///
1199/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1200/// into which the designation in @p DIE should refer.
1201///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001202/// @param NextField If non-NULL and the first designator in @p DIE is
1203/// a field, this will be set to the field declaration corresponding
1204/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001205///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001206/// @param NextElementIndex If non-NULL and the first designator in @p
1207/// DIE is an array designator or GNU array-range designator, this
1208/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001209///
1210/// @param Index Index into @p IList where the designated initializer
1211/// @p DIE occurs.
1212///
Douglas Gregor4c678342009-01-28 21:54:33 +00001213/// @param StructuredList The initializer list expression that
1214/// describes all of the subobject initializers in the order they'll
1215/// actually be initialized.
1216///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001217/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001218bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001219InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001220 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001221 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001222 QualType &CurrentObjectType,
1223 RecordDecl::field_iterator *NextField,
1224 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001225 unsigned &Index,
1226 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001227 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001228 bool FinishSubobjectInit,
1229 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001230 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001231 // Check the actual initialization for the designated object type.
1232 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001233
1234 // Temporarily remove the designator expression from the
1235 // initializer list that the child calls see, so that we don't try
1236 // to re-process the designator.
1237 unsigned OldIndex = Index;
1238 IList->setInit(OldIndex, DIE->getInit());
1239
1240 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001241 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001242
1243 // Restore the designated initializer expression in the syntactic
1244 // form of the initializer list.
1245 if (IList->getInit(OldIndex) != DIE->getInit())
1246 DIE->setInit(IList->getInit(OldIndex));
1247 IList->setInit(OldIndex, DIE);
1248
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001249 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001250 }
1251
Douglas Gregor71199712009-04-15 04:56:10 +00001252 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001253 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001254 "Need a non-designated initializer list to start from");
1255
Douglas Gregor71199712009-04-15 04:56:10 +00001256 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001257 // Determine the structural initializer list that corresponds to the
1258 // current subobject.
1259 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001260 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001261 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001262 SourceRange(D->getStartLocation(),
1263 DIE->getSourceRange().getEnd()));
1264 assert(StructuredList && "Expected a structured initializer list");
1265
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001266 if (D->isFieldDesignator()) {
1267 // C99 6.7.8p7:
1268 //
1269 // If a designator has the form
1270 //
1271 // . identifier
1272 //
1273 // then the current object (defined below) shall have
1274 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001275 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001276 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001277 if (!RT) {
1278 SourceLocation Loc = D->getDotLoc();
1279 if (Loc.isInvalid())
1280 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001281 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1282 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001283 ++Index;
1284 return true;
1285 }
1286
Douglas Gregor4c678342009-01-28 21:54:33 +00001287 // Note: we perform a linear search of the fields here, despite
1288 // the fact that we have a faster lookup method, because we always
1289 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001290 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001291 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001293 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001294 Field = RT->getDecl()->field_begin(),
1295 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 for (; Field != FieldEnd; ++Field) {
1297 if (Field->isUnnamedBitfield())
1298 continue;
1299
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001300 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001301 break;
1302
1303 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001304 }
1305
Douglas Gregor4c678342009-01-28 21:54:33 +00001306 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001307 // There was no normal field in the struct with the designated
1308 // name. Perform another lookup for this name, which may find
1309 // something that we can't designate (e.g., a member function),
1310 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001311 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001312 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001313 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001314 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001315 // Name lookup didn't find anything. Determine whether this
1316 // was a typo for another field name.
1317 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1318 Sema::LookupMemberName);
1319 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1320 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1321 ReplacementField->getDeclContext()->getLookupContext()
1322 ->Equals(RT->getDecl())) {
1323 SemaRef.Diag(D->getFieldLoc(),
1324 diag::err_field_designator_unknown_suggest)
1325 << FieldName << CurrentObjectType << R.getLookupName()
1326 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1327 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001328 SemaRef.Diag(ReplacementField->getLocation(),
1329 diag::note_previous_decl)
1330 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001331 } else {
1332 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1333 << FieldName << CurrentObjectType;
1334 ++Index;
1335 return true;
1336 }
1337 } else if (!KnownField) {
1338 // Determine whether we found a field at all.
1339 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1340 }
1341
1342 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001343 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001344 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001345 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001346 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001348 ++Index;
1349 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001350 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001351
1352 if (!KnownField &&
1353 cast<RecordDecl>((ReplacementField)->getDeclContext())
1354 ->isAnonymousStructOrUnion()) {
1355 // Handle an field designator that refers to a member of an
1356 // anonymous struct or union.
1357 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1358 ReplacementField,
1359 Field, FieldIndex);
1360 D = DIE->getDesignator(DesigIdx);
1361 } else if (!KnownField) {
1362 // The replacement field comes from typo correction; find it
1363 // in the list of fields.
1364 FieldIndex = 0;
1365 Field = RT->getDecl()->field_begin();
1366 for (; Field != FieldEnd; ++Field) {
1367 if (Field->isUnnamedBitfield())
1368 continue;
1369
1370 if (ReplacementField == *Field ||
1371 Field->getIdentifier() == ReplacementField->getIdentifier())
1372 break;
1373
1374 ++FieldIndex;
1375 }
1376 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001377 } else if (!KnownField &&
1378 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001380 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1381 Field, FieldIndex);
1382 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001383 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001384
1385 // All of the fields of a union are located at the same place in
1386 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001387 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001388 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001389 StructuredList->setInitializedFieldInUnion(*Field);
1390 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001391
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001392 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregor4c678342009-01-28 21:54:33 +00001395 // Make sure that our non-designated initializer list has space
1396 // for a subobject corresponding to this field.
1397 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001398 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001399
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001400 // This designator names a flexible array member.
1401 if (Field->getType()->isIncompleteArrayType()) {
1402 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001403 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 // We can't designate an object within the flexible array
1405 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001406 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001407 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001408 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001409 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001410 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001411 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001412 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001413 << *Field;
1414 Invalid = true;
1415 }
1416
1417 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1418 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001419 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001420 diag::err_flexible_array_init_needs_braces)
1421 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001422 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001423 << *Field;
1424 Invalid = true;
1425 }
1426
1427 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001428 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001429 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001430 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001431 diag::err_flexible_array_init_nonempty)
1432 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001433 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001434 << *Field;
1435 Invalid = true;
1436 }
1437
1438 if (Invalid) {
1439 ++Index;
1440 return true;
1441 }
1442
1443 // Initialize the array.
1444 bool prevHadError = hadError;
1445 unsigned newStructuredIndex = FieldIndex;
1446 unsigned OldIndex = Index;
1447 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001448 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 StructuredList, newStructuredIndex);
1450 IList->setInit(OldIndex, DIE);
1451 if (hadError && !prevHadError) {
1452 ++Field;
1453 ++FieldIndex;
1454 if (NextField)
1455 *NextField = Field;
1456 StructuredIndex = FieldIndex;
1457 return true;
1458 }
1459 } else {
1460 // Recurse to check later designated subobjects.
1461 QualType FieldType = (*Field)->getType();
1462 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001463 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1464 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001465 true, false))
1466 return true;
1467 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001468
1469 // Find the position of the next field to be initialized in this
1470 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001471 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001472 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001473
1474 // If this the first designator, our caller will continue checking
1475 // the rest of this struct/class/union subobject.
1476 if (IsFirstDesignator) {
1477 if (NextField)
1478 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001479 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001480 return false;
1481 }
1482
Douglas Gregor34e79462009-01-28 23:36:17 +00001483 if (!FinishSubobjectInit)
1484 return false;
1485
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001486 // We've already initialized something in the union; we're done.
1487 if (RT->getDecl()->isUnion())
1488 return hadError;
1489
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001490 // Check the remaining fields within this class/struct/union subobject.
1491 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001492 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1493 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001494 return hadError && !prevHadError;
1495 }
1496
1497 // C99 6.7.8p6:
1498 //
1499 // If a designator has the form
1500 //
1501 // [ constant-expression ]
1502 //
1503 // then the current object (defined below) shall have array
1504 // type and the expression shall be an integer constant
1505 // expression. If the array is of unknown size, any
1506 // nonnegative value is valid.
1507 //
1508 // Additionally, cope with the GNU extension that permits
1509 // designators of the form
1510 //
1511 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001512 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001513 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001514 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001515 << CurrentObjectType;
1516 ++Index;
1517 return true;
1518 }
1519
1520 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001521 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1522 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001524 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001525 DesignatedEndIndex = DesignatedStartIndex;
1526 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001528
Mike Stump1eb44332009-09-09 15:08:12 +00001529
1530 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001531 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001532 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001533 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001534 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001535
Chris Lattner3bf68932009-04-25 21:59:05 +00001536 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001537 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001538 }
1539
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001540 if (isa<ConstantArrayType>(AT)) {
1541 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001542 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1543 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1544 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1545 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1546 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001547 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001548 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001549 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001550 << IndexExpr->getSourceRange();
1551 ++Index;
1552 return true;
1553 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001554 } else {
1555 // Make sure the bit-widths and signedness match.
1556 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1557 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001558 else if (DesignatedStartIndex.getBitWidth() <
1559 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001560 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1561 DesignatedStartIndex.setIsUnsigned(true);
1562 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Douglas Gregor4c678342009-01-28 21:54:33 +00001565 // Make sure that our non-designated initializer list has space
1566 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001567 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001568 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001569 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001570
Douglas Gregor34e79462009-01-28 23:36:17 +00001571 // Repeatedly perform subobject initializations in the range
1572 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001573
Douglas Gregor34e79462009-01-28 23:36:17 +00001574 // Move to the next designator
1575 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1576 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001577 while (DesignatedStartIndex <= DesignatedEndIndex) {
1578 // Recurse to check later designated subobjects.
1579 QualType ElementType = AT->getElementType();
1580 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001581 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1582 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001583 (DesignatedStartIndex == DesignatedEndIndex),
1584 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001585 return true;
1586
1587 // Move to the next index in the array that we'll be initializing.
1588 ++DesignatedStartIndex;
1589 ElementIndex = DesignatedStartIndex.getZExtValue();
1590 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591
1592 // If this the first designator, our caller will continue checking
1593 // the rest of this array subobject.
1594 if (IsFirstDesignator) {
1595 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001596 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001597 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001598 return false;
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregor34e79462009-01-28 23:36:17 +00001601 if (!FinishSubobjectInit)
1602 return false;
1603
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001604 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001605 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001606 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001607 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001608 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001609}
1610
Douglas Gregor4c678342009-01-28 21:54:33 +00001611// Get the structured initializer list for a subobject of type
1612// @p CurrentObjectType.
1613InitListExpr *
1614InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1615 QualType CurrentObjectType,
1616 InitListExpr *StructuredList,
1617 unsigned StructuredIndex,
1618 SourceRange InitRange) {
1619 Expr *ExistingInit = 0;
1620 if (!StructuredList)
1621 ExistingInit = SyntacticToSemantic[IList];
1622 else if (StructuredIndex < StructuredList->getNumInits())
1623 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Douglas Gregor4c678342009-01-28 21:54:33 +00001625 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1626 return Result;
1627
1628 if (ExistingInit) {
1629 // We are creating an initializer list that initializes the
1630 // subobjects of the current object, but there was already an
1631 // initialization that completely initialized the current
1632 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001633 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001634 // struct X { int a, b; };
1635 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001636 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001637 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1638 // designated initializer re-initializes the whole
1639 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001640 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001641 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001642 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001643 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001644 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001645 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001646 << ExistingInit->getSourceRange();
1647 }
1648
Mike Stump1eb44332009-09-09 15:08:12 +00001649 InitListExpr *Result
1650 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001651 InitRange.getEnd());
1652
Douglas Gregor4c678342009-01-28 21:54:33 +00001653 Result->setType(CurrentObjectType);
1654
Douglas Gregorfa219202009-03-20 23:58:33 +00001655 // Pre-allocate storage for the structured initializer list.
1656 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001657 unsigned NumInits = 0;
1658 if (!StructuredList)
1659 NumInits = IList->getNumInits();
1660 else if (Index < IList->getNumInits()) {
1661 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1662 NumInits = SubList->getNumInits();
1663 }
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001666 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1667 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1668 NumElements = CAType->getSize().getZExtValue();
1669 // Simple heuristic so that we don't allocate a very large
1670 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001671 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001672 NumElements = 0;
1673 }
John McCall183700f2009-09-21 23:43:11 +00001674 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001675 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001676 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001677 RecordDecl *RDecl = RType->getDecl();
1678 if (RDecl->isUnion())
1679 NumElements = 1;
1680 else
Mike Stump1eb44332009-09-09 15:08:12 +00001681 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001682 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001683 }
1684
Douglas Gregor08457732009-03-21 18:13:52 +00001685 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001686 NumElements = IList->getNumInits();
1687
1688 Result->reserveInits(NumElements);
1689
Douglas Gregor4c678342009-01-28 21:54:33 +00001690 // Link this new initializer list into the structured initializer
1691 // lists.
1692 if (StructuredList)
1693 StructuredList->updateInit(StructuredIndex, Result);
1694 else {
1695 Result->setSyntacticForm(IList);
1696 SyntacticToSemantic[IList] = Result;
1697 }
1698
1699 return Result;
1700}
1701
1702/// Update the initializer at index @p StructuredIndex within the
1703/// structured initializer list to the value @p expr.
1704void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1705 unsigned &StructuredIndex,
1706 Expr *expr) {
1707 // No structured initializer list to update
1708 if (!StructuredList)
1709 return;
1710
1711 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1712 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001713 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001714 diag::warn_initializer_overrides)
1715 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001716 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001717 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001718 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001719 << PrevInit->getSourceRange();
1720 }
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 ++StructuredIndex;
1723}
1724
Douglas Gregor05c13a32009-01-22 00:58:24 +00001725/// Check that the given Index expression is a valid array designator
1726/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001727/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001728/// and produces a reasonable diagnostic if there is a
1729/// failure. Returns true if there was an error, false otherwise. If
1730/// everything went okay, Value will receive the value of the constant
1731/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001732static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001733CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001734 SourceLocation Loc = Index->getSourceRange().getBegin();
1735
1736 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001737 if (S.VerifyIntegerConstantExpression(Index, &Value))
1738 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001739
Chris Lattner3bf68932009-04-25 21:59:05 +00001740 if (Value.isSigned() && Value.isNegative())
1741 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001742 << Value.toString(10) << Index->getSourceRange();
1743
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001744 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001745 return false;
1746}
1747
1748Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1749 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001750 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001751 OwningExprResult Init) {
1752 typedef DesignatedInitExpr::Designator ASTDesignator;
1753
1754 bool Invalid = false;
1755 llvm::SmallVector<ASTDesignator, 32> Designators;
1756 llvm::SmallVector<Expr *, 32> InitExpressions;
1757
1758 // Build designators and check array designator expressions.
1759 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1760 const Designator &D = Desig.getDesignator(Idx);
1761 switch (D.getKind()) {
1762 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001763 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001764 D.getFieldLoc()));
1765 break;
1766
1767 case Designator::ArrayDesignator: {
1768 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1769 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001770 if (!Index->isTypeDependent() &&
1771 !Index->isValueDependent() &&
1772 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001773 Invalid = true;
1774 else {
1775 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001776 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001777 D.getRBracketLoc()));
1778 InitExpressions.push_back(Index);
1779 }
1780 break;
1781 }
1782
1783 case Designator::ArrayRangeDesignator: {
1784 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1785 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1786 llvm::APSInt StartValue;
1787 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001788 bool StartDependent = StartIndex->isTypeDependent() ||
1789 StartIndex->isValueDependent();
1790 bool EndDependent = EndIndex->isTypeDependent() ||
1791 EndIndex->isValueDependent();
1792 if ((!StartDependent &&
1793 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1794 (!EndDependent &&
1795 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001796 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001797 else {
1798 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001799 if (StartDependent || EndDependent) {
1800 // Nothing to compute.
1801 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001802 EndValue.extend(StartValue.getBitWidth());
1803 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1804 StartValue.extend(EndValue.getBitWidth());
1805
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001806 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001807 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001808 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001809 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1810 Invalid = true;
1811 } else {
1812 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001813 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001814 D.getEllipsisLoc(),
1815 D.getRBracketLoc()));
1816 InitExpressions.push_back(StartIndex);
1817 InitExpressions.push_back(EndIndex);
1818 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001819 }
1820 break;
1821 }
1822 }
1823 }
1824
1825 if (Invalid || Init.isInvalid())
1826 return ExprError();
1827
1828 // Clear out the expressions within the designation.
1829 Desig.ClearExprs(*this);
1830
1831 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001832 = DesignatedInitExpr::Create(Context,
1833 Designators.data(), Designators.size(),
1834 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001835 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001836 return Owned(DIE);
1837}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001838
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001839bool Sema::CheckInitList(const InitializedEntity &Entity,
1840 InitListExpr *&InitList, QualType &DeclType) {
1841 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001842 if (!CheckInitList.HadError())
1843 InitList = CheckInitList.getFullyStructuredList();
1844
1845 return CheckInitList.HadError();
1846}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001847
Douglas Gregor20093b42009-12-09 23:02:17 +00001848//===----------------------------------------------------------------------===//
1849// Initialization entity
1850//===----------------------------------------------------------------------===//
1851
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001852InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1853 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001854 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001855{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001856 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1857 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001858 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001859 } else {
1860 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001861 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001862 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001863}
1864
1865InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1866 CXXBaseSpecifier *Base)
1867{
1868 InitializedEntity Result;
1869 Result.Kind = EK_Base;
1870 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001871 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001872 return Result;
1873}
1874
Douglas Gregor99a2e602009-12-16 01:38:02 +00001875DeclarationName InitializedEntity::getName() const {
1876 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001877 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001878 if (!VariableOrMember)
1879 return DeclarationName();
1880 // Fall through
1881
1882 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001883 case EK_Member:
1884 return VariableOrMember->getDeclName();
1885
1886 case EK_Result:
1887 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001888 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001889 case EK_Temporary:
1890 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001891 case EK_ArrayElement:
1892 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001893 return DeclarationName();
1894 }
1895
1896 // Silence GCC warning
1897 return DeclarationName();
1898}
1899
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001900DeclaratorDecl *InitializedEntity::getDecl() const {
1901 switch (getKind()) {
1902 case EK_Variable:
1903 case EK_Parameter:
1904 case EK_Member:
1905 return VariableOrMember;
1906
1907 case EK_Result:
1908 case EK_Exception:
1909 case EK_New:
1910 case EK_Temporary:
1911 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001912 case EK_ArrayElement:
1913 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001914 return 0;
1915 }
1916
1917 // Silence GCC warning
1918 return 0;
1919}
1920
Douglas Gregor20093b42009-12-09 23:02:17 +00001921//===----------------------------------------------------------------------===//
1922// Initialization sequence
1923//===----------------------------------------------------------------------===//
1924
1925void InitializationSequence::Step::Destroy() {
1926 switch (Kind) {
1927 case SK_ResolveAddressOfOverloadedFunction:
1928 case SK_CastDerivedToBaseRValue:
1929 case SK_CastDerivedToBaseLValue:
1930 case SK_BindReference:
1931 case SK_BindReferenceToTemporary:
1932 case SK_UserConversion:
1933 case SK_QualificationConversionRValue:
1934 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001935 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001936 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001937 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001938 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001939 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001940 break;
1941
1942 case SK_ConversionSequence:
1943 delete ICS;
1944 }
1945}
1946
1947void InitializationSequence::AddAddressOverloadResolutionStep(
1948 FunctionDecl *Function) {
1949 Step S;
1950 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1951 S.Type = Function->getType();
1952 S.Function = Function;
1953 Steps.push_back(S);
1954}
1955
1956void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1957 bool IsLValue) {
1958 Step S;
1959 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1960 S.Type = BaseType;
1961 Steps.push_back(S);
1962}
1963
1964void InitializationSequence::AddReferenceBindingStep(QualType T,
1965 bool BindingTemporary) {
1966 Step S;
1967 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1968 S.Type = T;
1969 Steps.push_back(S);
1970}
1971
Eli Friedman03981012009-12-11 02:42:07 +00001972void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1973 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001974 Step S;
1975 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00001976 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00001977 S.Function = Function;
1978 Steps.push_back(S);
1979}
1980
1981void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1982 bool IsLValue) {
1983 Step S;
1984 S.Kind = IsLValue? SK_QualificationConversionLValue
1985 : SK_QualificationConversionRValue;
1986 S.Type = Ty;
1987 Steps.push_back(S);
1988}
1989
1990void InitializationSequence::AddConversionSequenceStep(
1991 const ImplicitConversionSequence &ICS,
1992 QualType T) {
1993 Step S;
1994 S.Kind = SK_ConversionSequence;
1995 S.Type = T;
1996 S.ICS = new ImplicitConversionSequence(ICS);
1997 Steps.push_back(S);
1998}
1999
Douglas Gregord87b61f2009-12-10 17:56:55 +00002000void InitializationSequence::AddListInitializationStep(QualType T) {
2001 Step S;
2002 S.Kind = SK_ListInitialization;
2003 S.Type = T;
2004 Steps.push_back(S);
2005}
2006
Douglas Gregor51c56d62009-12-14 20:49:26 +00002007void
2008InitializationSequence::AddConstructorInitializationStep(
2009 CXXConstructorDecl *Constructor,
2010 QualType T) {
2011 Step S;
2012 S.Kind = SK_ConstructorInitialization;
2013 S.Type = T;
2014 S.Function = Constructor;
2015 Steps.push_back(S);
2016}
2017
Douglas Gregor71d17402009-12-15 00:01:57 +00002018void InitializationSequence::AddZeroInitializationStep(QualType T) {
2019 Step S;
2020 S.Kind = SK_ZeroInitialization;
2021 S.Type = T;
2022 Steps.push_back(S);
2023}
2024
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002025void InitializationSequence::AddCAssignmentStep(QualType T) {
2026 Step S;
2027 S.Kind = SK_CAssignment;
2028 S.Type = T;
2029 Steps.push_back(S);
2030}
2031
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002032void InitializationSequence::AddStringInitStep(QualType T) {
2033 Step S;
2034 S.Kind = SK_StringInit;
2035 S.Type = T;
2036 Steps.push_back(S);
2037}
2038
Douglas Gregor20093b42009-12-09 23:02:17 +00002039void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2040 OverloadingResult Result) {
2041 SequenceKind = FailedSequence;
2042 this->Failure = Failure;
2043 this->FailedOverloadResult = Result;
2044}
2045
2046//===----------------------------------------------------------------------===//
2047// Attempt initialization
2048//===----------------------------------------------------------------------===//
2049
2050/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002051static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002052 const InitializedEntity &Entity,
2053 const InitializationKind &Kind,
2054 InitListExpr *InitList,
2055 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002056 // FIXME: We only perform rudimentary checking of list
2057 // initializations at this point, then assume that any list
2058 // initialization of an array, aggregate, or scalar will be
2059 // well-formed. We we actually "perform" list initialization, we'll
2060 // do all of the necessary checking. C++0x initializer lists will
2061 // force us to perform more checking here.
2062 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2063
Douglas Gregord6542d82009-12-22 15:35:07 +00002064 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002065
2066 // C++ [dcl.init]p13:
2067 // If T is a scalar type, then a declaration of the form
2068 //
2069 // T x = { a };
2070 //
2071 // is equivalent to
2072 //
2073 // T x = a;
2074 if (DestType->isScalarType()) {
2075 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2076 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2077 return;
2078 }
2079
2080 // Assume scalar initialization from a single value works.
2081 } else if (DestType->isAggregateType()) {
2082 // Assume aggregate initialization works.
2083 } else if (DestType->isVectorType()) {
2084 // Assume vector initialization works.
2085 } else if (DestType->isReferenceType()) {
2086 // FIXME: C++0x defines behavior for this.
2087 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2088 return;
2089 } else if (DestType->isRecordType()) {
2090 // FIXME: C++0x defines behavior for this
2091 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2092 }
2093
2094 // Add a general "list initialization" step.
2095 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002096}
2097
2098/// \brief Try a reference initialization that involves calling a conversion
2099/// function.
2100///
2101/// FIXME: look intos DRs 656, 896
2102static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2103 const InitializedEntity &Entity,
2104 const InitializationKind &Kind,
2105 Expr *Initializer,
2106 bool AllowRValues,
2107 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002108 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002109 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2110 QualType T1 = cv1T1.getUnqualifiedType();
2111 QualType cv2T2 = Initializer->getType();
2112 QualType T2 = cv2T2.getUnqualifiedType();
2113
2114 bool DerivedToBase;
2115 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2116 T1, T2, DerivedToBase) &&
2117 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002118 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002119
2120 // Build the candidate set directly in the initialization sequence
2121 // structure, so that it will persist if we fail.
2122 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2123 CandidateSet.clear();
2124
2125 // Determine whether we are allowed to call explicit constructors or
2126 // explicit conversion operators.
2127 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2128
2129 const RecordType *T1RecordType = 0;
2130 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2131 // The type we're converting to is a class type. Enumerate its constructors
2132 // to see if there is a suitable conversion.
2133 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2134
2135 DeclarationName ConstructorName
2136 = S.Context.DeclarationNames.getCXXConstructorName(
2137 S.Context.getCanonicalType(T1).getUnqualifiedType());
2138 DeclContext::lookup_iterator Con, ConEnd;
2139 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2140 Con != ConEnd; ++Con) {
2141 // Find the constructor (which may be a template).
2142 CXXConstructorDecl *Constructor = 0;
2143 FunctionTemplateDecl *ConstructorTmpl
2144 = dyn_cast<FunctionTemplateDecl>(*Con);
2145 if (ConstructorTmpl)
2146 Constructor = cast<CXXConstructorDecl>(
2147 ConstructorTmpl->getTemplatedDecl());
2148 else
2149 Constructor = cast<CXXConstructorDecl>(*Con);
2150
2151 if (!Constructor->isInvalidDecl() &&
2152 Constructor->isConvertingConstructor(AllowExplicit)) {
2153 if (ConstructorTmpl)
2154 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2155 &Initializer, 1, CandidateSet);
2156 else
2157 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2158 }
2159 }
2160 }
2161
2162 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2163 // The type we're converting from is a class type, enumerate its conversion
2164 // functions.
2165 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2166
2167 // Determine the type we are converting to. If we are allowed to
2168 // convert to an rvalue, take the type that the destination type
2169 // refers to.
2170 QualType ToType = AllowRValues? cv1T1 : DestType;
2171
John McCalleec51cf2010-01-20 00:46:10 +00002172 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002173 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002174 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2175 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002176 NamedDecl *D = *I;
2177 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2178 if (isa<UsingShadowDecl>(D))
2179 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2180
2181 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2182 CXXConversionDecl *Conv;
2183 if (ConvTemplate)
2184 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2185 else
2186 Conv = cast<CXXConversionDecl>(*I);
2187
2188 // If the conversion function doesn't return a reference type,
2189 // it can't be considered for this conversion unless we're allowed to
2190 // consider rvalues.
2191 // FIXME: Do we need to make sure that we only consider conversion
2192 // candidates with reference-compatible results? That might be needed to
2193 // break recursion.
2194 if ((AllowExplicit || !Conv->isExplicit()) &&
2195 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2196 if (ConvTemplate)
2197 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2198 ToType, CandidateSet);
2199 else
2200 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2201 CandidateSet);
2202 }
2203 }
2204 }
2205
2206 SourceLocation DeclLoc = Initializer->getLocStart();
2207
2208 // Perform overload resolution. If it fails, return the failed result.
2209 OverloadCandidateSet::iterator Best;
2210 if (OverloadingResult Result
2211 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2212 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002213
Douglas Gregor20093b42009-12-09 23:02:17 +00002214 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002215
2216 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002217 if (isa<CXXConversionDecl>(Function))
2218 T2 = Function->getResultType();
2219 else
2220 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002221
2222 // Add the user-defined conversion step.
2223 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2224
2225 // Determine whether we need to perform derived-to-base or
2226 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002227 bool NewDerivedToBase = false;
2228 Sema::ReferenceCompareResult NewRefRelationship
2229 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2230 NewDerivedToBase);
2231 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2232 "Overload resolution picked a bad conversion function");
2233 (void)NewRefRelationship;
2234 if (NewDerivedToBase)
2235 Sequence.AddDerivedToBaseCastStep(
2236 S.Context.getQualifiedType(T1,
2237 T2.getNonReferenceType().getQualifiers()),
2238 /*isLValue=*/true);
2239
2240 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2241 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2242
2243 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2244 return OR_Success;
2245}
2246
2247/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2248static void TryReferenceInitialization(Sema &S,
2249 const InitializedEntity &Entity,
2250 const InitializationKind &Kind,
2251 Expr *Initializer,
2252 InitializationSequence &Sequence) {
2253 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2254
Douglas Gregord6542d82009-12-22 15:35:07 +00002255 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002256 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002257 Qualifiers T1Quals;
2258 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002259 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002260 Qualifiers T2Quals;
2261 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002262 SourceLocation DeclLoc = Initializer->getLocStart();
2263
2264 // If the initializer is the address of an overloaded function, try
2265 // to resolve the overloaded function. If all goes well, T2 is the
2266 // type of the resulting function.
2267 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2268 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2269 T1,
2270 false);
2271 if (!Fn) {
2272 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2273 return;
2274 }
2275
2276 Sequence.AddAddressOverloadResolutionStep(Fn);
2277 cv2T2 = Fn->getType();
2278 T2 = cv2T2.getUnqualifiedType();
2279 }
2280
2281 // FIXME: Rvalue references
2282 bool ForceRValue = false;
2283
2284 // Compute some basic properties of the types and the initializer.
2285 bool isLValueRef = DestType->isLValueReferenceType();
2286 bool isRValueRef = !isLValueRef;
2287 bool DerivedToBase = false;
2288 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2289 Initializer->isLvalue(S.Context);
2290 Sema::ReferenceCompareResult RefRelationship
2291 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2292
2293 // C++0x [dcl.init.ref]p5:
2294 // A reference to type "cv1 T1" is initialized by an expression of type
2295 // "cv2 T2" as follows:
2296 //
2297 // - If the reference is an lvalue reference and the initializer
2298 // expression
2299 OverloadingResult ConvOvlResult = OR_Success;
2300 if (isLValueRef) {
2301 if (InitLvalue == Expr::LV_Valid &&
2302 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2303 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2304 // reference-compatible with "cv2 T2," or
2305 //
2306 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2307 // bit-field when we're determining whether the reference initialization
2308 // can occur. This property will be checked by PerformInitialization.
2309 if (DerivedToBase)
2310 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002311 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002312 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002313 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002314 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2315 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2316 return;
2317 }
2318
2319 // - has a class type (i.e., T2 is a class type), where T1 is not
2320 // reference-related to T2, and can be implicitly converted to an
2321 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2322 // with "cv3 T3" (this conversion is selected by enumerating the
2323 // applicable conversion functions (13.3.1.6) and choosing the best
2324 // one through overload resolution (13.3)),
2325 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2326 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2327 Initializer,
2328 /*AllowRValues=*/false,
2329 Sequence);
2330 if (ConvOvlResult == OR_Success)
2331 return;
John McCall1d318332010-01-12 00:44:57 +00002332 if (ConvOvlResult != OR_No_Viable_Function) {
2333 Sequence.SetOverloadFailure(
2334 InitializationSequence::FK_ReferenceInitOverloadFailed,
2335 ConvOvlResult);
2336 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002337 }
2338 }
2339
2340 // - Otherwise, the reference shall be an lvalue reference to a
2341 // non-volatile const type (i.e., cv1 shall be const), or the reference
2342 // shall be an rvalue reference and the initializer expression shall
2343 // be an rvalue.
Chandler Carruth5535c382010-01-12 20:32:25 +00002344 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002345 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2346 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2347 Sequence.SetOverloadFailure(
2348 InitializationSequence::FK_ReferenceInitOverloadFailed,
2349 ConvOvlResult);
2350 else if (isLValueRef)
2351 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2352 ? (RefRelationship == Sema::Ref_Related
2353 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2354 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2355 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2356 else
2357 Sequence.SetFailed(
2358 InitializationSequence::FK_RValueReferenceBindingToLValue);
2359
2360 return;
2361 }
2362
2363 // - If T1 and T2 are class types and
2364 if (T1->isRecordType() && T2->isRecordType()) {
2365 // - the initializer expression is an rvalue and "cv1 T1" is
2366 // reference-compatible with "cv2 T2", or
2367 if (InitLvalue != Expr::LV_Valid &&
2368 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2369 if (DerivedToBase)
2370 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002371 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002372 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002373 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002374 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2375 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2376 return;
2377 }
2378
2379 // - T1 is not reference-related to T2 and the initializer expression
2380 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2381 // conversion is selected by enumerating the applicable conversion
2382 // functions (13.3.1.6) and choosing the best one through overload
2383 // resolution (13.3)),
2384 if (RefRelationship == Sema::Ref_Incompatible) {
2385 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2386 Kind, Initializer,
2387 /*AllowRValues=*/true,
2388 Sequence);
2389 if (ConvOvlResult)
2390 Sequence.SetOverloadFailure(
2391 InitializationSequence::FK_ReferenceInitOverloadFailed,
2392 ConvOvlResult);
2393
2394 return;
2395 }
2396
2397 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2398 return;
2399 }
2400
2401 // - If the initializer expression is an rvalue, with T2 an array type,
2402 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2403 // is bound to the object represented by the rvalue (see 3.10).
2404 // FIXME: How can an array type be reference-compatible with anything?
2405 // Don't we mean the element types of T1 and T2?
2406
2407 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2408 // from the initializer expression using the rules for a non-reference
2409 // copy initialization (8.5). The reference is then bound to the
2410 // temporary. [...]
2411 // Determine whether we are allowed to call explicit constructors or
2412 // explicit conversion operators.
2413 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2414 ImplicitConversionSequence ICS
2415 = S.TryImplicitConversion(Initializer, cv1T1,
2416 /*SuppressUserConversions=*/false, AllowExplicit,
2417 /*ForceRValue=*/false,
2418 /*FIXME:InOverloadResolution=*/false,
2419 /*UserCast=*/Kind.isExplicitCast());
2420
John McCall1d318332010-01-12 00:44:57 +00002421 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002422 // FIXME: Use the conversion function set stored in ICS to turn
2423 // this into an overloading ambiguity diagnostic. However, we need
2424 // to keep that set as an OverloadCandidateSet rather than as some
2425 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002426 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2427 Sequence.SetOverloadFailure(
2428 InitializationSequence::FK_ReferenceInitOverloadFailed,
2429 ConvOvlResult);
2430 else
2431 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 return;
2433 }
2434
2435 // [...] If T1 is reference-related to T2, cv1 must be the
2436 // same cv-qualification as, or greater cv-qualification
2437 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002438 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2439 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002441 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002442 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2443 return;
2444 }
2445
2446 // Perform the actual conversion.
2447 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2448 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2449 return;
2450}
2451
2452/// \brief Attempt character array initialization from a string literal
2453/// (C++ [dcl.init.string], C99 6.7.8).
2454static void TryStringLiteralInitialization(Sema &S,
2455 const InitializedEntity &Entity,
2456 const InitializationKind &Kind,
2457 Expr *Initializer,
2458 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002459 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002460 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002461}
2462
Douglas Gregor20093b42009-12-09 23:02:17 +00002463/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2464/// enumerates the constructors of the initialized entity and performs overload
2465/// resolution to select the best.
2466static void TryConstructorInitialization(Sema &S,
2467 const InitializedEntity &Entity,
2468 const InitializationKind &Kind,
2469 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002470 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002472 if (Kind.getKind() == InitializationKind::IK_Copy)
2473 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2474 else
2475 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002476
2477 // Build the candidate set directly in the initialization sequence
2478 // structure, so that it will persist if we fail.
2479 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2480 CandidateSet.clear();
2481
2482 // Determine whether we are allowed to call explicit constructors or
2483 // explicit conversion operators.
2484 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2485 Kind.getKind() == InitializationKind::IK_Value ||
2486 Kind.getKind() == InitializationKind::IK_Default);
2487
2488 // The type we're converting to is a class type. Enumerate its constructors
2489 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002490 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2491 assert(DestRecordType && "Constructor initialization requires record type");
2492 CXXRecordDecl *DestRecordDecl
2493 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2494
2495 DeclarationName ConstructorName
2496 = S.Context.DeclarationNames.getCXXConstructorName(
2497 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2498 DeclContext::lookup_iterator Con, ConEnd;
2499 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2500 Con != ConEnd; ++Con) {
2501 // Find the constructor (which may be a template).
2502 CXXConstructorDecl *Constructor = 0;
2503 FunctionTemplateDecl *ConstructorTmpl
2504 = dyn_cast<FunctionTemplateDecl>(*Con);
2505 if (ConstructorTmpl)
2506 Constructor = cast<CXXConstructorDecl>(
2507 ConstructorTmpl->getTemplatedDecl());
2508 else
2509 Constructor = cast<CXXConstructorDecl>(*Con);
2510
2511 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002512 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002513 if (ConstructorTmpl)
2514 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2515 Args, NumArgs, CandidateSet);
2516 else
2517 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2518 }
2519 }
2520
2521 SourceLocation DeclLoc = Kind.getLocation();
2522
2523 // Perform overload resolution. If it fails, return the failed result.
2524 OverloadCandidateSet::iterator Best;
2525 if (OverloadingResult Result
2526 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2527 Sequence.SetOverloadFailure(
2528 InitializationSequence::FK_ConstructorOverloadFailed,
2529 Result);
2530 return;
2531 }
2532
2533 // Add the constructor initialization step. Any cv-qualification conversion is
2534 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002535 if (Kind.getKind() == InitializationKind::IK_Copy) {
2536 Sequence.AddUserConversionStep(Best->Function, DestType);
2537 } else {
2538 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002539 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002540 DestType);
2541 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002542}
2543
Douglas Gregor71d17402009-12-15 00:01:57 +00002544/// \brief Attempt value initialization (C++ [dcl.init]p7).
2545static void TryValueInitialization(Sema &S,
2546 const InitializedEntity &Entity,
2547 const InitializationKind &Kind,
2548 InitializationSequence &Sequence) {
2549 // C++ [dcl.init]p5:
2550 //
2551 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002552 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002553
2554 // -- if T is an array type, then each element is value-initialized;
2555 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2556 T = AT->getElementType();
2557
2558 if (const RecordType *RT = T->getAs<RecordType>()) {
2559 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2560 // -- if T is a class type (clause 9) with a user-declared
2561 // constructor (12.1), then the default constructor for T is
2562 // called (and the initialization is ill-formed if T has no
2563 // accessible default constructor);
2564 //
2565 // FIXME: we really want to refer to a single subobject of the array,
2566 // but Entity doesn't have a way to capture that (yet).
2567 if (ClassDecl->hasUserDeclaredConstructor())
2568 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2569
Douglas Gregor16006c92009-12-16 18:50:27 +00002570 // -- if T is a (possibly cv-qualified) non-union class type
2571 // without a user-provided constructor, then the object is
2572 // zero-initialized and, if T’s implicitly-declared default
2573 // constructor is non-trivial, that constructor is called.
2574 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2575 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2576 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002577 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002578 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2579 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002580 }
2581 }
2582
Douglas Gregord6542d82009-12-22 15:35:07 +00002583 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002584 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2585}
2586
Douglas Gregor99a2e602009-12-16 01:38:02 +00002587/// \brief Attempt default initialization (C++ [dcl.init]p6).
2588static void TryDefaultInitialization(Sema &S,
2589 const InitializedEntity &Entity,
2590 const InitializationKind &Kind,
2591 InitializationSequence &Sequence) {
2592 assert(Kind.getKind() == InitializationKind::IK_Default);
2593
2594 // C++ [dcl.init]p6:
2595 // To default-initialize an object of type T means:
2596 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002597 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002598 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2599 DestType = Array->getElementType();
2600
2601 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2602 // constructor for T is called (and the initialization is ill-formed if
2603 // T has no accessible default constructor);
2604 if (DestType->isRecordType()) {
2605 // FIXME: If a program calls for the default initialization of an object of
2606 // a const-qualified type T, T shall be a class type with a user-provided
2607 // default constructor.
2608 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2609 Sequence);
2610 }
2611
2612 // - otherwise, no initialization is performed.
2613 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2614
2615 // If a program calls for the default initialization of an object of
2616 // a const-qualified type T, T shall be a class type with a user-provided
2617 // default constructor.
2618 if (DestType.isConstQualified())
2619 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2620}
2621
Douglas Gregor20093b42009-12-09 23:02:17 +00002622/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2623/// which enumerates all conversion functions and performs overload resolution
2624/// to select the best.
2625static void TryUserDefinedConversion(Sema &S,
2626 const InitializedEntity &Entity,
2627 const InitializationKind &Kind,
2628 Expr *Initializer,
2629 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002630 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2631
Douglas Gregord6542d82009-12-22 15:35:07 +00002632 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002633 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2634 QualType SourceType = Initializer->getType();
2635 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2636 "Must have a class type to perform a user-defined conversion");
2637
2638 // Build the candidate set directly in the initialization sequence
2639 // structure, so that it will persist if we fail.
2640 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2641 CandidateSet.clear();
2642
2643 // Determine whether we are allowed to call explicit constructors or
2644 // explicit conversion operators.
2645 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2646
2647 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2648 // The type we're converting to is a class type. Enumerate its constructors
2649 // to see if there is a suitable conversion.
2650 CXXRecordDecl *DestRecordDecl
2651 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2652
2653 DeclarationName ConstructorName
2654 = S.Context.DeclarationNames.getCXXConstructorName(
2655 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2656 DeclContext::lookup_iterator Con, ConEnd;
2657 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2658 Con != ConEnd; ++Con) {
2659 // Find the constructor (which may be a template).
2660 CXXConstructorDecl *Constructor = 0;
2661 FunctionTemplateDecl *ConstructorTmpl
2662 = dyn_cast<FunctionTemplateDecl>(*Con);
2663 if (ConstructorTmpl)
2664 Constructor = cast<CXXConstructorDecl>(
2665 ConstructorTmpl->getTemplatedDecl());
2666 else
2667 Constructor = cast<CXXConstructorDecl>(*Con);
2668
2669 if (!Constructor->isInvalidDecl() &&
2670 Constructor->isConvertingConstructor(AllowExplicit)) {
2671 if (ConstructorTmpl)
2672 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2673 &Initializer, 1, CandidateSet);
2674 else
2675 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2676 }
2677 }
2678 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002679
2680 SourceLocation DeclLoc = Initializer->getLocStart();
2681
Douglas Gregor4a520a22009-12-14 17:27:33 +00002682 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2683 // The type we're converting from is a class type, enumerate its conversion
2684 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002685
Eli Friedman33c2da92009-12-20 22:12:03 +00002686 // We can only enumerate the conversion functions for a complete type; if
2687 // the type isn't complete, simply skip this step.
2688 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2689 CXXRecordDecl *SourceRecordDecl
2690 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002691
John McCalleec51cf2010-01-20 00:46:10 +00002692 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002693 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002694 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002695 E = Conversions->end();
2696 I != E; ++I) {
2697 NamedDecl *D = *I;
2698 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2699 if (isa<UsingShadowDecl>(D))
2700 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2701
2702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2703 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002704 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002705 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002706 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002707 Conv = cast<CXXConversionDecl>(*I);
2708
2709 if (AllowExplicit || !Conv->isExplicit()) {
2710 if (ConvTemplate)
2711 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2712 Initializer, DestType,
2713 CandidateSet);
2714 else
2715 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2716 CandidateSet);
2717 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002718 }
2719 }
2720 }
2721
Douglas Gregor4a520a22009-12-14 17:27:33 +00002722 // Perform overload resolution. If it fails, return the failed result.
2723 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002724 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002725 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2726 Sequence.SetOverloadFailure(
2727 InitializationSequence::FK_UserConversionOverloadFailed,
2728 Result);
2729 return;
2730 }
John McCall1d318332010-01-12 00:44:57 +00002731
Douglas Gregor4a520a22009-12-14 17:27:33 +00002732 FunctionDecl *Function = Best->Function;
2733
2734 if (isa<CXXConstructorDecl>(Function)) {
2735 // Add the user-defined conversion step. Any cv-qualification conversion is
2736 // subsumed by the initialization.
2737 Sequence.AddUserConversionStep(Function, DestType);
2738 return;
2739 }
2740
2741 // Add the user-defined conversion step that calls the conversion function.
2742 QualType ConvType = Function->getResultType().getNonReferenceType();
2743 Sequence.AddUserConversionStep(Function, ConvType);
2744
2745 // If the conversion following the call to the conversion function is
2746 // interesting, add it as a separate step.
2747 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2748 Best->FinalConversion.Third) {
2749 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002750 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002751 ICS.Standard = Best->FinalConversion;
2752 Sequence.AddConversionSequenceStep(ICS, DestType);
2753 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002754}
2755
2756/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2757/// non-class type to another.
2758static void TryImplicitConversion(Sema &S,
2759 const InitializedEntity &Entity,
2760 const InitializationKind &Kind,
2761 Expr *Initializer,
2762 InitializationSequence &Sequence) {
2763 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002764 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002765 /*SuppressUserConversions=*/true,
2766 /*AllowExplicit=*/false,
2767 /*ForceRValue=*/false,
2768 /*FIXME:InOverloadResolution=*/false,
2769 /*UserCast=*/Kind.isExplicitCast());
2770
John McCall1d318332010-01-12 00:44:57 +00002771 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002772 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2773 return;
2774 }
2775
Douglas Gregord6542d82009-12-22 15:35:07 +00002776 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002777}
2778
2779InitializationSequence::InitializationSequence(Sema &S,
2780 const InitializedEntity &Entity,
2781 const InitializationKind &Kind,
2782 Expr **Args,
2783 unsigned NumArgs) {
2784 ASTContext &Context = S.Context;
2785
2786 // C++0x [dcl.init]p16:
2787 // The semantics of initializers are as follows. The destination type is
2788 // the type of the object or reference being initialized and the source
2789 // type is the type of the initializer expression. The source type is not
2790 // defined when the initializer is a braced-init-list or when it is a
2791 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002792 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002793
2794 if (DestType->isDependentType() ||
2795 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2796 SequenceKind = DependentSequence;
2797 return;
2798 }
2799
2800 QualType SourceType;
2801 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002802 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002803 Initializer = Args[0];
2804 if (!isa<InitListExpr>(Initializer))
2805 SourceType = Initializer->getType();
2806 }
2807
2808 // - If the initializer is a braced-init-list, the object is
2809 // list-initialized (8.5.4).
2810 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2811 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002812 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002813 }
2814
2815 // - If the destination type is a reference type, see 8.5.3.
2816 if (DestType->isReferenceType()) {
2817 // C++0x [dcl.init.ref]p1:
2818 // A variable declared to be a T& or T&&, that is, "reference to type T"
2819 // (8.3.2), shall be initialized by an object, or function, of type T or
2820 // by an object that can be converted into a T.
2821 // (Therefore, multiple arguments are not permitted.)
2822 if (NumArgs != 1)
2823 SetFailed(FK_TooManyInitsForReference);
2824 else
2825 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2826 return;
2827 }
2828
2829 // - If the destination type is an array of characters, an array of
2830 // char16_t, an array of char32_t, or an array of wchar_t, and the
2831 // initializer is a string literal, see 8.5.2.
2832 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2833 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2834 return;
2835 }
2836
2837 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002838 if (Kind.getKind() == InitializationKind::IK_Value ||
2839 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002840 TryValueInitialization(S, Entity, Kind, *this);
2841 return;
2842 }
2843
Douglas Gregor99a2e602009-12-16 01:38:02 +00002844 // Handle default initialization.
2845 if (Kind.getKind() == InitializationKind::IK_Default){
2846 TryDefaultInitialization(S, Entity, Kind, *this);
2847 return;
2848 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002849
Douglas Gregor20093b42009-12-09 23:02:17 +00002850 // - Otherwise, if the destination type is an array, the program is
2851 // ill-formed.
2852 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2853 if (AT->getElementType()->isAnyCharacterType())
2854 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2855 else
2856 SetFailed(FK_ArrayNeedsInitList);
2857
2858 return;
2859 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002860
2861 // Handle initialization in C
2862 if (!S.getLangOptions().CPlusPlus) {
2863 setSequenceKind(CAssignment);
2864 AddCAssignmentStep(DestType);
2865 return;
2866 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002867
2868 // - If the destination type is a (possibly cv-qualified) class type:
2869 if (DestType->isRecordType()) {
2870 // - If the initialization is direct-initialization, or if it is
2871 // copy-initialization where the cv-unqualified version of the
2872 // source type is the same class as, or a derived class of, the
2873 // class of the destination, constructors are considered. [...]
2874 if (Kind.getKind() == InitializationKind::IK_Direct ||
2875 (Kind.getKind() == InitializationKind::IK_Copy &&
2876 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2877 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002878 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002879 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002880 // - Otherwise (i.e., for the remaining copy-initialization cases),
2881 // user-defined conversion sequences that can convert from the source
2882 // type to the destination type or (when a conversion function is
2883 // used) to a derived class thereof are enumerated as described in
2884 // 13.3.1.4, and the best one is chosen through overload resolution
2885 // (13.3).
2886 else
2887 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2888 return;
2889 }
2890
Douglas Gregor99a2e602009-12-16 01:38:02 +00002891 if (NumArgs > 1) {
2892 SetFailed(FK_TooManyInitsForScalar);
2893 return;
2894 }
2895 assert(NumArgs == 1 && "Zero-argument case handled above");
2896
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 // - Otherwise, if the source type is a (possibly cv-qualified) class
2898 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002899 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002900 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2901 return;
2902 }
2903
2904 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002905 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002906 // conversions (Clause 4) will be used, if necessary, to convert the
2907 // initializer expression to the cv-unqualified version of the
2908 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002909 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002910 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2911}
2912
2913InitializationSequence::~InitializationSequence() {
2914 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2915 StepEnd = Steps.end();
2916 Step != StepEnd; ++Step)
2917 Step->Destroy();
2918}
2919
2920//===----------------------------------------------------------------------===//
2921// Perform initialization
2922//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002923static Sema::AssignmentAction
2924getAssignmentAction(const InitializedEntity &Entity) {
2925 switch(Entity.getKind()) {
2926 case InitializedEntity::EK_Variable:
2927 case InitializedEntity::EK_New:
2928 return Sema::AA_Initializing;
2929
2930 case InitializedEntity::EK_Parameter:
2931 // FIXME: Can we tell when we're sending vs. passing?
2932 return Sema::AA_Passing;
2933
2934 case InitializedEntity::EK_Result:
2935 return Sema::AA_Returning;
2936
2937 case InitializedEntity::EK_Exception:
2938 case InitializedEntity::EK_Base:
2939 llvm_unreachable("No assignment action for C++-specific initialization");
2940 break;
2941
2942 case InitializedEntity::EK_Temporary:
2943 // FIXME: Can we tell apart casting vs. converting?
2944 return Sema::AA_Casting;
2945
2946 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002947 case InitializedEntity::EK_ArrayElement:
2948 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002949 return Sema::AA_Initializing;
2950 }
2951
2952 return Sema::AA_Converting;
2953}
2954
2955static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2956 bool IsCopy) {
2957 switch (Entity.getKind()) {
2958 case InitializedEntity::EK_Result:
2959 case InitializedEntity::EK_Exception:
2960 return !IsCopy;
2961
2962 case InitializedEntity::EK_New:
2963 case InitializedEntity::EK_Variable:
2964 case InitializedEntity::EK_Base:
2965 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002966 case InitializedEntity::EK_ArrayElement:
2967 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002968 return false;
2969
2970 case InitializedEntity::EK_Parameter:
2971 case InitializedEntity::EK_Temporary:
2972 return true;
2973 }
2974
2975 llvm_unreachable("missed an InitializedEntity kind?");
2976}
2977
2978/// \brief If we need to perform an additional copy of the initialized object
2979/// for this kind of entity (e.g., the result of a function or an object being
2980/// thrown), make the copy.
2981static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2982 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002983 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002984 Sema::OwningExprResult CurInit) {
2985 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002986
2987 switch (Entity.getKind()) {
2988 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00002989 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002990 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002991 Loc = Entity.getReturnLoc();
2992 break;
2993
2994 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002995 Loc = Entity.getThrowLoc();
2996 break;
2997
2998 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00002999 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003000 Kind.getKind() != InitializationKind::IK_Copy)
3001 return move(CurInit);
3002 Loc = Entity.getDecl()->getLocation();
3003 break;
3004
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003005 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003006 // FIXME: Do we need this initialization for a parameter?
3007 return move(CurInit);
3008
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003009 case InitializedEntity::EK_New:
3010 case InitializedEntity::EK_Temporary:
3011 case InitializedEntity::EK_Base:
3012 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003013 case InitializedEntity::EK_ArrayElement:
3014 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003015 // We don't need to copy for any of these initialized entities.
3016 return move(CurInit);
3017 }
3018
3019 Expr *CurInitExpr = (Expr *)CurInit.get();
3020 CXXRecordDecl *Class = 0;
3021 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3022 Class = cast<CXXRecordDecl>(Record->getDecl());
3023 if (!Class)
3024 return move(CurInit);
3025
3026 // Perform overload resolution using the class's copy constructors.
3027 DeclarationName ConstructorName
3028 = S.Context.DeclarationNames.getCXXConstructorName(
3029 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3030 DeclContext::lookup_iterator Con, ConEnd;
3031 OverloadCandidateSet CandidateSet;
3032 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3033 Con != ConEnd; ++Con) {
3034 // Find the constructor (which may be a template).
3035 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3036 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003037 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003038 continue;
3039
3040 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3041 }
3042
3043 OverloadCandidateSet::iterator Best;
3044 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3045 case OR_Success:
3046 break;
3047
3048 case OR_No_Viable_Function:
3049 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003050 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003051 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003052 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3053 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003054 return S.ExprError();
3055
3056 case OR_Ambiguous:
3057 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003058 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003059 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003060 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3061 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003062 return S.ExprError();
3063
3064 case OR_Deleted:
3065 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003066 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003067 << CurInitExpr->getSourceRange();
3068 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3069 << Best->Function->isDeleted();
3070 return S.ExprError();
3071 }
3072
3073 CurInit.release();
3074 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3075 cast<CXXConstructorDecl>(Best->Function),
3076 /*Elidable=*/true,
3077 Sema::MultiExprArg(S,
3078 (void**)&CurInitExpr, 1));
3079}
Douglas Gregor20093b42009-12-09 23:02:17 +00003080
3081Action::OwningExprResult
3082InitializationSequence::Perform(Sema &S,
3083 const InitializedEntity &Entity,
3084 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003085 Action::MultiExprArg Args,
3086 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003087 if (SequenceKind == FailedSequence) {
3088 unsigned NumArgs = Args.size();
3089 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3090 return S.ExprError();
3091 }
3092
3093 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003094 // If the declaration is a non-dependent, incomplete array type
3095 // that has an initializer, then its type will be completed once
3096 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003097 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003098 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003099 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003100 if (const IncompleteArrayType *ArrayT
3101 = S.Context.getAsIncompleteArrayType(DeclType)) {
3102 // FIXME: We don't currently have the ability to accurately
3103 // compute the length of an initializer list without
3104 // performing full type-checking of the initializer list
3105 // (since we have to determine where braces are implicitly
3106 // introduced and such). So, we fall back to making the array
3107 // type a dependently-sized array type with no specified
3108 // bound.
3109 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3110 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003111
Douglas Gregord87b61f2009-12-10 17:56:55 +00003112 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003113 if (DeclaratorDecl *DD = Entity.getDecl()) {
3114 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3115 TypeLoc TL = TInfo->getTypeLoc();
3116 if (IncompleteArrayTypeLoc *ArrayLoc
3117 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3118 Brackets = ArrayLoc->getBracketsRange();
3119 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003120 }
3121
3122 *ResultType
3123 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3124 /*NumElts=*/0,
3125 ArrayT->getSizeModifier(),
3126 ArrayT->getIndexTypeCVRQualifiers(),
3127 Brackets);
3128 }
3129
3130 }
3131 }
3132
Eli Friedman08544622009-12-22 02:35:53 +00003133 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003134 return Sema::OwningExprResult(S, Args.release()[0]);
3135
3136 unsigned NumArgs = Args.size();
3137 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3138 SourceLocation(),
3139 (Expr **)Args.release(),
3140 NumArgs,
3141 SourceLocation()));
3142 }
3143
Douglas Gregor99a2e602009-12-16 01:38:02 +00003144 if (SequenceKind == NoInitialization)
3145 return S.Owned((Expr *)0);
3146
Douglas Gregord6542d82009-12-22 15:35:07 +00003147 QualType DestType = Entity.getType().getNonReferenceType();
3148 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003149 // the same as Entity.getDecl()->getType() in cases involving type merging,
3150 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003151 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003152 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003153 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003154
Douglas Gregor99a2e602009-12-16 01:38:02 +00003155 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3156
3157 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3158
3159 // For initialization steps that start with a single initializer,
3160 // grab the only argument out the Args and place it into the "current"
3161 // initializer.
3162 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003163 case SK_ResolveAddressOfOverloadedFunction:
3164 case SK_CastDerivedToBaseRValue:
3165 case SK_CastDerivedToBaseLValue:
3166 case SK_BindReference:
3167 case SK_BindReferenceToTemporary:
3168 case SK_UserConversion:
3169 case SK_QualificationConversionLValue:
3170 case SK_QualificationConversionRValue:
3171 case SK_ConversionSequence:
3172 case SK_ListInitialization:
3173 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003174 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003175 assert(Args.size() == 1);
3176 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3177 if (CurInit.isInvalid())
3178 return S.ExprError();
3179 break;
3180
3181 case SK_ConstructorInitialization:
3182 case SK_ZeroInitialization:
3183 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003184 }
3185
3186 // Walk through the computed steps for the initialization sequence,
3187 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003188 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 for (step_iterator Step = step_begin(), StepEnd = step_end();
3190 Step != StepEnd; ++Step) {
3191 if (CurInit.isInvalid())
3192 return S.ExprError();
3193
3194 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003195 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003196
3197 switch (Step->Kind) {
3198 case SK_ResolveAddressOfOverloadedFunction:
3199 // Overload resolution determined which function invoke; update the
3200 // initializer to reflect that choice.
3201 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3202 break;
3203
3204 case SK_CastDerivedToBaseRValue:
3205 case SK_CastDerivedToBaseLValue: {
3206 // We have a derived-to-base cast that produces either an rvalue or an
3207 // lvalue. Perform that cast.
3208
3209 // Casts to inaccessible base classes are allowed with C-style casts.
3210 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3211 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3212 CurInitExpr->getLocStart(),
3213 CurInitExpr->getSourceRange(),
3214 IgnoreBaseAccess))
3215 return S.ExprError();
3216
3217 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3218 CastExpr::CK_DerivedToBase,
3219 (Expr*)CurInit.release(),
3220 Step->Kind == SK_CastDerivedToBaseLValue));
3221 break;
3222 }
3223
3224 case SK_BindReference:
3225 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3226 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3227 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003228 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003229 << BitField->getDeclName()
3230 << CurInitExpr->getSourceRange();
3231 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3232 return S.ExprError();
3233 }
3234
3235 // Reference binding does not have any corresponding ASTs.
3236
3237 // Check exception specifications
3238 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3239 return S.ExprError();
3240 break;
3241
3242 case SK_BindReferenceToTemporary:
3243 // Check exception specifications
3244 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3245 return S.ExprError();
3246
3247 // FIXME: At present, we have no AST to describe when we need to make a
3248 // temporary to bind a reference to. We should.
3249 break;
3250
3251 case SK_UserConversion: {
3252 // We have a user-defined conversion that invokes either a constructor
3253 // or a conversion function.
3254 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003255 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 if (CXXConstructorDecl *Constructor
3257 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3258 // Build a call to the selected constructor.
3259 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3260 SourceLocation Loc = CurInitExpr->getLocStart();
3261 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3262
3263 // Determine the arguments required to actually perform the constructor
3264 // call.
3265 if (S.CompleteConstructorCall(Constructor,
3266 Sema::MultiExprArg(S,
3267 (void **)&CurInitExpr,
3268 1),
3269 Loc, ConstructorArgs))
3270 return S.ExprError();
3271
3272 // Build the an expression that constructs a temporary.
3273 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3274 move_arg(ConstructorArgs));
3275 if (CurInit.isInvalid())
3276 return S.ExprError();
3277
3278 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003279 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3280 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3281 S.IsDerivedFrom(SourceType, Class))
3282 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003283 } else {
3284 // Build a call to the conversion function.
3285 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003286
Douglas Gregor20093b42009-12-09 23:02:17 +00003287 // FIXME: Should we move this initialization into a separate
3288 // derived-to-base conversion? I believe the answer is "no", because
3289 // we don't want to turn off access control here for c-style casts.
3290 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3291 return S.ExprError();
3292
3293 // Do a little dance to make sure that CurInit has the proper
3294 // pointer.
3295 CurInit.release();
3296
3297 // Build the actual call to the conversion function.
3298 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3299 if (CurInit.isInvalid() || !CurInit.get())
3300 return S.ExprError();
3301
3302 CastKind = CastExpr::CK_UserDefinedConversion;
3303 }
3304
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003305 if (shouldBindAsTemporary(Entity, IsCopy))
3306 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3307
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 CurInitExpr = CurInit.takeAs<Expr>();
3309 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3310 CastKind,
3311 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003312 false));
3313
3314 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003315 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003316 break;
3317 }
3318
3319 case SK_QualificationConversionLValue:
3320 case SK_QualificationConversionRValue:
3321 // Perform a qualification conversion; these can never go wrong.
3322 S.ImpCastExprToType(CurInitExpr, Step->Type,
3323 CastExpr::CK_NoOp,
3324 Step->Kind == SK_QualificationConversionLValue);
3325 CurInit.release();
3326 CurInit = S.Owned(CurInitExpr);
3327 break;
3328
3329 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003330 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003331 false, false, *Step->ICS))
3332 return S.ExprError();
3333
3334 CurInit.release();
3335 CurInit = S.Owned(CurInitExpr);
3336 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003337
3338 case SK_ListInitialization: {
3339 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3340 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003341 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003342 return S.ExprError();
3343
3344 CurInit.release();
3345 CurInit = S.Owned(InitList);
3346 break;
3347 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003348
3349 case SK_ConstructorInitialization: {
3350 CXXConstructorDecl *Constructor
3351 = cast<CXXConstructorDecl>(Step->Function);
3352
3353 // Build a call to the selected constructor.
3354 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3355 SourceLocation Loc = Kind.getLocation();
3356
3357 // Determine the arguments required to actually perform the constructor
3358 // call.
3359 if (S.CompleteConstructorCall(Constructor, move(Args),
3360 Loc, ConstructorArgs))
3361 return S.ExprError();
3362
3363 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003364 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003365 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003366 move_arg(ConstructorArgs),
3367 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003368 if (CurInit.isInvalid())
3369 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003370
3371 bool Elidable
3372 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3373 if (shouldBindAsTemporary(Entity, Elidable))
3374 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3375
3376 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003377 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003378 break;
3379 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003380
3381 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003382 step_iterator NextStep = Step;
3383 ++NextStep;
3384 if (NextStep != StepEnd &&
3385 NextStep->Kind == SK_ConstructorInitialization) {
3386 // The need for zero-initialization is recorded directly into
3387 // the call to the object's constructor within the next step.
3388 ConstructorInitRequiresZeroInit = true;
3389 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3390 S.getLangOptions().CPlusPlus &&
3391 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003392 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3393 Kind.getRange().getBegin(),
3394 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003395 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003396 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003397 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003398 break;
3399 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003400
3401 case SK_CAssignment: {
3402 QualType SourceType = CurInitExpr->getType();
3403 Sema::AssignConvertType ConvTy =
3404 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003405
3406 // If this is a call, allow conversion to a transparent union.
3407 if (ConvTy != Sema::Compatible &&
3408 Entity.getKind() == InitializedEntity::EK_Parameter &&
3409 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3410 == Sema::Compatible)
3411 ConvTy = Sema::Compatible;
3412
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003413 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3414 Step->Type, SourceType,
3415 CurInitExpr, getAssignmentAction(Entity)))
3416 return S.ExprError();
3417
3418 CurInit.release();
3419 CurInit = S.Owned(CurInitExpr);
3420 break;
3421 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003422
3423 case SK_StringInit: {
3424 QualType Ty = Step->Type;
3425 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3426 break;
3427 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003428 }
3429 }
3430
3431 return move(CurInit);
3432}
3433
3434//===----------------------------------------------------------------------===//
3435// Diagnose initialization failures
3436//===----------------------------------------------------------------------===//
3437bool InitializationSequence::Diagnose(Sema &S,
3438 const InitializedEntity &Entity,
3439 const InitializationKind &Kind,
3440 Expr **Args, unsigned NumArgs) {
3441 if (SequenceKind != FailedSequence)
3442 return false;
3443
Douglas Gregord6542d82009-12-22 15:35:07 +00003444 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003445 switch (Failure) {
3446 case FK_TooManyInitsForReference:
3447 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3448 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3449 break;
3450
3451 case FK_ArrayNeedsInitList:
3452 case FK_ArrayNeedsInitListOrStringLiteral:
3453 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3454 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3455 break;
3456
3457 case FK_AddressOfOverloadFailed:
3458 S.ResolveAddressOfOverloadedFunction(Args[0],
3459 DestType.getNonReferenceType(),
3460 true);
3461 break;
3462
3463 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003464 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003465 switch (FailedOverloadResult) {
3466 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003467 if (Failure == FK_UserConversionOverloadFailed)
3468 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3469 << Args[0]->getType() << DestType
3470 << Args[0]->getSourceRange();
3471 else
3472 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3473 << DestType << Args[0]->getType()
3474 << Args[0]->getSourceRange();
3475
John McCallcbce6062010-01-12 07:18:19 +00003476 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3477 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003478 break;
3479
3480 case OR_No_Viable_Function:
3481 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3482 << Args[0]->getType() << DestType.getNonReferenceType()
3483 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003484 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3485 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003486 break;
3487
3488 case OR_Deleted: {
3489 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3490 << Args[0]->getType() << DestType.getNonReferenceType()
3491 << Args[0]->getSourceRange();
3492 OverloadCandidateSet::iterator Best;
3493 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3494 Kind.getLocation(),
3495 Best);
3496 if (Ovl == OR_Deleted) {
3497 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3498 << Best->Function->isDeleted();
3499 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003500 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003501 }
3502 break;
3503 }
3504
3505 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003506 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003507 break;
3508 }
3509 break;
3510
3511 case FK_NonConstLValueReferenceBindingToTemporary:
3512 case FK_NonConstLValueReferenceBindingToUnrelated:
3513 S.Diag(Kind.getLocation(),
3514 Failure == FK_NonConstLValueReferenceBindingToTemporary
3515 ? diag::err_lvalue_reference_bind_to_temporary
3516 : diag::err_lvalue_reference_bind_to_unrelated)
3517 << DestType.getNonReferenceType()
3518 << Args[0]->getType()
3519 << Args[0]->getSourceRange();
3520 break;
3521
3522 case FK_RValueReferenceBindingToLValue:
3523 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3524 << Args[0]->getSourceRange();
3525 break;
3526
3527 case FK_ReferenceInitDropsQualifiers:
3528 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3529 << DestType.getNonReferenceType()
3530 << Args[0]->getType()
3531 << Args[0]->getSourceRange();
3532 break;
3533
3534 case FK_ReferenceInitFailed:
3535 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3536 << DestType.getNonReferenceType()
3537 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3538 << Args[0]->getType()
3539 << Args[0]->getSourceRange();
3540 break;
3541
3542 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003543 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3544 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 << DestType
3546 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3547 << Args[0]->getType()
3548 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003549 break;
3550
3551 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003552 SourceRange R;
3553
3554 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3555 R = SourceRange(InitList->getInit(1)->getLocStart(),
3556 InitList->getLocEnd());
3557 else
3558 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003559
3560 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003561 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003562 break;
3563 }
3564
3565 case FK_ReferenceBindingToInitList:
3566 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3567 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3568 break;
3569
3570 case FK_InitListBadDestinationType:
3571 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3572 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3573 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003574
3575 case FK_ConstructorOverloadFailed: {
3576 SourceRange ArgsRange;
3577 if (NumArgs)
3578 ArgsRange = SourceRange(Args[0]->getLocStart(),
3579 Args[NumArgs - 1]->getLocEnd());
3580
3581 // FIXME: Using "DestType" for the entity we're printing is probably
3582 // bad.
3583 switch (FailedOverloadResult) {
3584 case OR_Ambiguous:
3585 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3586 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003587 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003588 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003589 break;
3590
3591 case OR_No_Viable_Function:
3592 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3593 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003594 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3595 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003596 break;
3597
3598 case OR_Deleted: {
3599 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3600 << true << DestType << ArgsRange;
3601 OverloadCandidateSet::iterator Best;
3602 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3603 Kind.getLocation(),
3604 Best);
3605 if (Ovl == OR_Deleted) {
3606 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3607 << Best->Function->isDeleted();
3608 } else {
3609 llvm_unreachable("Inconsistent overload resolution?");
3610 }
3611 break;
3612 }
3613
3614 case OR_Success:
3615 llvm_unreachable("Conversion did not fail!");
3616 break;
3617 }
3618 break;
3619 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003620
3621 case FK_DefaultInitOfConst:
3622 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3623 << DestType;
3624 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 }
3626
3627 return true;
3628}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003629
3630//===----------------------------------------------------------------------===//
3631// Initialization helper functions
3632//===----------------------------------------------------------------------===//
3633Sema::OwningExprResult
3634Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3635 SourceLocation EqualLoc,
3636 OwningExprResult Init) {
3637 if (Init.isInvalid())
3638 return ExprError();
3639
3640 Expr *InitE = (Expr *)Init.get();
3641 assert(InitE && "No initialization expression?");
3642
3643 if (EqualLoc.isInvalid())
3644 EqualLoc = InitE->getLocStart();
3645
3646 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3647 EqualLoc);
3648 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3649 Init.release();
3650 return Seq.Perform(*this, Entity, Kind,
3651 MultiExprArg(*this, (void**)&InitE, 1));
3652}