blob: 0cf75464668b40d4c6c2281323334f51f49933d0 [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//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.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
John McCallce6c9b72011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
John McCallce6c9b72011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCallfef8b342011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000090 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000091 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Eli Friedman8718a6a2009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000094
Eli Friedmanbc34b1d2011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Eli Friedman8718a6a2009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000126}
127
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregor9e80f722009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000159namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000236
Douglas Gregord6d37de2009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner8b419b92009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278
Douglas Gregord6d37de2009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000287
John McCall60d7b3a2010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
299 } else if (InitSeq.getKind()
300 == InitializationSequence::ConstructorInitialization) {
301 // Value-initialization requires a constructor call, so
302 // extend the initializer list to include the constructor
303 // call and make a note that we'll need to take another pass
304 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000305 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306 RequiresSecondPass = true;
307 }
308 } else if (InitListExpr *InnerILE
309 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000310 FillInValueInitializations(MemberEntity, InnerILE,
311 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312}
313
Douglas Gregor4c678342009-01-28 21:54:33 +0000314/// Recursively replaces NULL values within the given initializer list
315/// with expressions that perform value-initialization of the
316/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000317void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000318InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE,
320 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000321 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000322 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000323 SourceLocation Loc = ILE->getSourceRange().getBegin();
324 if (ILE->getSyntacticForm())
325 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Ted Kremenek6217b802009-07-29 21:53:49 +0000327 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328 if (RType->getDecl()->isUnion() &&
329 ILE->getInitializedFieldInUnion())
330 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
331 Entity, ILE, RequiresSecondPass);
332 else {
333 unsigned Init = 0;
334 for (RecordDecl::field_iterator
335 Field = RType->getDecl()->field_begin(),
336 FieldEnd = RType->getDecl()->field_end();
337 Field != FieldEnd; ++Field) {
338 if (Field->isUnnamedBitfield())
339 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000340
Douglas Gregord6d37de2009-12-22 00:05:34 +0000341 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000342 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000343
344 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
345 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000347
Douglas Gregord6d37de2009-12-22 00:05:34 +0000348 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000349
Douglas Gregord6d37de2009-12-22 00:05:34 +0000350 // Only look at the first initialization of a union.
351 if (RType->getDecl()->isUnion())
352 break;
353 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000354 }
355
356 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000357 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000358
359 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000361 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000362 unsigned NumInits = ILE->getNumInits();
363 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000364 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000365 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
367 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000368 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000369 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000370 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000371 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000373 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000374 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000376 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000377
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000378
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000380 if (hadError)
381 return;
382
Anders Carlssond3d824d2010-01-23 04:34:47 +0000383 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
384 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000385 ElementEntity.setElementIndex(Init);
386
Douglas Gregor87fd7032009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
John McCall60d7b3a2010-08-24 06:29:42 +0000397 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000398 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000399 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000400 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 return;
402 }
403
404 if (hadError) {
405 // Do nothing
406 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000407 // For arrays, just set the expression used for value-initialization
408 // of the "holes" in the array.
409 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
410 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
411 else
412 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000413 } else {
414 // For arrays, just set the expression used for value-initialization
415 // of the rest of elements and exit.
416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
417 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
418 return;
419 }
420
421 if (InitSeq.getKind()
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422 == InitializationSequence::ConstructorInitialization) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000423 // Value-initialization requires a constructor call, so
424 // extend the initializer list to include the constructor
425 // call and make a note that we'll need to take another pass
426 // through the initializer list.
427 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
428 RequiresSecondPass = true;
429 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000430 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000431 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000432 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
433 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000434 }
435}
436
Chris Lattner68355a52009-01-29 05:10:57 +0000437
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000438InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
439 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000440 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000441 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000442
Eli Friedmanb85f7072008-05-19 19:16:24 +0000443 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000444 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000445 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000446 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000447 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000448 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000449 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000450
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000451 if (!hadError) {
452 bool RequiresSecondPass = false;
453 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000454 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000456 RequiresSecondPass);
457 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000458}
459
460int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000461 // FIXME: use a proper constant
462 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000463 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000464 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000465 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
466 }
467 return maxElements;
468}
469
470int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000471 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000472 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000473 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000474 Field = structDecl->field_begin(),
475 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 Field != FieldEnd; ++Field) {
477 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
478 ++InitializableMembers;
479 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000480 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000481 return std::min(InitializableMembers, 1);
482 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000483}
484
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000485void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000486 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 QualType T, unsigned &Index,
488 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 unsigned &StructuredIndex,
490 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000491 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Steve Naroff0cca7492008-05-01 22:18:59 +0000493 if (T->isArrayType())
494 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000495 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000496 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000497 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000498 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 else
500 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000501
Eli Friedman402256f2008-05-25 13:49:22 +0000502 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000503 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000504 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000505 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000506 hadError = true;
507 return;
508 }
509
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 // Build a structured initializer list corresponding to this subobject.
511 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000512 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
513 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000514 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
515 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000516 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000517
Douglas Gregor4c678342009-01-28 21:54:33 +0000518 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000519 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000520 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000521 /*SubobjectIsDesignatorContext=*/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 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000535
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000536 // Warn about missing braces.
537 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000538 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
539 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000540 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000542 "{")
543 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000545 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000546 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000547}
548
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000549void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000550 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000551 unsigned &Index,
552 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000553 unsigned &StructuredIndex,
554 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000555 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000556 SyntacticToSemantic[IList] = StructuredList;
557 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000559 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000560 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
561 IList->setType(ExprTy);
562 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000563 if (hadError)
564 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000565
Eli Friedman638e1442008-05-25 13:22:35 +0000566 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000568 if (StructuredIndex == 1 &&
569 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000570 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000571 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000572 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000573 hadError = true;
574 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000575 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000577 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000578 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000579 // Don't complain for incomplete types, since we'll get an error
580 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000581 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000582 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000583 CurrentObjectType->isArrayType()? 0 :
584 CurrentObjectType->isVectorType()? 1 :
585 CurrentObjectType->isScalarType()? 2 :
586 CurrentObjectType->isUnionType()? 3 :
587 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000588
589 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000590 if (SemaRef.getLangOptions().CPlusPlus) {
591 DK = diag::err_excess_initializers;
592 hadError = true;
593 }
Nate Begeman08634522009-07-07 21:53:06 +0000594 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
595 DK = diag::err_excess_initializers;
596 hadError = true;
597 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000598
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000600 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000601 }
602 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000603
Eli Friedman759f2522009-05-16 11:45:48 +0000604 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000605 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000606 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000607 << FixItHint::CreateRemoval(IList->getLocStart())
608 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000609}
610
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000611void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000612 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000613 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000614 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000615 unsigned &Index,
616 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000617 unsigned &StructuredIndex,
618 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000619 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000620 CheckScalarType(Entity, IList, DeclType, Index,
621 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000622 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000624 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000625 } else if (DeclType->isAggregateType()) {
626 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000627 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000628 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000629 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000630 StructuredList, StructuredIndex,
631 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000632 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000633 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000634 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000635 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000636 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000637 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000639 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000640 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000641 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
642 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000643 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000644 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000645 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000646 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000647 } else if (DeclType->isRecordType()) {
648 // C++ [dcl.init]p14:
649 // [...] If the class is an aggregate (8.5.1), and the initializer
650 // is a brace-enclosed list, see 8.5.1.
651 //
652 // Note: 8.5.1 is handled below; here, we diagnose the case where
653 // we have an initializer list and a destination type that is not
654 // an aggregate.
655 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000657 << DeclType << IList->getSourceRange();
658 hadError = true;
659 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000660 CheckReferenceType(Entity, IList, DeclType, Index,
661 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000662 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000663 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
664 << DeclType;
665 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000666 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000667 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
668 << DeclType;
669 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000670 }
671}
672
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000673void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000674 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000675 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000676 unsigned &Index,
677 InitListExpr *StructuredList,
678 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000679 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000680 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
681 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000683 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000684 = getStructuredSubobjectInit(IList, Index, ElemType,
685 StructuredList, StructuredIndex,
686 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000687 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000688 newStructuredList, newStructuredIndex);
689 ++StructuredIndex;
690 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000691 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000692 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000693 return CheckScalarType(Entity, IList, ElemType, Index,
694 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000695 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000696 return CheckReferenceType(Entity, IList, ElemType, Index,
697 StructuredList, StructuredIndex);
698 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000699
John McCallfef8b342011-02-21 07:57:55 +0000700 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
701 // arrayType can be incomplete if we're initializing a flexible
702 // array member. There's nothing we can do with the completed
703 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000704
John McCallfef8b342011-02-21 07:57:55 +0000705 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
706 CheckStringInit(Str, ElemType, arrayType, SemaRef);
707 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000708 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000709 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000710 }
John McCallfef8b342011-02-21 07:57:55 +0000711
712 // Fall through for subaggregate initialization.
713
714 } else if (SemaRef.getLangOptions().CPlusPlus) {
715 // C++ [dcl.init.aggr]p12:
716 // All implicit type conversions (clause 4) are considered when
717 // initializing the aggregate member with an ini- tializer from
718 // an initializer-list. If the initializer can initialize a
719 // member, the member is initialized. [...]
720
721 // FIXME: Better EqualLoc?
722 InitializationKind Kind =
723 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
724 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
725
726 if (Seq) {
727 ExprResult Result =
728 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
729 if (Result.isInvalid())
730 hadError = true;
731
732 UpdateStructuredListElement(StructuredList, StructuredIndex,
733 Result.takeAs<Expr>());
734 ++Index;
735 return;
736 }
737
738 // Fall through for subaggregate initialization
739 } else {
740 // C99 6.7.8p13:
741 //
742 // The initializer for a structure or union object that has
743 // automatic storage duration shall be either an initializer
744 // list as described below, or a single expression that has
745 // compatible structure or union type. In the latter case, the
746 // initial value of the object, including unnamed members, is
747 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000748 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000749 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000750 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000751 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000752 if (ExprRes.isInvalid())
753 hadError = true;
754 else {
755 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
756 if (ExprRes.isInvalid())
757 hadError = true;
758 }
759 UpdateStructuredListElement(StructuredList, StructuredIndex,
760 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000761 ++Index;
762 return;
763 }
John Wiegley429bb272011-04-08 18:41:53 +0000764 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000765 // Fall through for subaggregate initialization
766 }
767
768 // C++ [dcl.init.aggr]p12:
769 //
770 // [...] Otherwise, if the member is itself a non-empty
771 // subaggregate, brace elision is assumed and the initializer is
772 // considered for the initialization of the first member of
773 // the subaggregate.
774 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
775 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
776 StructuredIndex);
777 ++StructuredIndex;
778 } else {
779 // We cannot initialize this element, so let
780 // PerformCopyInitialization produce the appropriate diagnostic.
781 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
782 SemaRef.Owned(expr));
783 hadError = true;
784 ++Index;
785 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000786 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000787}
788
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000789void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000790 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000791 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000792 InitListExpr *StructuredList,
793 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000794 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000795 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000796 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000797 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000798 ++Index;
799 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000800 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000801 }
John McCallb934c2d2010-11-11 00:46:36 +0000802
803 Expr *expr = IList->getInit(Index);
804 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
805 SemaRef.Diag(SubIList->getLocStart(),
806 diag::warn_many_braces_around_scalar_init)
807 << SubIList->getSourceRange();
808
809 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
810 StructuredIndex);
811 return;
812 } else if (isa<DesignatedInitExpr>(expr)) {
813 SemaRef.Diag(expr->getSourceRange().getBegin(),
814 diag::err_designator_for_scalar_init)
815 << DeclType << expr->getSourceRange();
816 hadError = true;
817 ++Index;
818 ++StructuredIndex;
819 return;
820 }
821
822 ExprResult Result =
823 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
824 SemaRef.Owned(expr));
825
826 Expr *ResultExpr = 0;
827
828 if (Result.isInvalid())
829 hadError = true; // types weren't compatible.
830 else {
831 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000832
John McCallb934c2d2010-11-11 00:46:36 +0000833 if (ResultExpr != expr) {
834 // The type was promoted, update initializer list.
835 IList->setInit(Index, ResultExpr);
836 }
837 }
838 if (hadError)
839 ++StructuredIndex;
840 else
841 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
842 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000843}
844
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000845void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
846 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000847 unsigned &Index,
848 InitListExpr *StructuredList,
849 unsigned &StructuredIndex) {
850 if (Index < IList->getNumInits()) {
851 Expr *expr = IList->getInit(Index);
852 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000853 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000854 << DeclType << IList->getSourceRange();
855 hadError = true;
856 ++Index;
857 ++StructuredIndex;
858 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000859 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000860
John McCall60d7b3a2010-08-24 06:29:42 +0000861 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000862 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
863 SemaRef.Owned(expr));
864
865 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000867
868 expr = Result.takeAs<Expr>();
869 IList->setInit(Index, expr);
870
Douglas Gregor930d8b52009-01-30 22:09:00 +0000871 if (hadError)
872 ++StructuredIndex;
873 else
874 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
875 ++Index;
876 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000877 // FIXME: It would be wonderful if we could point at the actual member. In
878 // general, it would be useful to pass location information down the stack,
879 // so that we know the location (or decl) of the "current object" being
880 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000881 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000882 diag::err_init_reference_member_uninitialized)
883 << DeclType
884 << IList->getSourceRange();
885 hadError = true;
886 ++Index;
887 ++StructuredIndex;
888 return;
889 }
890}
891
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000892void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000893 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000894 unsigned &Index,
895 InitListExpr *StructuredList,
896 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000897 if (Index >= IList->getNumInits())
898 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
John McCall20e047a2010-10-30 00:11:39 +0000900 const VectorType *VT = DeclType->getAs<VectorType>();
901 unsigned maxElements = VT->getNumElements();
902 unsigned numEltsInit = 0;
903 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000904
John McCall20e047a2010-10-30 00:11:39 +0000905 if (!SemaRef.getLangOptions().OpenCL) {
906 // If the initializing element is a vector, try to copy-initialize
907 // instead of breaking it apart (which is doomed to failure anyway).
908 Expr *Init = IList->getInit(Index);
909 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
910 ExprResult Result =
911 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
912 SemaRef.Owned(Init));
913
914 Expr *ResultExpr = 0;
915 if (Result.isInvalid())
916 hadError = true; // types weren't compatible.
917 else {
918 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000919
John McCall20e047a2010-10-30 00:11:39 +0000920 if (ResultExpr != Init) {
921 // The type was promoted, update initializer list.
922 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000923 }
924 }
John McCall20e047a2010-10-30 00:11:39 +0000925 if (hadError)
926 ++StructuredIndex;
927 else
928 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
929 ++Index;
930 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCall20e047a2010-10-30 00:11:39 +0000933 InitializedEntity ElementEntity =
934 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935
John McCall20e047a2010-10-30 00:11:39 +0000936 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
937 // Don't attempt to go past the end of the init list
938 if (Index >= IList->getNumInits())
939 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000940
John McCall20e047a2010-10-30 00:11:39 +0000941 ElementEntity.setElementIndex(Index);
942 CheckSubElementType(ElementEntity, IList, elementType, Index,
943 StructuredList, StructuredIndex);
944 }
945 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000946 }
John McCall20e047a2010-10-30 00:11:39 +0000947
948 InitializedEntity ElementEntity =
949 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000950
John McCall20e047a2010-10-30 00:11:39 +0000951 // OpenCL initializers allows vectors to be constructed from vectors.
952 for (unsigned i = 0; i < maxElements; ++i) {
953 // Don't attempt to go past the end of the init list
954 if (Index >= IList->getNumInits())
955 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000956
John McCall20e047a2010-10-30 00:11:39 +0000957 ElementEntity.setElementIndex(Index);
958
959 QualType IType = IList->getInit(Index)->getType();
960 if (!IType->isVectorType()) {
961 CheckSubElementType(ElementEntity, IList, elementType, Index,
962 StructuredList, StructuredIndex);
963 ++numEltsInit;
964 } else {
965 QualType VecType;
966 const VectorType *IVT = IType->getAs<VectorType>();
967 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000968
John McCall20e047a2010-10-30 00:11:39 +0000969 if (IType->isExtVectorType())
970 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
971 else
972 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000973 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000974 CheckSubElementType(ElementEntity, IList, VecType, Index,
975 StructuredList, StructuredIndex);
976 numEltsInit += numIElts;
977 }
978 }
979
980 // OpenCL requires all elements to be initialized.
981 if (numEltsInit != maxElements)
982 if (SemaRef.getLangOptions().OpenCL)
983 SemaRef.Diag(IList->getSourceRange().getBegin(),
984 diag::err_vector_incorrect_num_initializers)
985 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000986}
987
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000988void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000989 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000990 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000991 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000992 unsigned &Index,
993 InitListExpr *StructuredList,
994 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +0000995 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
996
Steve Naroff0cca7492008-05-01 22:18:59 +0000997 // Check for the special-case of initializing an array with a string.
998 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +0000999 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001000 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001001 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001002 // We place the string literal directly into the resulting
1003 // initializer list. This is the only place where the structure
1004 // of the structured initializer list doesn't match exactly,
1005 // because doing so would involve allocating one character
1006 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001007 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001008 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001009 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001010 return;
1011 }
1012 }
John McCallce6c9b72011-02-21 07:22:22 +00001013 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001014 // Check for VLAs; in standard C it would be possible to check this
1015 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1016 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001017 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001018 diag::err_variable_object_no_init)
1019 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001020 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001021 ++Index;
1022 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001023 return;
1024 }
1025
Douglas Gregor05c13a32009-01-22 00:58:24 +00001026 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001027 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1028 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001029 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001030 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001031 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001032 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001033 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001034 maxElementsKnown = true;
1035 }
1036
John McCallce6c9b72011-02-21 07:22:22 +00001037 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001038 while (Index < IList->getNumInits()) {
1039 Expr *Init = IList->getInit(Index);
1040 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001041 // If we're not the subobject that matches up with the '{' for
1042 // the designator, we shouldn't be handling the
1043 // designator. Return immediately.
1044 if (!SubobjectIsDesignatorContext)
1045 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001046
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001047 // Handle this designated initializer. elementIndex will be
1048 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001049 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001050 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001051 StructuredList, StructuredIndex, true,
1052 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001053 hadError = true;
1054 continue;
1055 }
1056
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001057 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001058 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001059 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001060 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001061 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001062
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001063 // If the array is of incomplete type, keep track of the number of
1064 // elements in the initializer.
1065 if (!maxElementsKnown && elementIndex > maxElements)
1066 maxElements = elementIndex;
1067
Douglas Gregor05c13a32009-01-22 00:58:24 +00001068 continue;
1069 }
1070
1071 // If we know the maximum number of elements, and we've already
1072 // hit it, stop consuming elements in the initializer list.
1073 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001074 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001075
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001076 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001078 Entity);
1079 // Check this element.
1080 CheckSubElementType(ElementEntity, IList, elementType, Index,
1081 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001082 ++elementIndex;
1083
1084 // If the array is of incomplete type, keep track of the number of
1085 // elements in the initializer.
1086 if (!maxElementsKnown && elementIndex > maxElements)
1087 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001089 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001090 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001091 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001092 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001093 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001094 // Sizing an array implicitly to zero is not allowed by ISO C,
1095 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001096 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001097 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001098 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001099
Mike Stump1eb44332009-09-09 15:08:12 +00001100 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001101 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
1103}
1104
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001105void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001106 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001107 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001108 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001109 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001110 unsigned &Index,
1111 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001112 unsigned &StructuredIndex,
1113 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001114 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Eli Friedmanb85f7072008-05-19 19:16:24 +00001116 // If the record is invalid, some of it's members are invalid. To avoid
1117 // confusion, we forgo checking the intializer for the entire record.
1118 if (structDecl->isInvalidDecl()) {
1119 hadError = true;
1120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001121 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001122
1123 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1124 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001125 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001126 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001127 Field != FieldEnd; ++Field) {
1128 if (Field->getDeclName()) {
1129 StructuredList->setInitializedFieldInUnion(*Field);
1130 break;
1131 }
1132 }
1133 return;
1134 }
1135
Douglas Gregor05c13a32009-01-22 00:58:24 +00001136 // If structDecl is a forward declaration, this loop won't do
1137 // anything except look at designated initializers; That's okay,
1138 // because an error should get printed out elsewhere. It might be
1139 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001141 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001142 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001143 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001144 while (Index < IList->getNumInits()) {
1145 Expr *Init = IList->getInit(Index);
1146
1147 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001148 // If we're not the subobject that matches up with the '{' for
1149 // the designator, we shouldn't be handling the
1150 // designator. Return immediately.
1151 if (!SubobjectIsDesignatorContext)
1152 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001153
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001154 // Handle this designated initializer. Field will be updated to
1155 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001156 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001157 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001158 StructuredList, StructuredIndex,
1159 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001160 hadError = true;
1161
Douglas Gregordfb5e592009-02-12 19:00:39 +00001162 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001163
1164 // Disable check for missing fields when designators are used.
1165 // This matches gcc behaviour.
1166 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167 continue;
1168 }
1169
1170 if (Field == FieldEnd) {
1171 // We've run out of fields. We're done.
1172 break;
1173 }
1174
Douglas Gregordfb5e592009-02-12 19:00:39 +00001175 // We've already initialized a member of a union. We're done.
1176 if (InitializedSomething && DeclType->isUnionType())
1177 break;
1178
Douglas Gregor44b43212008-12-11 16:49:14 +00001179 // If we've hit the flexible array member at the end, we're done.
1180 if (Field->getType()->isIncompleteArrayType())
1181 break;
1182
Douglas Gregor0bb76892009-01-29 16:53:55 +00001183 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001184 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001185 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001186 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001187 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001188
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001189 InitializedEntity MemberEntity =
1190 InitializedEntity::InitializeMember(*Field, &Entity);
1191 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1192 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001193 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001194
1195 if (DeclType->isUnionType()) {
1196 // Initialize the first field within the union.
1197 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001198 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199
1200 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001201 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001202
John McCall80639de2010-03-11 19:32:38 +00001203 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001205 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1206 // It is possible we have one or more unnamed bitfields remaining.
1207 // Find first (if any) named field and emit warning.
1208 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1209 it != end; ++it) {
1210 if (!it->isUnnamedBitfield()) {
1211 SemaRef.Diag(IList->getSourceRange().getEnd(),
1212 diag::warn_missing_field_initializers) << it->getName();
1213 break;
1214 }
1215 }
1216 }
1217
Mike Stump1eb44332009-09-09 15:08:12 +00001218 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001219 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001220 return;
1221
1222 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001223 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001224 (!isa<InitListExpr>(IList->getInit(Index)) ||
1225 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001226 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001227 diag::err_flexible_array_init_nonempty)
1228 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001229 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001230 << *Field;
1231 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001232 ++Index;
1233 return;
1234 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001235 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001236 diag::ext_flexible_array_init)
1237 << IList->getInit(Index)->getSourceRange().getBegin();
1238 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1239 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001240 }
1241
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001242 InitializedEntity MemberEntity =
1243 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001245 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001246 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001247 StructuredList, StructuredIndex);
1248 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001250 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001251}
Steve Naroff0cca7492008-05-01 22:18:59 +00001252
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001253/// \brief Expand a field designator that refers to a member of an
1254/// anonymous struct or union into a series of field designators that
1255/// refers to the field within the appropriate subobject.
1256///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001257static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001258 DesignatedInitExpr *DIE,
1259 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001260 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001261 typedef DesignatedInitExpr::Designator Designator;
1262
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001263 // Build the replacement designators.
1264 llvm::SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001265 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1266 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1267 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001268 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001269 DIE->getDesignator(DesigIdx)->getDotLoc(),
1270 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1271 else
1272 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1273 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001274 assert(isa<FieldDecl>(*PI));
1275 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001276 }
1277
1278 // Expand the current designator into the set of replacement
1279 // designators, so we have a full subobject path down to where the
1280 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001281 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001282 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001283}
Mike Stump1eb44332009-09-09 15:08:12 +00001284
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001286/// corresponds to FieldName.
1287static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1288 IdentifierInfo *FieldName) {
1289 assert(AnonField->isAnonymousStructOrUnion());
1290 Decl *NextDecl = AnonField->getNextDeclInContext();
1291 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1292 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1293 return IF;
1294 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001295 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001296 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001297}
1298
Douglas Gregor05c13a32009-01-22 00:58:24 +00001299/// @brief Check the well-formedness of a C99 designated initializer.
1300///
1301/// Determines whether the designated initializer @p DIE, which
1302/// resides at the given @p Index within the initializer list @p
1303/// IList, is well-formed for a current object of type @p DeclType
1304/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001305/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001306/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001307///
1308/// @param IList The initializer list in which this designated
1309/// initializer occurs.
1310///
Douglas Gregor71199712009-04-15 04:56:10 +00001311/// @param DIE The designated initializer expression.
1312///
1313/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001314///
1315/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1316/// into which the designation in @p DIE should refer.
1317///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318/// @param NextField If non-NULL and the first designator in @p DIE is
1319/// a field, this will be set to the field declaration corresponding
1320/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001321///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001322/// @param NextElementIndex If non-NULL and the first designator in @p
1323/// DIE is an array designator or GNU array-range designator, this
1324/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001325///
1326/// @param Index Index into @p IList where the designated initializer
1327/// @p DIE occurs.
1328///
Douglas Gregor4c678342009-01-28 21:54:33 +00001329/// @param StructuredList The initializer list expression that
1330/// describes all of the subobject initializers in the order they'll
1331/// actually be initialized.
1332///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001333/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001334bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001335InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001336 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001337 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001338 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 QualType &CurrentObjectType,
1340 RecordDecl::field_iterator *NextField,
1341 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001342 unsigned &Index,
1343 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001344 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001345 bool FinishSubobjectInit,
1346 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001347 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001348 // Check the actual initialization for the designated object type.
1349 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001350
1351 // Temporarily remove the designator expression from the
1352 // initializer list that the child calls see, so that we don't try
1353 // to re-process the designator.
1354 unsigned OldIndex = Index;
1355 IList->setInit(OldIndex, DIE->getInit());
1356
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001357 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001358 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001359
1360 // Restore the designated initializer expression in the syntactic
1361 // form of the initializer list.
1362 if (IList->getInit(OldIndex) != DIE->getInit())
1363 DIE->setInit(IList->getInit(OldIndex));
1364 IList->setInit(OldIndex, DIE);
1365
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001366 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001367 }
1368
Douglas Gregor71199712009-04-15 04:56:10 +00001369 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001370 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001371 "Need a non-designated initializer list to start from");
1372
Douglas Gregor71199712009-04-15 04:56:10 +00001373 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001374 // Determine the structural initializer list that corresponds to the
1375 // current subobject.
1376 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001377 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001378 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 SourceRange(D->getStartLocation(),
1380 DIE->getSourceRange().getEnd()));
1381 assert(StructuredList && "Expected a structured initializer list");
1382
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001383 if (D->isFieldDesignator()) {
1384 // C99 6.7.8p7:
1385 //
1386 // If a designator has the form
1387 //
1388 // . identifier
1389 //
1390 // then the current object (defined below) shall have
1391 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001392 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001393 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001394 if (!RT) {
1395 SourceLocation Loc = D->getDotLoc();
1396 if (Loc.isInvalid())
1397 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001398 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1399 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 ++Index;
1401 return true;
1402 }
1403
Douglas Gregor4c678342009-01-28 21:54:33 +00001404 // Note: we perform a linear search of the fields here, despite
1405 // the fact that we have a faster lookup method, because we always
1406 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001407 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001408 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001409 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001410 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001411 Field = RT->getDecl()->field_begin(),
1412 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001413 for (; Field != FieldEnd; ++Field) {
1414 if (Field->isUnnamedBitfield())
1415 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001416
Francois Picheta0e27f02010-12-22 03:46:10 +00001417 // If we find a field representing an anonymous field, look in the
1418 // IndirectFieldDecl that follow for the designated initializer.
1419 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1420 if (IndirectFieldDecl *IF =
1421 FindIndirectFieldDesignator(*Field, FieldName)) {
1422 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1423 D = DIE->getDesignator(DesigIdx);
1424 break;
1425 }
1426 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001427 if (KnownField && KnownField == *Field)
1428 break;
1429 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 break;
1431
1432 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001433 }
1434
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001436 // There was no normal field in the struct with the designated
1437 // name. Perform another lookup for this name, which may find
1438 // something that we can't designate (e.g., a member function),
1439 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001440 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001441 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001442 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001443 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001444 // Name lookup didn't find anything. Determine whether this
1445 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001447 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001448 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001450 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001451 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001452 ->Equals(RT->getDecl())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001454 diag::err_field_designator_unknown_suggest)
1455 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001456 << FixItHint::CreateReplacement(D->getFieldLoc(),
1457 R.getLookupName().getAsString());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001459 diag::note_previous_decl)
1460 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001461 } else {
1462 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1463 << FieldName << CurrentObjectType;
1464 ++Index;
1465 return true;
1466 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001469 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001470 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001471 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001472 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001473 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001474 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001475 ++Index;
1476 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001477 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001478
Francois Picheta0e27f02010-12-22 03:46:10 +00001479 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001480 // The replacement field comes from typo correction; find it
1481 // in the list of fields.
1482 FieldIndex = 0;
1483 Field = RT->getDecl()->field_begin();
1484 for (; Field != FieldEnd; ++Field) {
1485 if (Field->isUnnamedBitfield())
1486 continue;
1487
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001489 Field->getIdentifier() == ReplacementField->getIdentifier())
1490 break;
1491
1492 ++FieldIndex;
1493 }
1494 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001495 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001496
1497 // All of the fields of a union are located at the same place in
1498 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001499 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001500 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001501 StructuredList->setInitializedFieldInUnion(*Field);
1502 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001503
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001504 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001505 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor4c678342009-01-28 21:54:33 +00001507 // Make sure that our non-designated initializer list has space
1508 // for a subobject corresponding to this field.
1509 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001510 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001511
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001512 // This designator names a flexible array member.
1513 if (Field->getType()->isIncompleteArrayType()) {
1514 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001515 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001516 // We can't designate an object within the flexible array
1517 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001518 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001519 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001520 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001522 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001523 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001524 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001525 << *Field;
1526 Invalid = true;
1527 }
1528
Chris Lattner9046c222010-10-10 17:49:49 +00001529 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1530 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001531 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001532 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001533 diag::err_flexible_array_init_needs_braces)
1534 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001535 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001536 << *Field;
1537 Invalid = true;
1538 }
1539
1540 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001541 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001542 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001543 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001544 diag::err_flexible_array_init_nonempty)
1545 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001546 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001547 << *Field;
1548 Invalid = true;
1549 }
1550
1551 if (Invalid) {
1552 ++Index;
1553 return true;
1554 }
1555
1556 // Initialize the array.
1557 bool prevHadError = hadError;
1558 unsigned newStructuredIndex = FieldIndex;
1559 unsigned OldIndex = Index;
1560 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001561
1562 InitializedEntity MemberEntity =
1563 InitializedEntity::InitializeMember(*Field, &Entity);
1564 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001565 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001566
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001567 IList->setInit(OldIndex, DIE);
1568 if (hadError && !prevHadError) {
1569 ++Field;
1570 ++FieldIndex;
1571 if (NextField)
1572 *NextField = Field;
1573 StructuredIndex = FieldIndex;
1574 return true;
1575 }
1576 } else {
1577 // Recurse to check later designated subobjects.
1578 QualType FieldType = (*Field)->getType();
1579 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001581 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001582 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001583 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1584 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001585 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001586 true, false))
1587 return true;
1588 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589
1590 // Find the position of the next field to be initialized in this
1591 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001593 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001594
1595 // If this the first designator, our caller will continue checking
1596 // the rest of this struct/class/union subobject.
1597 if (IsFirstDesignator) {
1598 if (NextField)
1599 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001600 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001601 return false;
1602 }
1603
Douglas Gregor34e79462009-01-28 23:36:17 +00001604 if (!FinishSubobjectInit)
1605 return false;
1606
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001607 // We've already initialized something in the union; we're done.
1608 if (RT->getDecl()->isUnion())
1609 return hadError;
1610
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611 // Check the remaining fields within this class/struct/union subobject.
1612 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001613
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001614 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001615 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616 return hadError && !prevHadError;
1617 }
1618
1619 // C99 6.7.8p6:
1620 //
1621 // If a designator has the form
1622 //
1623 // [ constant-expression ]
1624 //
1625 // then the current object (defined below) shall have array
1626 // type and the expression shall be an integer constant
1627 // expression. If the array is of unknown size, any
1628 // nonnegative value is valid.
1629 //
1630 // Additionally, cope with the GNU extension that permits
1631 // designators of the form
1632 //
1633 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001634 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001635 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001636 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001637 << CurrentObjectType;
1638 ++Index;
1639 return true;
1640 }
1641
1642 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001643 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1644 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001646 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001647 DesignatedEndIndex = DesignatedStartIndex;
1648 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001650
Mike Stump1eb44332009-09-09 15:08:12 +00001651 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001652 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001653 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001654 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001655 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001656
Chris Lattnere0fd8322011-02-19 22:28:58 +00001657 // Codegen can't handle evaluating array range designators that have side
1658 // effects, because we replicate the AST value for each initialized element.
1659 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1660 // elements with something that has a side effect, so codegen can emit an
1661 // "error unsupported" error instead of miscompiling the app.
1662 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1663 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001664 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001665 }
1666
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001667 if (isa<ConstantArrayType>(AT)) {
1668 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001669 DesignatedStartIndex
1670 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001671 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001672 DesignatedEndIndex
1673 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001674 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1675 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001676 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001677 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001678 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001679 << IndexExpr->getSourceRange();
1680 ++Index;
1681 return true;
1682 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001683 } else {
1684 // Make sure the bit-widths and signedness match.
1685 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001686 DesignatedEndIndex
1687 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001688 else if (DesignatedStartIndex.getBitWidth() <
1689 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001690 DesignatedStartIndex
1691 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001692 DesignatedStartIndex.setIsUnsigned(true);
1693 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Douglas Gregor4c678342009-01-28 21:54:33 +00001696 // Make sure that our non-designated initializer list has space
1697 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001698 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001699 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001700 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001701
Douglas Gregor34e79462009-01-28 23:36:17 +00001702 // Repeatedly perform subobject initializations in the range
1703 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001704
Douglas Gregor34e79462009-01-28 23:36:17 +00001705 // Move to the next designator
1706 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1707 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001709 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001710 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001711
Douglas Gregor34e79462009-01-28 23:36:17 +00001712 while (DesignatedStartIndex <= DesignatedEndIndex) {
1713 // Recurse to check later designated subobjects.
1714 QualType ElementType = AT->getElementType();
1715 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001717 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001718 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1719 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001720 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001721 (DesignatedStartIndex == DesignatedEndIndex),
1722 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001723 return true;
1724
1725 // Move to the next index in the array that we'll be initializing.
1726 ++DesignatedStartIndex;
1727 ElementIndex = DesignatedStartIndex.getZExtValue();
1728 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001729
1730 // If this the first designator, our caller will continue checking
1731 // the rest of this array subobject.
1732 if (IsFirstDesignator) {
1733 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001734 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001735 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001736 return false;
1737 }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Douglas Gregor34e79462009-01-28 23:36:17 +00001739 if (!FinishSubobjectInit)
1740 return false;
1741
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001742 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001743 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001745 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001746 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001747 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001748}
1749
Douglas Gregor4c678342009-01-28 21:54:33 +00001750// Get the structured initializer list for a subobject of type
1751// @p CurrentObjectType.
1752InitListExpr *
1753InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1754 QualType CurrentObjectType,
1755 InitListExpr *StructuredList,
1756 unsigned StructuredIndex,
1757 SourceRange InitRange) {
1758 Expr *ExistingInit = 0;
1759 if (!StructuredList)
1760 ExistingInit = SyntacticToSemantic[IList];
1761 else if (StructuredIndex < StructuredList->getNumInits())
1762 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Douglas Gregor4c678342009-01-28 21:54:33 +00001764 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1765 return Result;
1766
1767 if (ExistingInit) {
1768 // We are creating an initializer list that initializes the
1769 // subobjects of the current object, but there was already an
1770 // initialization that completely initialized the current
1771 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001772 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001773 // struct X { int a, b; };
1774 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001775 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001776 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1777 // designated initializer re-initializes the whole
1778 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001780 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001782 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001783 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001784 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001785 << ExistingInit->getSourceRange();
1786 }
1787
Mike Stump1eb44332009-09-09 15:08:12 +00001788 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001789 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1790 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001791 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001792
Douglas Gregor63982352010-07-13 18:40:04 +00001793 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001794
Douglas Gregorfa219202009-03-20 23:58:33 +00001795 // Pre-allocate storage for the structured initializer list.
1796 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001797 unsigned NumInits = 0;
1798 if (!StructuredList)
1799 NumInits = IList->getNumInits();
1800 else if (Index < IList->getNumInits()) {
1801 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1802 NumInits = SubList->getNumInits();
1803 }
1804
Mike Stump1eb44332009-09-09 15:08:12 +00001805 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001806 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1807 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1808 NumElements = CAType->getSize().getZExtValue();
1809 // Simple heuristic so that we don't allocate a very large
1810 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001811 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001812 NumElements = 0;
1813 }
John McCall183700f2009-09-21 23:43:11 +00001814 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001815 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001816 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001817 RecordDecl *RDecl = RType->getDecl();
1818 if (RDecl->isUnion())
1819 NumElements = 1;
1820 else
Mike Stump1eb44332009-09-09 15:08:12 +00001821 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001822 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001823 }
1824
Douglas Gregor08457732009-03-21 18:13:52 +00001825 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001826 NumElements = IList->getNumInits();
1827
Ted Kremenek709210f2010-04-13 23:39:13 +00001828 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001829
Douglas Gregor4c678342009-01-28 21:54:33 +00001830 // Link this new initializer list into the structured initializer
1831 // lists.
1832 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001833 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001834 else {
1835 Result->setSyntacticForm(IList);
1836 SyntacticToSemantic[IList] = Result;
1837 }
1838
1839 return Result;
1840}
1841
1842/// Update the initializer at index @p StructuredIndex within the
1843/// structured initializer list to the value @p expr.
1844void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1845 unsigned &StructuredIndex,
1846 Expr *expr) {
1847 // No structured initializer list to update
1848 if (!StructuredList)
1849 return;
1850
Ted Kremenek709210f2010-04-13 23:39:13 +00001851 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1852 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001853 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001854 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001855 diag::warn_initializer_overrides)
1856 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001857 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001858 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001859 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001860 << PrevInit->getSourceRange();
1861 }
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor4c678342009-01-28 21:54:33 +00001863 ++StructuredIndex;
1864}
1865
Douglas Gregor05c13a32009-01-22 00:58:24 +00001866/// Check that the given Index expression is a valid array designator
1867/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001868/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001869/// and produces a reasonable diagnostic if there is a
1870/// failure. Returns true if there was an error, false otherwise. If
1871/// everything went okay, Value will receive the value of the constant
1872/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001873static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001874CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001875 SourceLocation Loc = Index->getSourceRange().getBegin();
1876
1877 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001878 if (S.VerifyIntegerConstantExpression(Index, &Value))
1879 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001880
Chris Lattner3bf68932009-04-25 21:59:05 +00001881 if (Value.isSigned() && Value.isNegative())
1882 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001883 << Value.toString(10) << Index->getSourceRange();
1884
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001885 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001886 return false;
1887}
1888
John McCall60d7b3a2010-08-24 06:29:42 +00001889ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001890 SourceLocation Loc,
1891 bool GNUSyntax,
1892 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001893 typedef DesignatedInitExpr::Designator ASTDesignator;
1894
1895 bool Invalid = false;
1896 llvm::SmallVector<ASTDesignator, 32> Designators;
1897 llvm::SmallVector<Expr *, 32> InitExpressions;
1898
1899 // Build designators and check array designator expressions.
1900 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1901 const Designator &D = Desig.getDesignator(Idx);
1902 switch (D.getKind()) {
1903 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001904 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001905 D.getFieldLoc()));
1906 break;
1907
1908 case Designator::ArrayDesignator: {
1909 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1910 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001911 if (!Index->isTypeDependent() &&
1912 !Index->isValueDependent() &&
1913 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001914 Invalid = true;
1915 else {
1916 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001917 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001918 D.getRBracketLoc()));
1919 InitExpressions.push_back(Index);
1920 }
1921 break;
1922 }
1923
1924 case Designator::ArrayRangeDesignator: {
1925 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1926 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1927 llvm::APSInt StartValue;
1928 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001929 bool StartDependent = StartIndex->isTypeDependent() ||
1930 StartIndex->isValueDependent();
1931 bool EndDependent = EndIndex->isTypeDependent() ||
1932 EndIndex->isValueDependent();
1933 if ((!StartDependent &&
1934 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1935 (!EndDependent &&
1936 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001937 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001938 else {
1939 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001940 if (StartDependent || EndDependent) {
1941 // Nothing to compute.
1942 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001943 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001944 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001945 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001946
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001947 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001948 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001949 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001950 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1951 Invalid = true;
1952 } else {
1953 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001954 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001955 D.getEllipsisLoc(),
1956 D.getRBracketLoc()));
1957 InitExpressions.push_back(StartIndex);
1958 InitExpressions.push_back(EndIndex);
1959 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001960 }
1961 break;
1962 }
1963 }
1964 }
1965
1966 if (Invalid || Init.isInvalid())
1967 return ExprError();
1968
1969 // Clear out the expressions within the designation.
1970 Desig.ClearExprs(*this);
1971
1972 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001973 = DesignatedInitExpr::Create(Context,
1974 Designators.data(), Designators.size(),
1975 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001976 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001977
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001978 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00001979 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
1980 << DIE->getSourceRange();
1981 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001982 Diag(DIE->getLocStart(), diag::ext_designated_init)
1983 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001984
Douglas Gregor05c13a32009-01-22 00:58:24 +00001985 return Owned(DIE);
1986}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001987
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001988bool Sema::CheckInitList(const InitializedEntity &Entity,
1989 InitListExpr *&InitList, QualType &DeclType) {
1990 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001991 if (!CheckInitList.HadError())
1992 InitList = CheckInitList.getFullyStructuredList();
1993
1994 return CheckInitList.HadError();
1995}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001996
Douglas Gregor20093b42009-12-09 23:02:17 +00001997//===----------------------------------------------------------------------===//
1998// Initialization entity
1999//===----------------------------------------------------------------------===//
2000
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002001InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002002 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002003 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002004{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002005 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2006 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002007 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002008 } else {
2009 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002010 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002011 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002012}
2013
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002015 CXXBaseSpecifier *Base,
2016 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002017{
2018 InitializedEntity Result;
2019 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002020 Result.Base = reinterpret_cast<uintptr_t>(Base);
2021 if (IsInheritedVirtualBase)
2022 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002023
Douglas Gregord6542d82009-12-22 15:35:07 +00002024 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002025 return Result;
2026}
2027
Douglas Gregor99a2e602009-12-16 01:38:02 +00002028DeclarationName InitializedEntity::getName() const {
2029 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002030 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00002031 if (!VariableOrMember)
2032 return DeclarationName();
2033 // Fall through
2034
2035 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002036 case EK_Member:
2037 return VariableOrMember->getDeclName();
2038
2039 case EK_Result:
2040 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002041 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002042 case EK_Temporary:
2043 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002044 case EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002045 case EK_ArrayElement:
2046 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002047 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002048 return DeclarationName();
2049 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050
Douglas Gregor99a2e602009-12-16 01:38:02 +00002051 // Silence GCC warning
2052 return DeclarationName();
2053}
2054
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002055DeclaratorDecl *InitializedEntity::getDecl() const {
2056 switch (getKind()) {
2057 case EK_Variable:
2058 case EK_Parameter:
2059 case EK_Member:
2060 return VariableOrMember;
2061
2062 case EK_Result:
2063 case EK_Exception:
2064 case EK_New:
2065 case EK_Temporary:
2066 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002067 case EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002068 case EK_ArrayElement:
2069 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002070 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002071 return 0;
2072 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002073
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002074 // Silence GCC warning
2075 return 0;
2076}
2077
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002078bool InitializedEntity::allowsNRVO() const {
2079 switch (getKind()) {
2080 case EK_Result:
2081 case EK_Exception:
2082 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002084 case EK_Variable:
2085 case EK_Parameter:
2086 case EK_Member:
2087 case EK_New:
2088 case EK_Temporary:
2089 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002090 case EK_Delegation:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002091 case EK_ArrayElement:
2092 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002093 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002094 break;
2095 }
2096
2097 return false;
2098}
2099
Douglas Gregor20093b42009-12-09 23:02:17 +00002100//===----------------------------------------------------------------------===//
2101// Initialization sequence
2102//===----------------------------------------------------------------------===//
2103
2104void InitializationSequence::Step::Destroy() {
2105 switch (Kind) {
2106 case SK_ResolveAddressOfOverloadedFunction:
2107 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002108 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002109 case SK_CastDerivedToBaseLValue:
2110 case SK_BindReference:
2111 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002112 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002113 case SK_UserConversion:
2114 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002115 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002116 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002117 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002118 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002119 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002120 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002121 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002122 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002123 case SK_ArrayInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002124 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Douglas Gregor20093b42009-12-09 23:02:17 +00002126 case SK_ConversionSequence:
2127 delete ICS;
2128 }
2129}
2130
Douglas Gregorb70cf442010-03-26 20:14:36 +00002131bool InitializationSequence::isDirectReferenceBinding() const {
2132 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2133}
2134
2135bool InitializationSequence::isAmbiguous() const {
2136 if (getKind() != FailedSequence)
2137 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138
Douglas Gregorb70cf442010-03-26 20:14:36 +00002139 switch (getFailureKind()) {
2140 case FK_TooManyInitsForReference:
2141 case FK_ArrayNeedsInitList:
2142 case FK_ArrayNeedsInitListOrStringLiteral:
2143 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2144 case FK_NonConstLValueReferenceBindingToTemporary:
2145 case FK_NonConstLValueReferenceBindingToUnrelated:
2146 case FK_RValueReferenceBindingToLValue:
2147 case FK_ReferenceInitDropsQualifiers:
2148 case FK_ReferenceInitFailed:
2149 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002150 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002151 case FK_TooManyInitsForScalar:
2152 case FK_ReferenceBindingToInitList:
2153 case FK_InitListBadDestinationType:
2154 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002155 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002156 case FK_ArrayTypeMismatch:
2157 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002158 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159
Douglas Gregorb70cf442010-03-26 20:14:36 +00002160 case FK_ReferenceInitOverloadFailed:
2161 case FK_UserConversionOverloadFailed:
2162 case FK_ConstructorOverloadFailed:
2163 return FailedOverloadResult == OR_Ambiguous;
2164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002165
Douglas Gregorb70cf442010-03-26 20:14:36 +00002166 return false;
2167}
2168
Douglas Gregord6e44a32010-04-16 22:09:46 +00002169bool InitializationSequence::isConstructorInitialization() const {
2170 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2171}
2172
Douglas Gregor20093b42009-12-09 23:02:17 +00002173void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002174 FunctionDecl *Function,
2175 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002176 Step S;
2177 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2178 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002179 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002180 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002181 Steps.push_back(S);
2182}
2183
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002184void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002185 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002186 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002187 switch (VK) {
2188 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2189 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2190 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002191 default: llvm_unreachable("No such category");
2192 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002193 S.Type = BaseType;
2194 Steps.push_back(S);
2195}
2196
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002198 bool BindingTemporary) {
2199 Step S;
2200 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2201 S.Type = T;
2202 Steps.push_back(S);
2203}
2204
Douglas Gregor523d46a2010-04-18 07:40:54 +00002205void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2206 Step S;
2207 S.Kind = SK_ExtraneousCopyToTemporary;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
Eli Friedman03981012009-12-11 02:42:07 +00002212void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002213 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002214 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002215 Step S;
2216 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002217 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002218 S.Function.Function = Function;
2219 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002220 Steps.push_back(S);
2221}
2222
2223void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002224 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002225 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002226 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002227 switch (VK) {
2228 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002229 S.Kind = SK_QualificationConversionRValue;
2230 break;
John McCall5baba9d2010-08-25 10:28:54 +00002231 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002232 S.Kind = SK_QualificationConversionXValue;
2233 break;
John McCall5baba9d2010-08-25 10:28:54 +00002234 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002235 S.Kind = SK_QualificationConversionLValue;
2236 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002237 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002238 S.Type = Ty;
2239 Steps.push_back(S);
2240}
2241
2242void InitializationSequence::AddConversionSequenceStep(
2243 const ImplicitConversionSequence &ICS,
2244 QualType T) {
2245 Step S;
2246 S.Kind = SK_ConversionSequence;
2247 S.Type = T;
2248 S.ICS = new ImplicitConversionSequence(ICS);
2249 Steps.push_back(S);
2250}
2251
Douglas Gregord87b61f2009-12-10 17:56:55 +00002252void InitializationSequence::AddListInitializationStep(QualType T) {
2253 Step S;
2254 S.Kind = SK_ListInitialization;
2255 S.Type = T;
2256 Steps.push_back(S);
2257}
2258
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002260InitializationSequence::AddConstructorInitializationStep(
2261 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002262 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002263 QualType T) {
2264 Step S;
2265 S.Kind = SK_ConstructorInitialization;
2266 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002267 S.Function.Function = Constructor;
2268 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002269 Steps.push_back(S);
2270}
2271
Douglas Gregor71d17402009-12-15 00:01:57 +00002272void InitializationSequence::AddZeroInitializationStep(QualType T) {
2273 Step S;
2274 S.Kind = SK_ZeroInitialization;
2275 S.Type = T;
2276 Steps.push_back(S);
2277}
2278
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002279void InitializationSequence::AddCAssignmentStep(QualType T) {
2280 Step S;
2281 S.Kind = SK_CAssignment;
2282 S.Type = T;
2283 Steps.push_back(S);
2284}
2285
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002286void InitializationSequence::AddStringInitStep(QualType T) {
2287 Step S;
2288 S.Kind = SK_StringInit;
2289 S.Type = T;
2290 Steps.push_back(S);
2291}
2292
Douglas Gregor569c3162010-08-07 11:51:51 +00002293void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2294 Step S;
2295 S.Kind = SK_ObjCObjectConversion;
2296 S.Type = T;
2297 Steps.push_back(S);
2298}
2299
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002300void InitializationSequence::AddArrayInitStep(QualType T) {
2301 Step S;
2302 S.Kind = SK_ArrayInit;
2303 S.Type = T;
2304 Steps.push_back(S);
2305}
2306
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002307void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002308 OverloadingResult Result) {
2309 SequenceKind = FailedSequence;
2310 this->Failure = Failure;
2311 this->FailedOverloadResult = Result;
2312}
2313
2314//===----------------------------------------------------------------------===//
2315// Attempt initialization
2316//===----------------------------------------------------------------------===//
2317
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002318/// \brief Attempt list initialization (C++0x [dcl.init.list])
2319static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002320 const InitializedEntity &Entity,
2321 const InitializationKind &Kind,
2322 InitListExpr *InitList,
2323 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002324 // FIXME: We only perform rudimentary checking of list
2325 // initializations at this point, then assume that any list
2326 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002327 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002328 // do all of the necessary checking. C++0x initializer lists will
2329 // force us to perform more checking here.
2330 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2331
Douglas Gregord6542d82009-12-22 15:35:07 +00002332 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002333
2334 // C++ [dcl.init]p13:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335 // If T is a scalar type, then a declaration of the form
Douglas Gregord87b61f2009-12-10 17:56:55 +00002336 //
2337 // T x = { a };
2338 //
2339 // is equivalent to
2340 //
2341 // T x = a;
2342 if (DestType->isScalarType()) {
2343 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2344 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2345 return;
2346 }
2347
2348 // Assume scalar initialization from a single value works.
2349 } else if (DestType->isAggregateType()) {
2350 // Assume aggregate initialization works.
2351 } else if (DestType->isVectorType()) {
2352 // Assume vector initialization works.
2353 } else if (DestType->isReferenceType()) {
2354 // FIXME: C++0x defines behavior for this.
2355 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2356 return;
2357 } else if (DestType->isRecordType()) {
2358 // FIXME: C++0x defines behavior for this
2359 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2360 }
2361
2362 // Add a general "list initialization" step.
2363 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002364}
2365
2366/// \brief Try a reference initialization that involves calling a conversion
2367/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002368static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2369 const InitializedEntity &Entity,
2370 const InitializationKind &Kind,
2371 Expr *Initializer,
2372 bool AllowRValues,
2373 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002374 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2376 QualType T1 = cv1T1.getUnqualifiedType();
2377 QualType cv2T2 = Initializer->getType();
2378 QualType T2 = cv2T2.getUnqualifiedType();
2379
2380 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002381 bool ObjCConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002382 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002383 T1, T2, DerivedToBase,
2384 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002385 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002386 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002387 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002388
2389 // Build the candidate set directly in the initialization sequence
2390 // structure, so that it will persist if we fail.
2391 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2392 CandidateSet.clear();
2393
2394 // Determine whether we are allowed to call explicit constructors or
2395 // explicit conversion operators.
2396 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002397
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002399 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2400 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002401 // The type we're converting to is a class type. Enumerate its constructors
2402 // to see if there is a suitable conversion.
2403 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002404
Douglas Gregor20093b42009-12-09 23:02:17 +00002405 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002406 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002407 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002408 NamedDecl *D = *Con;
2409 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2410
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 // Find the constructor (which may be a template).
2412 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002413 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002414 if (ConstructorTmpl)
2415 Constructor = cast<CXXConstructorDecl>(
2416 ConstructorTmpl->getTemplatedDecl());
2417 else
John McCall9aa472c2010-03-19 07:35:19 +00002418 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002419
Douglas Gregor20093b42009-12-09 23:02:17 +00002420 if (!Constructor->isInvalidDecl() &&
2421 Constructor->isConvertingConstructor(AllowExplicit)) {
2422 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002423 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002424 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002425 &Initializer, 1, CandidateSet,
2426 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002427 else
John McCall9aa472c2010-03-19 07:35:19 +00002428 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002429 &Initializer, 1, CandidateSet,
2430 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002431 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002432 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 }
John McCall572fc622010-08-17 07:23:57 +00002434 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2435 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002436
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002437 const RecordType *T2RecordType = 0;
2438 if ((T2RecordType = T2->getAs<RecordType>()) &&
2439 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 // The type we're converting from is a class type, enumerate its conversion
2441 // functions.
2442 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2443
John McCalleec51cf2010-01-20 00:46:10 +00002444 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002446 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2447 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002448 NamedDecl *D = *I;
2449 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2450 if (isa<UsingShadowDecl>(D))
2451 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452
Douglas Gregor20093b42009-12-09 23:02:17 +00002453 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2454 CXXConversionDecl *Conv;
2455 if (ConvTemplate)
2456 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2457 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002458 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002459
Douglas Gregor20093b42009-12-09 23:02:17 +00002460 // If the conversion function doesn't return a reference type,
2461 // it can't be considered for this conversion unless we're allowed to
2462 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002463 // FIXME: Do we need to make sure that we only consider conversion
2464 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002465 // break recursion.
2466 if ((AllowExplicit || !Conv->isExplicit()) &&
2467 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2468 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002469 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002470 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002471 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 else
John McCall9aa472c2010-03-19 07:35:19 +00002473 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002474 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002475 }
2476 }
2477 }
John McCall572fc622010-08-17 07:23:57 +00002478 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2479 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002480
Douglas Gregor20093b42009-12-09 23:02:17 +00002481 SourceLocation DeclLoc = Initializer->getLocStart();
2482
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002483 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002485 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002486 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002487 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002488
Douglas Gregor20093b42009-12-09 23:02:17 +00002489 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002490
Chandler Carruth25ca4212011-02-25 19:41:05 +00002491 // This is the overload that will actually be used for the initialization, so
2492 // mark it as used.
2493 S.MarkDeclarationReferenced(DeclLoc, Function);
2494
Eli Friedman03981012009-12-11 02:42:07 +00002495 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002496 if (isa<CXXConversionDecl>(Function))
2497 T2 = Function->getResultType();
2498 else
2499 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002500
2501 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002502 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002503 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002504
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002506 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002507 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002508 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002509 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002510 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002511 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002512
Douglas Gregor20093b42009-12-09 23:02:17 +00002513 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002514 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002515 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002517 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002518 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002519 if (NewRefRelationship == Sema::Ref_Incompatible) {
2520 // If the type we've converted to is not reference-related to the
2521 // type we're looking for, then there is another conversion step
2522 // we need to perform to produce a temporary of the right type
2523 // that we'll be binding to.
2524 ImplicitConversionSequence ICS;
2525 ICS.setStandard();
2526 ICS.Standard = Best->FinalConversion;
2527 T2 = ICS.Standard.getToType(2);
2528 Sequence.AddConversionSequenceStep(ICS, T2);
2529 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 Sequence.AddDerivedToBaseCastStep(
2531 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002532 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002533 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002534 else if (NewObjCConversion)
2535 Sequence.AddObjCObjectConversionStep(
2536 S.Context.getQualifiedType(T1,
2537 T2.getNonReferenceType().getQualifiers()));
2538
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002540 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2543 return OR_Success;
2544}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002545
2546/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2547static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002548 const InitializedEntity &Entity,
2549 const InitializationKind &Kind,
2550 Expr *Initializer,
2551 InitializationSequence &Sequence) {
2552 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002553
Douglas Gregord6542d82009-12-22 15:35:07 +00002554 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002555 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002556 Qualifiers T1Quals;
2557 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002559 Qualifiers T2Quals;
2560 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002561 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002562
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 // If the initializer is the address of an overloaded function, try
2564 // to resolve the overloaded function. If all goes well, T2 is the
2565 // type of the resulting function.
2566 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002567 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002569 T1,
2570 false,
2571 Found)) {
2572 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2573 cv2T2 = Fn->getType();
2574 T2 = cv2T2.getUnqualifiedType();
2575 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002576 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2577 return;
2578 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002579 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002580
Douglas Gregor20093b42009-12-09 23:02:17 +00002581 // Compute some basic properties of the types and the initializer.
2582 bool isLValueRef = DestType->isLValueReferenceType();
2583 bool isRValueRef = !isLValueRef;
2584 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002585 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002586 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002587 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002588 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2589 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002590
Douglas Gregor20093b42009-12-09 23:02:17 +00002591 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002592 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002593 // "cv2 T2" as follows:
2594 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002596 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002597 // Note the analogous bullet points for rvlaue refs to functions. Because
2598 // there are no function rvalues in C++, rvalue refs to functions are treated
2599 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002600 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002601 bool T1Function = T1->isFunctionType();
2602 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002603 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002604 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002605 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002606 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002607 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002608 // reference-compatible with "cv2 T2," or
2609 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002610 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002611 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002612 // can occur. However, we do pay attention to whether it is a bit-field
2613 // to decide whether we're actually binding to a temporary created from
2614 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 if (DerivedToBase)
2616 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002617 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002618 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002619 else if (ObjCConversion)
2620 Sequence.AddObjCObjectConversionStep(
2621 S.Context.getQualifiedType(T1, T2Quals));
2622
Chandler Carruth5535c382010-01-12 20:32:25 +00002623 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002624 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002625 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002626 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002627 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002628 return;
2629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630
2631 // - has a class type (i.e., T2 is a class type), where T1 is not
2632 // reference-related to T2, and can be implicitly converted to an
2633 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2634 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002635 // applicable conversion functions (13.3.1.6) and choosing the best
2636 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002637 // If we have an rvalue ref to function type here, the rhs must be
2638 // an rvalue.
2639 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2640 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002641 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002643 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002644 Sequence);
2645 if (ConvOvlResult == OR_Success)
2646 return;
John McCall1d318332010-01-12 00:44:57 +00002647 if (ConvOvlResult != OR_No_Viable_Function) {
2648 Sequence.SetOverloadFailure(
2649 InitializationSequence::FK_ReferenceInitOverloadFailed,
2650 ConvOvlResult);
2651 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 }
2653 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002654
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002655 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002656 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002657 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002658 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002659 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2660 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2661 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002662 Sequence.SetOverloadFailure(
2663 InitializationSequence::FK_ReferenceInitOverloadFailed,
2664 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002665 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002666 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002667 ? (RefRelationship == Sema::Ref_Related
2668 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2669 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2670 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002671
Douglas Gregor20093b42009-12-09 23:02:17 +00002672 return;
2673 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002674
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002675 // - If the initializer expression
2676 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2677 // "cv1 T1" is reference-compatible with "cv2 T2"
2678 // Note: functions are handled below.
2679 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002680 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002681 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002682 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002683 (InitCategory.isXValue() ||
2684 (InitCategory.isPRValue() && T2->isRecordType()) ||
2685 (InitCategory.isPRValue() && T2->isArrayType()))) {
2686 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2687 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002688 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2689 // compiler the freedom to perform a copy here or bind to the
2690 // object, while C++0x requires that we bind directly to the
2691 // object. Hence, we always bind to the object without making an
2692 // extra copy. However, in C++03 requires that we check for the
2693 // presence of a suitable copy constructor:
2694 //
2695 // The constructor that would be used to make the copy shall
2696 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002697 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002698 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002699 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002701 if (DerivedToBase)
2702 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2703 ValueKind);
2704 else if (ObjCConversion)
2705 Sequence.AddObjCObjectConversionStep(
2706 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002707
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002708 if (T1Quals != T2Quals)
2709 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002711 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002712 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002713 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002714
2715 // - has a class type (i.e., T2 is a class type), where T1 is not
2716 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002717 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2718 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002719 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002720 if (RefRelationship == Sema::Ref_Incompatible) {
2721 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2722 Kind, Initializer,
2723 /*AllowRValues=*/true,
2724 Sequence);
2725 if (ConvOvlResult)
2726 Sequence.SetOverloadFailure(
2727 InitializationSequence::FK_ReferenceInitOverloadFailed,
2728 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002729
Douglas Gregor20093b42009-12-09 23:02:17 +00002730 return;
2731 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002732
Douglas Gregor20093b42009-12-09 23:02:17 +00002733 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2734 return;
2735 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002736
2737 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002738 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002739 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002740 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002741
Douglas Gregor20093b42009-12-09 23:02:17 +00002742 // Determine whether we are allowed to call explicit constructors or
2743 // explicit conversion operators.
2744 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002745
2746 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2747
2748 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2749 /*SuppressUserConversions*/ false,
2750 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002751 /*FIXME:InOverloadResolution=*/false,
2752 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002753 // FIXME: Use the conversion function set stored in ICS to turn
2754 // this into an overloading ambiguity diagnostic. However, we need
2755 // to keep that set as an OverloadCandidateSet rather than as some
2756 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002757 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2758 Sequence.SetOverloadFailure(
2759 InitializationSequence::FK_ReferenceInitOverloadFailed,
2760 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002761 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2762 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002763 else
2764 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002765 return;
2766 }
2767
2768 // [...] If T1 is reference-related to T2, cv1 must be the
2769 // same cv-qualification as, or greater cv-qualification
2770 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002771 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2772 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002773 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002774 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002775 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2776 return;
2777 }
2778
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002779 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002780 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002781 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002782 InitCategory.isLValue()) {
2783 Sequence.SetFailed(
2784 InitializationSequence::FK_RValueReferenceBindingToLValue);
2785 return;
2786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787
Douglas Gregor20093b42009-12-09 23:02:17 +00002788 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2789 return;
2790}
2791
2792/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793/// (C++ [dcl.init.string], C99 6.7.8).
2794static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 const InitializedEntity &Entity,
2796 const InitializationKind &Kind,
2797 Expr *Initializer,
2798 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002799 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002800 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002801}
2802
Douglas Gregor20093b42009-12-09 23:02:17 +00002803/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2804/// enumerates the constructors of the initialized entity and performs overload
2805/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002807 const InitializedEntity &Entity,
2808 const InitializationKind &Kind,
2809 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002810 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002811 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002812 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002813
Douglas Gregor51c56d62009-12-14 20:49:26 +00002814 // Build the candidate set directly in the initialization sequence
2815 // structure, so that it will persist if we fail.
2816 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2817 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002818
Douglas Gregor51c56d62009-12-14 20:49:26 +00002819 // Determine whether we are allowed to call explicit constructors or
2820 // explicit conversion operators.
2821 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2822 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002823 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002824
2825 // The type we're constructing needs to be complete.
2826 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002827 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002828 return;
2829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
Douglas Gregor51c56d62009-12-14 20:49:26 +00002831 // The type we're converting to is a class type. Enumerate its constructors
2832 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002833 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002834 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00002835 CXXRecordDecl *DestRecordDecl
2836 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002837
Douglas Gregor51c56d62009-12-14 20:49:26 +00002838 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002839 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002840 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002841 NamedDecl *D = *Con;
2842 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002843 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844
Douglas Gregor51c56d62009-12-14 20:49:26 +00002845 // Find the constructor (which may be a template).
2846 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002847 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002848 if (ConstructorTmpl)
2849 Constructor = cast<CXXConstructorDecl>(
2850 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002851 else {
John McCall9aa472c2010-03-19 07:35:19 +00002852 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002853
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002854 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00002855 // suppress user-defined conversions on the arguments.
2856 // FIXME: Move constructors?
2857 if (Kind.getKind() == InitializationKind::IK_Copy &&
2858 Constructor->isCopyConstructor())
2859 SuppressUserConversions = true;
2860 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861
Douglas Gregor51c56d62009-12-14 20:49:26 +00002862 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002863 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002864 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002865 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002866 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002867 Args, NumArgs, CandidateSet,
2868 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002869 else
John McCall9aa472c2010-03-19 07:35:19 +00002870 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002871 Args, NumArgs, CandidateSet,
2872 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002873 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 }
2875
Douglas Gregor51c56d62009-12-14 20:49:26 +00002876 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002877
2878 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002879 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002880 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002881 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002882 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002884 Result);
2885 return;
2886 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002887
2888 // C++0x [dcl.init]p6:
2889 // If a program calls for the default initialization of an object
2890 // of a const-qualified type T, T shall be a class type with a
2891 // user-provided default constructor.
2892 if (Kind.getKind() == InitializationKind::IK_Default &&
2893 Entity.getType().isConstQualified() &&
2894 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2895 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2896 return;
2897 }
2898
Douglas Gregor51c56d62009-12-14 20:49:26 +00002899 // Add the constructor initialization step. Any cv-qualification conversion is
2900 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002901 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002903 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002904 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002905}
2906
Douglas Gregor71d17402009-12-15 00:01:57 +00002907/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002908static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00002909 const InitializedEntity &Entity,
2910 const InitializationKind &Kind,
2911 InitializationSequence &Sequence) {
2912 // C++ [dcl.init]p5:
2913 //
2914 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002915 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002916
Douglas Gregor71d17402009-12-15 00:01:57 +00002917 // -- if T is an array type, then each element is value-initialized;
2918 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2919 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002920
Douglas Gregor71d17402009-12-15 00:01:57 +00002921 if (const RecordType *RT = T->getAs<RecordType>()) {
2922 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2923 // -- if T is a class type (clause 9) with a user-declared
2924 // constructor (12.1), then the default constructor for T is
2925 // called (and the initialization is ill-formed if T has no
2926 // accessible default constructor);
2927 //
2928 // FIXME: we really want to refer to a single subobject of the array,
2929 // but Entity doesn't have a way to capture that (yet).
2930 if (ClassDecl->hasUserDeclaredConstructor())
2931 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932
Douglas Gregor16006c92009-12-16 18:50:27 +00002933 // -- if T is a (possibly cv-qualified) non-union class type
2934 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002935 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00002936 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002937 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002938 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002939 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002940 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00002941 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002942 }
2943 }
2944
Douglas Gregord6542d82009-12-22 15:35:07 +00002945 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002946 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2947}
2948
Douglas Gregor99a2e602009-12-16 01:38:02 +00002949/// \brief Attempt default initialization (C++ [dcl.init]p6).
2950static void TryDefaultInitialization(Sema &S,
2951 const InitializedEntity &Entity,
2952 const InitializationKind &Kind,
2953 InitializationSequence &Sequence) {
2954 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955
Douglas Gregor99a2e602009-12-16 01:38:02 +00002956 // C++ [dcl.init]p6:
2957 // To default-initialize an object of type T means:
2958 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002959 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002960 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2961 DestType = Array->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002962
Douglas Gregor99a2e602009-12-16 01:38:02 +00002963 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2964 // constructor for T is called (and the initialization is ill-formed if
2965 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002966 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002967 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2968 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002970
Douglas Gregor99a2e602009-12-16 01:38:02 +00002971 // - otherwise, no initialization is performed.
2972 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002973
Douglas Gregor99a2e602009-12-16 01:38:02 +00002974 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002975 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00002976 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002977 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002978 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2979}
2980
Douglas Gregor20093b42009-12-09 23:02:17 +00002981/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2982/// which enumerates all conversion functions and performs overload resolution
2983/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002984static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002985 const InitializedEntity &Entity,
2986 const InitializationKind &Kind,
2987 Expr *Initializer,
2988 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002989 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002990
Douglas Gregord6542d82009-12-22 15:35:07 +00002991 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002992 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2993 QualType SourceType = Initializer->getType();
2994 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2995 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002996
Douglas Gregor4a520a22009-12-14 17:27:33 +00002997 // Build the candidate set directly in the initialization sequence
2998 // structure, so that it will persist if we fail.
2999 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3000 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003001
Douglas Gregor4a520a22009-12-14 17:27:33 +00003002 // Determine whether we are allowed to call explicit constructors or
3003 // explicit conversion operators.
3004 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003005
Douglas Gregor4a520a22009-12-14 17:27:33 +00003006 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3007 // The type we're converting to is a class type. Enumerate its constructors
3008 // to see if there is a suitable conversion.
3009 CXXRecordDecl *DestRecordDecl
3010 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003011
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003012 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003014 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003015 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003016 Con != ConEnd; ++Con) {
3017 NamedDecl *D = *Con;
3018 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003020 // Find the constructor (which may be a template).
3021 CXXConstructorDecl *Constructor = 0;
3022 FunctionTemplateDecl *ConstructorTmpl
3023 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003024 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003025 Constructor = cast<CXXConstructorDecl>(
3026 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003027 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003028 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003030 if (!Constructor->isInvalidDecl() &&
3031 Constructor->isConvertingConstructor(AllowExplicit)) {
3032 if (ConstructorTmpl)
3033 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3034 /*ExplicitArgs*/ 0,
3035 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003036 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003037 else
3038 S.AddOverloadCandidate(Constructor, FoundDecl,
3039 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003040 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003043 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003044 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003045
3046 SourceLocation DeclLoc = Initializer->getLocStart();
3047
Douglas Gregor4a520a22009-12-14 17:27:33 +00003048 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3049 // The type we're converting from is a class type, enumerate its conversion
3050 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003051
Eli Friedman33c2da92009-12-20 22:12:03 +00003052 // We can only enumerate the conversion functions for a complete type; if
3053 // the type isn't complete, simply skip this step.
3054 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3055 CXXRecordDecl *SourceRecordDecl
3056 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057
John McCalleec51cf2010-01-20 00:46:10 +00003058 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003059 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003060 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003062 I != E; ++I) {
3063 NamedDecl *D = *I;
3064 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3065 if (isa<UsingShadowDecl>(D))
3066 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003067
Eli Friedman33c2da92009-12-20 22:12:03 +00003068 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3069 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003070 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003071 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003072 else
John McCall32daa422010-03-31 01:36:47 +00003073 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003074
Eli Friedman33c2da92009-12-20 22:12:03 +00003075 if (AllowExplicit || !Conv->isExplicit()) {
3076 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003077 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003078 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003079 CandidateSet);
3080 else
John McCall9aa472c2010-03-19 07:35:19 +00003081 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003082 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003083 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003084 }
3085 }
3086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087
3088 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003089 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003090 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003091 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003092 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003093 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003094 Result);
3095 return;
3096 }
John McCall1d318332010-01-12 00:44:57 +00003097
Douglas Gregor4a520a22009-12-14 17:27:33 +00003098 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003099 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003100
Douglas Gregor4a520a22009-12-14 17:27:33 +00003101 if (isa<CXXConstructorDecl>(Function)) {
3102 // Add the user-defined conversion step. Any cv-qualification conversion is
3103 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003104 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003105 return;
3106 }
3107
3108 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003109 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003110 if (ConvType->getAs<RecordType>()) {
3111 // If we're converting to a class type, there may be an copy if
3112 // the resulting temporary object (possible to create an object of
3113 // a base class type). That copy is not a separate conversion, so
3114 // we just make a note of the actual destination type (possibly a
3115 // base class of the type returned by the conversion function) and
3116 // let the user-defined conversion step handle the conversion.
3117 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3118 return;
3119 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003120
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003121 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003123 // If the conversion following the call to the conversion function
3124 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003125 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3126 Best->FinalConversion.Third) {
3127 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003128 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003129 ICS.Standard = Best->FinalConversion;
3130 Sequence.AddConversionSequenceStep(ICS, DestType);
3131 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003132}
3133
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003134/// \brief Determine whether we have compatible array types for the
3135/// purposes of GNU by-copy array initialization.
3136static bool hasCompatibleArrayTypes(ASTContext &Context,
3137 const ArrayType *Dest,
3138 const ArrayType *Source) {
3139 // If the source and destination array types are equivalent, we're
3140 // done.
3141 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3142 return true;
3143
3144 // Make sure that the element types are the same.
3145 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3146 return false;
3147
3148 // The only mismatch we allow is when the destination is an
3149 // incomplete array type and the source is a constant array type.
3150 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3151}
3152
Douglas Gregor20093b42009-12-09 23:02:17 +00003153InitializationSequence::InitializationSequence(Sema &S,
3154 const InitializedEntity &Entity,
3155 const InitializationKind &Kind,
3156 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003157 unsigned NumArgs)
3158 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003159 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160
Douglas Gregor20093b42009-12-09 23:02:17 +00003161 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 // The semantics of initializers are as follows. The destination type is
3163 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003164 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003165 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003166 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003167 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003168
3169 if (DestType->isDependentType() ||
3170 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3171 SequenceKind = DependentSequence;
3172 return;
3173 }
3174
John McCall241d5582010-12-07 22:54:16 +00003175 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003176 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3177 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3178 if (Result.isInvalid()) {
3179 SetFailed(FK_ConversionFromPropertyFailed);
3180 return;
3181 }
3182 Args[I] = Result.take();
3183 }
John McCall241d5582010-12-07 22:54:16 +00003184
Douglas Gregor20093b42009-12-09 23:02:17 +00003185 QualType SourceType;
3186 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003187 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003188 Initializer = Args[0];
3189 if (!isa<InitListExpr>(Initializer))
3190 SourceType = Initializer->getType();
3191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192
3193 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003194 // list-initialized (8.5.4).
3195 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3196 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003197 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003198 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregor20093b42009-12-09 23:02:17 +00003200 // - If the destination type is a reference type, see 8.5.3.
3201 if (DestType->isReferenceType()) {
3202 // C++0x [dcl.init.ref]p1:
3203 // A variable declared to be a T& or T&&, that is, "reference to type T"
3204 // (8.3.2), shall be initialized by an object, or function, of type T or
3205 // by an object that can be converted into a T.
3206 // (Therefore, multiple arguments are not permitted.)
3207 if (NumArgs != 1)
3208 SetFailed(FK_TooManyInitsForReference);
3209 else
3210 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3211 return;
3212 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213
Douglas Gregor20093b42009-12-09 23:02:17 +00003214 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003215 if (Kind.getKind() == InitializationKind::IK_Value ||
3216 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003217 TryValueInitialization(S, Entity, Kind, *this);
3218 return;
3219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220
Douglas Gregor99a2e602009-12-16 01:38:02 +00003221 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003222 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003223 TryDefaultInitialization(S, Entity, Kind, *this);
3224 return;
3225 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003226
John McCallce6c9b72011-02-21 07:22:22 +00003227 // - If the destination type is an array of characters, an array of
3228 // char16_t, an array of char32_t, or an array of wchar_t, and the
3229 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003230 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003232 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3233 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCallce6c9b72011-02-21 07:22:22 +00003234 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3235 return;
3236 }
3237
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003238 // Note: as an GNU C extension, we allow initialization of an
3239 // array from a compound literal that creates an array of the same
3240 // type, so long as the initializer has no side effects.
3241 if (!S.getLangOptions().CPlusPlus && Initializer &&
3242 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3243 Initializer->getType()->isArrayType()) {
3244 const ArrayType *SourceAT
3245 = Context.getAsArrayType(Initializer->getType());
3246 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3247 SetFailed(FK_ArrayTypeMismatch);
3248 else if (Initializer->HasSideEffects(S.Context))
3249 SetFailed(FK_NonConstantArrayInit);
3250 else {
3251 setSequenceKind(ArrayInit);
3252 AddArrayInitStep(DestType);
3253 }
3254 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3256 else
3257 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258
Douglas Gregor20093b42009-12-09 23:02:17 +00003259 return;
3260 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003261
3262 // Handle initialization in C
3263 if (!S.getLangOptions().CPlusPlus) {
3264 setSequenceKind(CAssignment);
3265 AddCAssignmentStep(DestType);
3266 return;
3267 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 // - If the destination type is a (possibly cv-qualified) class type:
3270 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003271 // - If the initialization is direct-initialization, or if it is
3272 // copy-initialization where the cv-unqualified version of the
3273 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 // class of the destination, constructors are considered. [...]
3275 if (Kind.getKind() == InitializationKind::IK_Direct ||
3276 (Kind.getKind() == InitializationKind::IK_Copy &&
3277 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3278 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003280 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003282 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003284 // used) to a derived class thereof are enumerated as described in
3285 // 13.3.1.4, and the best one is chosen through overload resolution
3286 // (13.3).
3287 else
3288 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3289 return;
3290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003291
Douglas Gregor99a2e602009-12-16 01:38:02 +00003292 if (NumArgs > 1) {
3293 SetFailed(FK_TooManyInitsForScalar);
3294 return;
3295 }
3296 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297
3298 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003300 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003301 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3302 return;
3303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003306 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003309 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003310 if (S.TryImplicitConversion(*this, Entity, Initializer,
3311 /*SuppressUserConversions*/ true,
3312 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003313 /*InOverloadResolution*/ false,
3314 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregor8e960432010-11-08 03:40:48 +00003315 {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003316 DeclAccessPair dap;
3317 if (Initializer->getType() == Context.OverloadTy &&
3318 !S.ResolveAddressOfOverloadedFunction(Initializer
3319 , DestType, false, dap))
Douglas Gregor8e960432010-11-08 03:40:48 +00003320 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3321 else
3322 SetFailed(InitializationSequence::FK_ConversionFailed);
3323 }
John McCall369371c2010-06-04 02:29:22 +00003324 else
3325 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003326}
3327
3328InitializationSequence::~InitializationSequence() {
3329 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3330 StepEnd = Steps.end();
3331 Step != StepEnd; ++Step)
3332 Step->Destroy();
3333}
3334
3335//===----------------------------------------------------------------------===//
3336// Perform initialization
3337//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003339getAssignmentAction(const InitializedEntity &Entity) {
3340 switch(Entity.getKind()) {
3341 case InitializedEntity::EK_Variable:
3342 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003343 case InitializedEntity::EK_Exception:
3344 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003345 case InitializedEntity::EK_Delegation:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003346 return Sema::AA_Initializing;
3347
3348 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003350 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3351 return Sema::AA_Sending;
3352
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003353 return Sema::AA_Passing;
3354
3355 case InitializedEntity::EK_Result:
3356 return Sema::AA_Returning;
3357
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003358 case InitializedEntity::EK_Temporary:
3359 // FIXME: Can we tell apart casting vs. converting?
3360 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003362 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003363 case InitializedEntity::EK_ArrayElement:
3364 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003365 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003366 return Sema::AA_Initializing;
3367 }
3368
3369 return Sema::AA_Converting;
3370}
3371
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003372/// \brief Whether we should binding a created object as a temporary when
3373/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003374static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003375 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003376 case InitializedEntity::EK_ArrayElement:
3377 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003378 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003379 case InitializedEntity::EK_New:
3380 case InitializedEntity::EK_Variable:
3381 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003382 case InitializedEntity::EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003383 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003384 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003385 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003386 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003388 case InitializedEntity::EK_Parameter:
3389 case InitializedEntity::EK_Temporary:
3390 return true;
3391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003393 llvm_unreachable("missed an InitializedEntity kind?");
3394}
3395
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003396/// \brief Whether the given entity, when initialized with an object
3397/// created for that initialization, requires destruction.
3398static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3399 switch (Entity.getKind()) {
3400 case InitializedEntity::EK_Member:
3401 case InitializedEntity::EK_Result:
3402 case InitializedEntity::EK_New:
3403 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003404 case InitializedEntity::EK_Delegation:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003405 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003406 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003407 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003409 case InitializedEntity::EK_Variable:
3410 case InitializedEntity::EK_Parameter:
3411 case InitializedEntity::EK_Temporary:
3412 case InitializedEntity::EK_ArrayElement:
3413 case InitializedEntity::EK_Exception:
3414 return true;
3415 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003416
3417 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003418}
3419
Douglas Gregor523d46a2010-04-18 07:40:54 +00003420/// \brief Make a (potentially elidable) temporary copy of the object
3421/// provided by the given initializer by calling the appropriate copy
3422/// constructor.
3423///
3424/// \param S The Sema object used for type-checking.
3425///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003426/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003427/// the type of the initializer expression or a superclass thereof.
3428///
3429/// \param Enter The entity being initialized.
3430///
3431/// \param CurInit The initializer expression.
3432///
3433/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3434/// is permitted in C++03 (but not C++0x) when binding a reference to
3435/// an rvalue.
3436///
3437/// \returns An expression that copies the initializer expression into
3438/// a temporary object, or an error expression if a copy could not be
3439/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003440static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003441 QualType T,
3442 const InitializedEntity &Entity,
3443 ExprResult CurInit,
3444 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003445 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003446 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003448 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003449 Class = cast<CXXRecordDecl>(Record->getDecl());
3450 if (!Class)
3451 return move(CurInit);
3452
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003453 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003454 // When certain criteria are met, an implementation is allowed to
3455 // omit the copy/move construction of a class object, even if the
3456 // copy/move constructor and/or destructor for the object have
3457 // side effects. [...]
3458 // - when a temporary class object that has not been bound to a
3459 // reference (12.2) would be copied/moved to a class object
3460 // with the same cv-unqualified type, the copy/move operation
3461 // can be omitted by constructing the temporary object
3462 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003464 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003465 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003466 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003467 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003468 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003469 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003470 switch (Entity.getKind()) {
3471 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003472 Loc = Entity.getReturnLoc();
3473 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003474
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003475 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003476 Loc = Entity.getThrowLoc();
3477 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003479 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003480 Loc = Entity.getDecl()->getLocation();
3481 break;
3482
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003483 case InitializedEntity::EK_ArrayElement:
3484 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003485 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003486 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003487 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003488 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003489 case InitializedEntity::EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003490 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003491 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003492 Loc = CurInitExpr->getLocStart();
3493 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003494 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003495
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003497 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3498 return move(CurInit);
3499
Douglas Gregorcc15f012011-01-21 19:38:21 +00003500 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003501 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003502 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003503 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003504 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003505 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003506 // C++0x [dcl.init]p16, second bullet to class types, this
3507 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003508 CXXConstructorDecl *Constructor = 0;
3509
3510 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003511 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003512 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003513 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003514 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003515 continue;
3516
3517 DeclAccessPair FoundDecl
3518 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3519 S.AddOverloadCandidate(Constructor, FoundDecl,
3520 &CurInitExpr, 1, CandidateSet);
3521 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003523
3524 // Handle constructor templates.
3525 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3526 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003527 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003528
Douglas Gregor6493cc52010-11-08 17:16:59 +00003529 Constructor = cast<CXXConstructorDecl>(
3530 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003531 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003532 continue;
3533
3534 // FIXME: Do we need to limit this to copy-constructor-like
3535 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003536 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003537 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3538 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3539 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003542 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003543 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003544 case OR_Success:
3545 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003547 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003548 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3549 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3550 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003551 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003552 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003553 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003554 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003555 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003556 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003558 case OR_Ambiguous:
3559 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003560 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003561 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003562 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003563 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003565 case OR_Deleted:
3566 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003567 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003568 << CurInitExpr->getSourceRange();
3569 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3570 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003571 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003572 }
3573
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003574 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003575 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003576 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003577
Anders Carlsson9a68a672010-04-21 18:47:17 +00003578 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003579 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003580
3581 if (IsExtraneousCopy) {
3582 // If this is a totally extraneous copy for C++03 reference
3583 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003584 // expression. We don't generate an (elided) copy operation here
3585 // because doing so would require us to pass down a flag to avoid
3586 // infinite recursion, where each step adds another extraneous,
3587 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003588
Douglas Gregor2559a702010-04-18 07:57:34 +00003589 // Instantiate the default arguments of any extra parameters in
3590 // the selected copy constructor, as if we were going to create a
3591 // proper call to the copy constructor.
3592 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3593 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3594 if (S.RequireCompleteType(Loc, Parm->getType(),
3595 S.PDiag(diag::err_call_incomplete_argument)))
3596 break;
3597
3598 // Build the default argument expression; we don't actually care
3599 // if this succeeds or not, because this routine will complain
3600 // if there was a problem.
3601 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3602 }
3603
Douglas Gregor523d46a2010-04-18 07:40:54 +00003604 return S.Owned(CurInitExpr);
3605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606
Chandler Carruth25ca4212011-02-25 19:41:05 +00003607 S.MarkDeclarationReferenced(Loc, Constructor);
3608
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003609 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003610 // constructor call (we might have derived-to-base conversions, or
3611 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003612 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003613 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003614 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003615
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003616 // Actually perform the constructor call.
3617 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003618 move_arg(ConstructorArgs),
3619 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003620 CXXConstructExpr::CK_Complete,
3621 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003623 // If we're supposed to bind temporaries, do so.
3624 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3625 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3626 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003627}
Douglas Gregor20093b42009-12-09 23:02:17 +00003628
Douglas Gregora41a8c52010-04-22 00:20:18 +00003629void InitializationSequence::PrintInitLocationNote(Sema &S,
3630 const InitializedEntity &Entity) {
3631 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3632 if (Entity.getDecl()->getLocation().isInvalid())
3633 return;
3634
3635 if (Entity.getDecl()->getDeclName())
3636 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3637 << Entity.getDecl()->getDeclName();
3638 else
3639 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3640 }
3641}
3642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003643ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003644InitializationSequence::Perform(Sema &S,
3645 const InitializedEntity &Entity,
3646 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003647 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003648 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003649 if (SequenceKind == FailedSequence) {
3650 unsigned NumArgs = Args.size();
3651 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003652 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003653 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003654
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003656 // If the declaration is a non-dependent, incomplete array type
3657 // that has an initializer, then its type will be completed once
3658 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003659 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003660 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003661 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003662 if (const IncompleteArrayType *ArrayT
3663 = S.Context.getAsIncompleteArrayType(DeclType)) {
3664 // FIXME: We don't currently have the ability to accurately
3665 // compute the length of an initializer list without
3666 // performing full type-checking of the initializer list
3667 // (since we have to determine where braces are implicitly
3668 // introduced and such). So, we fall back to making the array
3669 // type a dependently-sized array type with no specified
3670 // bound.
3671 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3672 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003673
Douglas Gregord87b61f2009-12-10 17:56:55 +00003674 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003675 if (DeclaratorDecl *DD = Entity.getDecl()) {
3676 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3677 TypeLoc TL = TInfo->getTypeLoc();
3678 if (IncompleteArrayTypeLoc *ArrayLoc
3679 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3680 Brackets = ArrayLoc->getBracketsRange();
3681 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003682 }
3683
3684 *ResultType
3685 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3686 /*NumElts=*/0,
3687 ArrayT->getSizeModifier(),
3688 ArrayT->getIndexTypeCVRQualifiers(),
3689 Brackets);
3690 }
3691
3692 }
3693 }
3694
Eli Friedman08544622009-12-22 02:35:53 +00003695 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003696 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003697
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003698 if (Args.size() == 0)
3699 return S.Owned((Expr *)0);
3700
Douglas Gregor20093b42009-12-09 23:02:17 +00003701 unsigned NumArgs = Args.size();
3702 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3703 SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704 (Expr **)Args.release(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003705 NumArgs,
3706 SourceLocation()));
3707 }
3708
Douglas Gregor99a2e602009-12-16 01:38:02 +00003709 if (SequenceKind == NoInitialization)
3710 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711
Douglas Gregord6542d82009-12-22 15:35:07 +00003712 QualType DestType = Entity.getType().getNonReferenceType();
3713 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003714 // the same as Entity.getDecl()->getType() in cases involving type merging,
3715 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003716 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003717 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003718 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003719
John McCall60d7b3a2010-08-24 06:29:42 +00003720 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003721
Douglas Gregor99a2e602009-12-16 01:38:02 +00003722 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723
3724 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00003725 // grab the only argument out the Args and place it into the "current"
3726 // initializer.
3727 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003728 case SK_ResolveAddressOfOverloadedFunction:
3729 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003730 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003731 case SK_CastDerivedToBaseLValue:
3732 case SK_BindReference:
3733 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003734 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003735 case SK_UserConversion:
3736 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003737 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003738 case SK_QualificationConversionRValue:
3739 case SK_ConversionSequence:
3740 case SK_ListInitialization:
3741 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003742 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003743 case SK_ObjCObjectConversion:
3744 case SK_ArrayInit: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003745 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00003746 CurInit = Args.get()[0];
3747 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003748
3749 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00003750 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3751 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3752 if (CurInit.isInvalid())
3753 return ExprError();
3754 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003755 break;
John McCallf6a16482010-12-04 03:47:34 +00003756 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003758 case SK_ConstructorInitialization:
3759 case SK_ZeroInitialization:
3760 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003761 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003762
3763 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00003764 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003765 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 for (step_iterator Step = step_begin(), StepEnd = step_end();
3767 Step != StepEnd; ++Step) {
3768 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003769 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
John Wiegley429bb272011-04-08 18:41:53 +00003771 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 switch (Step->Kind) {
3774 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003775 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00003776 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00003777 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003778 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003779 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003780 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003781 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783
Douglas Gregor20093b42009-12-09 23:02:17 +00003784 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003785 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003786 case SK_CastDerivedToBaseLValue: {
3787 // We have a derived-to-base cast that produces either an rvalue or an
3788 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789
John McCallf871d0c2010-08-07 06:22:56 +00003790 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003791
Douglas Gregor20093b42009-12-09 23:02:17 +00003792 // Casts to inaccessible base classes are allowed with C-style casts.
3793 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3794 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00003795 CurInit.get()->getLocStart(),
3796 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003797 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003798 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003800 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3801 QualType T = SourceType;
3802 if (const PointerType *Pointer = T->getAs<PointerType>())
3803 T = Pointer->getPointeeType();
3804 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00003805 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003806 cast<CXXRecordDecl>(RecordTy->getDecl()));
3807 }
3808
John McCall5baba9d2010-08-25 10:28:54 +00003809 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003810 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003811 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003812 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003813 VK_XValue :
3814 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003815 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3816 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003817 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003818 CurInit.get(),
3819 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003820 break;
3821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822
Douglas Gregor20093b42009-12-09 23:02:17 +00003823 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00003824 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003825 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3826 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003827 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003828 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00003829 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00003830 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003831 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003832 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003833
John Wiegley429bb272011-04-08 18:41:53 +00003834 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003835 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003836 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3837 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00003838 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003839 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003840 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003841 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 // Reference binding does not have any corresponding ASTs.
3844
3845 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00003846 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003847 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003848
Douglas Gregor20093b42009-12-09 23:02:17 +00003849 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003850
Douglas Gregor20093b42009-12-09 23:02:17 +00003851 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003852 // Reference binding does not have any corresponding ASTs.
3853
Douglas Gregor20093b42009-12-09 23:02:17 +00003854 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00003855 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003856 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003857
Douglas Gregor20093b42009-12-09 23:02:17 +00003858 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003859
Douglas Gregor523d46a2010-04-18 07:40:54 +00003860 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00003862 /*IsExtraneousCopy=*/true);
3863 break;
3864
Douglas Gregor20093b42009-12-09 23:02:17 +00003865 case SK_UserConversion: {
3866 // We have a user-defined conversion that invokes either a constructor
3867 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003868 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003869 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003870 FunctionDecl *Fn = Step->Function.Function;
3871 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003872 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003873 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003874 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003876 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00003877 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003878 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003879
Douglas Gregor20093b42009-12-09 23:02:17 +00003880 // Determine the arguments required to actually perform the constructor
3881 // call.
John Wiegley429bb272011-04-08 18:41:53 +00003882 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00003883 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00003884 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003885 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003886 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor20093b42009-12-09 23:02:17 +00003888 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003890 move_arg(ConstructorArgs),
3891 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003892 CXXConstructExpr::CK_Complete,
3893 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003894 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003895 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003896
Anders Carlsson9a68a672010-04-21 18:47:17 +00003897 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003898 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003899 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003900
John McCall2de56d12010-08-25 11:45:40 +00003901 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003902 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3903 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3904 S.IsDerivedFrom(SourceType, Class))
3905 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003906
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003907 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003908 } else {
3909 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003910 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003911 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00003912 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00003913 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003914 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003915
3916 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00003917 // derived-to-base conversion? I believe the answer is "no", because
3918 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00003919 ExprResult CurInitExprRes =
3920 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
3921 FoundFn, Conversion);
3922 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003923 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00003924 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Douglas Gregor20093b42009-12-09 23:02:17 +00003926 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00003927 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003928 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003929 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930
John McCall2de56d12010-08-25 11:45:40 +00003931 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003933 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935
3936 bool RequiresCopy = !IsCopy &&
Douglas Gregor2f599792010-04-02 18:24:57 +00003937 getKind() != InitializationSequence::ReferenceBinding;
3938 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003939 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003940 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00003941 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003942 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00003944 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00003945 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003946 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00003947 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
3948 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003949 }
3950 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003951
Sebastian Redl906082e2010-07-20 04:20:21 +00003952 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003953 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00003954 CurInit.get()->getType(),
3955 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00003956 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003957
Douglas Gregor2f599792010-04-02 18:24:57 +00003958 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003959 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3960 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003961
Douglas Gregor20093b42009-12-09 23:02:17 +00003962 break;
3963 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003964
Douglas Gregor20093b42009-12-09 23:02:17 +00003965 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003966 case SK_QualificationConversionXValue:
3967 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003968 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003969 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003970 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003971 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003972 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003973 VK_XValue :
3974 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00003975 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003976 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003977 }
3978
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003979 case SK_ConversionSequence: {
John Wiegley429bb272011-04-08 18:41:53 +00003980 ExprResult CurInitExprRes =
3981 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
3982 getAssignmentAction(Entity),
3983 Kind.isCStyleOrFunctionalCast());
3984 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003985 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00003986 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregord87b61f2009-12-10 17:56:55 +00003990 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00003991 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003992 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003993 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003994 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003995
3996 CurInit.release();
3997 CurInit = S.Owned(InitList);
3998 break;
3999 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004000
4001 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004002 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004003 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004004 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregor51c56d62009-12-14 20:49:26 +00004006 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004007 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004008 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4009 ? Kind.getEqualLoc()
4010 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004011
4012 if (Kind.getKind() == InitializationKind::IK_Default) {
4013 // Force even a trivial, implicit default constructor to be
4014 // semantically checked. We do this explicitly because we don't build
4015 // the definition for completely trivial constructors.
4016 CXXRecordDecl *ClassDecl = Constructor->getParent();
4017 assert(ClassDecl && "No parent class for constructor.");
4018 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4019 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
4020 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4021 }
4022
Douglas Gregor51c56d62009-12-14 20:49:26 +00004023 // Determine the arguments required to actually perform the constructor
4024 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004026 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004027 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004028
4029
Douglas Gregor91be6f52010-03-02 17:18:33 +00004030 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004031 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004032 (Kind.getKind() == InitializationKind::IK_Direct ||
4033 Kind.getKind() == InitializationKind::IK_Value)) {
4034 // An explicitly-constructed temporary, e.g., X(1, 2).
4035 unsigned NumExprs = ConstructorArgs.size();
4036 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004037 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004038 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004039
Douglas Gregorab6677e2010-09-08 00:15:04 +00004040 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4041 if (!TSInfo)
4042 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor91be6f52010-03-02 17:18:33 +00004044 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4045 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004046 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004048 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004049 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004050 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004051 } else {
4052 CXXConstructExpr::ConstructionKind ConstructKind =
4053 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004054
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004055 if (Entity.getKind() == InitializedEntity::EK_Base) {
4056 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004058 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004059 }
4060
Chandler Carruth428edaf2010-10-25 08:47:36 +00004061 // Only get the parenthesis range if it is a direct construction.
4062 SourceRange parenRange =
4063 Kind.getKind() == InitializationKind::IK_Direct ?
4064 Kind.getParenRange() : SourceRange();
4065
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004066 // If the entity allows NRVO, mark the construction as elidable
4067 // unconditionally.
4068 if (Entity.allowsNRVO())
4069 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4070 Constructor, /*Elidable=*/true,
4071 move_arg(ConstructorArgs),
4072 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004073 ConstructKind,
4074 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004075 else
4076 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004078 move_arg(ConstructorArgs),
4079 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004080 ConstructKind,
4081 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004082 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004083 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004084 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004085
4086 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004087 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004088 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004089 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090
Douglas Gregor2f599792010-04-02 18:24:57 +00004091 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004092 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004093
Douglas Gregor51c56d62009-12-14 20:49:26 +00004094 break;
4095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Douglas Gregor71d17402009-12-15 00:01:57 +00004097 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004098 step_iterator NextStep = Step;
4099 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004100 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004101 NextStep->Kind == SK_ConstructorInitialization) {
4102 // The need for zero-initialization is recorded directly into
4103 // the call to the object's constructor within the next step.
4104 ConstructorInitRequiresZeroInit = true;
4105 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4106 S.getLangOptions().CPlusPlus &&
4107 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004108 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4109 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004111 Kind.getRange().getBegin());
4112
4113 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4114 TSInfo->getType().getNonLValueExprType(S.Context),
4115 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004116 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004117 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004118 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004119 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004120 break;
4121 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004122
4123 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004124 QualType SourceType = CurInit.get()->getType();
4125 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004126 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004127 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4128 if (Result.isInvalid())
4129 return ExprError();
4130 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004131
4132 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004133 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004134 if (ConvTy != Sema::Compatible &&
4135 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004136 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004137 == Sema::Compatible)
4138 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004139 if (CurInitExprRes.isInvalid())
4140 return ExprError();
4141 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004142
Douglas Gregora41a8c52010-04-22 00:20:18 +00004143 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004144 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4145 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004146 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004147 getAssignmentAction(Entity),
4148 &Complained)) {
4149 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004150 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004151 } else if (Complained)
4152 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004153 break;
4154 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004155
4156 case SK_StringInit: {
4157 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004158 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004159 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004160 break;
4161 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004162
4163 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004164 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004165 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004166 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004167 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004168
4169 case SK_ArrayInit:
4170 // Okay: we checked everything before creating this step. Note that
4171 // this is a GNU extension.
4172 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004173 << Step->Type << CurInit.get()->getType()
4174 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004175
4176 // If the destination type is an incomplete array type, update the
4177 // type accordingly.
4178 if (ResultType) {
4179 if (const IncompleteArrayType *IncompleteDest
4180 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4181 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004182 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004183 *ResultType = S.Context.getConstantArrayType(
4184 IncompleteDest->getElementType(),
4185 ConstantSource->getSize(),
4186 ArrayType::Normal, 0);
4187 }
4188 }
4189 }
4190
4191 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004192 }
4193 }
John McCall15d7d122010-11-11 03:21:53 +00004194
4195 // Diagnose non-fatal problems with the completed initialization.
4196 if (Entity.getKind() == InitializedEntity::EK_Member &&
4197 cast<FieldDecl>(Entity.getDecl())->isBitField())
4198 S.CheckBitFieldInitialization(Kind.getLocation(),
4199 cast<FieldDecl>(Entity.getDecl()),
4200 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
Douglas Gregor20093b42009-12-09 23:02:17 +00004202 return move(CurInit);
4203}
4204
4205//===----------------------------------------------------------------------===//
4206// Diagnose initialization failures
4207//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004208bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004209 const InitializedEntity &Entity,
4210 const InitializationKind &Kind,
4211 Expr **Args, unsigned NumArgs) {
4212 if (SequenceKind != FailedSequence)
4213 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214
Douglas Gregord6542d82009-12-22 15:35:07 +00004215 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004216 switch (Failure) {
4217 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004218 // FIXME: Customize for the initialized entity?
4219 if (NumArgs == 0)
4220 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4221 << DestType.getNonReferenceType();
4222 else // FIXME: diagnostic below could be better!
4223 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4224 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004225 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226
Douglas Gregor20093b42009-12-09 23:02:17 +00004227 case FK_ArrayNeedsInitList:
4228 case FK_ArrayNeedsInitListOrStringLiteral:
4229 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4230 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4231 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004233 case FK_ArrayTypeMismatch:
4234 case FK_NonConstantArrayInit:
4235 S.Diag(Kind.getLocation(),
4236 (Failure == FK_ArrayTypeMismatch
4237 ? diag::err_array_init_different_type
4238 : diag::err_array_init_non_constant_array))
4239 << DestType.getNonReferenceType()
4240 << Args[0]->getType()
4241 << Args[0]->getSourceRange();
4242 break;
4243
John McCall6bb80172010-03-30 21:47:33 +00004244 case FK_AddressOfOverloadFailed: {
4245 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004247 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004248 true,
4249 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004250 break;
John McCall6bb80172010-03-30 21:47:33 +00004251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004252
Douglas Gregor20093b42009-12-09 23:02:17 +00004253 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004254 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004255 switch (FailedOverloadResult) {
4256 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004257 if (Failure == FK_UserConversionOverloadFailed)
4258 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4259 << Args[0]->getType() << DestType
4260 << Args[0]->getSourceRange();
4261 else
4262 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4263 << DestType << Args[0]->getType()
4264 << Args[0]->getSourceRange();
4265
John McCall120d63c2010-08-24 20:38:10 +00004266 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004267 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004268
Douglas Gregor20093b42009-12-09 23:02:17 +00004269 case OR_No_Viable_Function:
4270 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4271 << Args[0]->getType() << DestType.getNonReferenceType()
4272 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004273 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004274 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275
Douglas Gregor20093b42009-12-09 23:02:17 +00004276 case OR_Deleted: {
4277 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4278 << Args[0]->getType() << DestType.getNonReferenceType()
4279 << Args[0]->getSourceRange();
4280 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004281 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004282 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4283 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004284 if (Ovl == OR_Deleted) {
4285 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4286 << Best->Function->isDeleted();
4287 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004288 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004289 }
4290 break;
4291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregor20093b42009-12-09 23:02:17 +00004293 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004294 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004295 break;
4296 }
4297 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298
Douglas Gregor20093b42009-12-09 23:02:17 +00004299 case FK_NonConstLValueReferenceBindingToTemporary:
4300 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004302 Failure == FK_NonConstLValueReferenceBindingToTemporary
4303 ? diag::err_lvalue_reference_bind_to_temporary
4304 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004305 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004306 << DestType.getNonReferenceType()
4307 << Args[0]->getType()
4308 << Args[0]->getSourceRange();
4309 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004310
Douglas Gregor20093b42009-12-09 23:02:17 +00004311 case FK_RValueReferenceBindingToLValue:
4312 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004313 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004314 << Args[0]->getSourceRange();
4315 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Douglas Gregor20093b42009-12-09 23:02:17 +00004317 case FK_ReferenceInitDropsQualifiers:
4318 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4319 << DestType.getNonReferenceType()
4320 << Args[0]->getType()
4321 << Args[0]->getSourceRange();
4322 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Douglas Gregor20093b42009-12-09 23:02:17 +00004324 case FK_ReferenceInitFailed:
4325 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4326 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004327 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004328 << Args[0]->getType()
4329 << Args[0]->getSourceRange();
4330 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004331
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004332 case FK_ConversionFailed: {
4333 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004334 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4335 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004336 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004337 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004338 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004339 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004340 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004341 }
John Wiegley429bb272011-04-08 18:41:53 +00004342
4343 case FK_ConversionFromPropertyFailed:
4344 // No-op. This error has already been reported.
4345 break;
4346
Douglas Gregord87b61f2009-12-10 17:56:55 +00004347 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004348 SourceRange R;
4349
4350 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004351 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004352 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004354 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004355
Douglas Gregor19311e72010-09-08 21:40:08 +00004356 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4357 if (Kind.isCStyleOrFunctionalCast())
4358 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4359 << R;
4360 else
4361 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4362 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004363 break;
4364 }
4365
4366 case FK_ReferenceBindingToInitList:
4367 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4368 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4369 break;
4370
4371 case FK_InitListBadDestinationType:
4372 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4373 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4374 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375
Douglas Gregor51c56d62009-12-14 20:49:26 +00004376 case FK_ConstructorOverloadFailed: {
4377 SourceRange ArgsRange;
4378 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004379 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004380 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004381
Douglas Gregor51c56d62009-12-14 20:49:26 +00004382 // FIXME: Using "DestType" for the entity we're printing is probably
4383 // bad.
4384 switch (FailedOverloadResult) {
4385 case OR_Ambiguous:
4386 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4387 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004388 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4389 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004390 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004391
Douglas Gregor51c56d62009-12-14 20:49:26 +00004392 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004393 if (Kind.getKind() == InitializationKind::IK_Default &&
4394 (Entity.getKind() == InitializedEntity::EK_Base ||
4395 Entity.getKind() == InitializedEntity::EK_Member) &&
4396 isa<CXXConstructorDecl>(S.CurContext)) {
4397 // This is implicit default initialization of a member or
4398 // base within a constructor. If no viable function was
4399 // found, notify the user that she needs to explicitly
4400 // initialize this base/member.
4401 CXXConstructorDecl *Constructor
4402 = cast<CXXConstructorDecl>(S.CurContext);
4403 if (Entity.getKind() == InitializedEntity::EK_Base) {
4404 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4405 << Constructor->isImplicit()
4406 << S.Context.getTypeDeclType(Constructor->getParent())
4407 << /*base=*/0
4408 << Entity.getType();
4409
4410 RecordDecl *BaseDecl
4411 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4412 ->getDecl();
4413 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4414 << S.Context.getTagDeclType(BaseDecl);
4415 } else {
4416 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4417 << Constructor->isImplicit()
4418 << S.Context.getTypeDeclType(Constructor->getParent())
4419 << /*member=*/1
4420 << Entity.getName();
4421 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4422
4423 if (const RecordType *Record
4424 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004425 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004426 diag::note_previous_decl)
4427 << S.Context.getTagDeclType(Record->getDecl());
4428 }
4429 break;
4430 }
4431
Douglas Gregor51c56d62009-12-14 20:49:26 +00004432 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4433 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004434 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004435 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436
Douglas Gregor51c56d62009-12-14 20:49:26 +00004437 case OR_Deleted: {
4438 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4439 << true << DestType << ArgsRange;
4440 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004441 OverloadingResult Ovl
4442 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004443 if (Ovl == OR_Deleted) {
4444 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4445 << Best->Function->isDeleted();
4446 } else {
4447 llvm_unreachable("Inconsistent overload resolution?");
4448 }
4449 break;
4450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregor51c56d62009-12-14 20:49:26 +00004452 case OR_Success:
4453 llvm_unreachable("Conversion did not fail!");
4454 break;
4455 }
4456 break;
4457 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458
Douglas Gregor99a2e602009-12-16 01:38:02 +00004459 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004460 if (Entity.getKind() == InitializedEntity::EK_Member &&
4461 isa<CXXConstructorDecl>(S.CurContext)) {
4462 // This is implicit default-initialization of a const member in
4463 // a constructor. Complain that it needs to be explicitly
4464 // initialized.
4465 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4466 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4467 << Constructor->isImplicit()
4468 << S.Context.getTypeDeclType(Constructor->getParent())
4469 << /*const=*/1
4470 << Entity.getName();
4471 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4472 << Entity.getName();
4473 } else {
4474 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4475 << DestType << (bool)DestType->getAs<RecordType>();
4476 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004477 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004478
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004479 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004481 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Douglas Gregora41a8c52010-04-22 00:20:18 +00004485 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004486 return true;
4487}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004488
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004489void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4490 switch (SequenceKind) {
4491 case FailedSequence: {
4492 OS << "Failed sequence: ";
4493 switch (Failure) {
4494 case FK_TooManyInitsForReference:
4495 OS << "too many initializers for reference";
4496 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004498 case FK_ArrayNeedsInitList:
4499 OS << "array requires initializer list";
4500 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004501
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004502 case FK_ArrayNeedsInitListOrStringLiteral:
4503 OS << "array requires initializer list or string literal";
4504 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004505
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004506 case FK_ArrayTypeMismatch:
4507 OS << "array type mismatch";
4508 break;
4509
4510 case FK_NonConstantArrayInit:
4511 OS << "non-constant array initializer";
4512 break;
4513
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004514 case FK_AddressOfOverloadFailed:
4515 OS << "address of overloaded function failed";
4516 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004517
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004518 case FK_ReferenceInitOverloadFailed:
4519 OS << "overload resolution for reference initialization failed";
4520 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004522 case FK_NonConstLValueReferenceBindingToTemporary:
4523 OS << "non-const lvalue reference bound to temporary";
4524 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004526 case FK_NonConstLValueReferenceBindingToUnrelated:
4527 OS << "non-const lvalue reference bound to unrelated type";
4528 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004529
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004530 case FK_RValueReferenceBindingToLValue:
4531 OS << "rvalue reference bound to an lvalue";
4532 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004534 case FK_ReferenceInitDropsQualifiers:
4535 OS << "reference initialization drops qualifiers";
4536 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004538 case FK_ReferenceInitFailed:
4539 OS << "reference initialization failed";
4540 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004542 case FK_ConversionFailed:
4543 OS << "conversion failed";
4544 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
John Wiegley429bb272011-04-08 18:41:53 +00004546 case FK_ConversionFromPropertyFailed:
4547 OS << "conversion from property failed";
4548 break;
4549
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004550 case FK_TooManyInitsForScalar:
4551 OS << "too many initializers for scalar";
4552 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004553
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004554 case FK_ReferenceBindingToInitList:
4555 OS << "referencing binding to initializer list";
4556 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004557
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004558 case FK_InitListBadDestinationType:
4559 OS << "initializer list for non-aggregate, non-scalar type";
4560 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004561
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004562 case FK_UserConversionOverloadFailed:
4563 OS << "overloading failed for user-defined conversion";
4564 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004566 case FK_ConstructorOverloadFailed:
4567 OS << "constructor overloading failed";
4568 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004569
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004570 case FK_DefaultInitOfConst:
4571 OS << "default initialization of a const variable";
4572 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004574 case FK_Incomplete:
4575 OS << "initialization of incomplete type";
4576 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004578 OS << '\n';
4579 return;
4580 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004581
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004582 case DependentSequence:
4583 OS << "Dependent sequence: ";
4584 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004585
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004586 case UserDefinedConversion:
4587 OS << "User-defined conversion sequence: ";
4588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004589
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004590 case ConstructorInitialization:
4591 OS << "Constructor initialization sequence: ";
4592 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004593
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004594 case ReferenceBinding:
4595 OS << "Reference binding: ";
4596 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004597
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004598 case ListInitialization:
4599 OS << "List initialization: ";
4600 break;
4601
4602 case ZeroInitialization:
4603 OS << "Zero initialization\n";
4604 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004606 case NoInitialization:
4607 OS << "No initialization\n";
4608 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004609
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004610 case StandardConversion:
4611 OS << "Standard conversion: ";
4612 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004613
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004614 case CAssignment:
4615 OS << "C assignment: ";
4616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004617
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004618 case StringInit:
4619 OS << "String initialization: ";
4620 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004621
4622 case ArrayInit:
4623 OS << "Array initialization: ";
4624 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004625 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004626
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004627 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4628 if (S != step_begin()) {
4629 OS << " -> ";
4630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004631
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004632 switch (S->Kind) {
4633 case SK_ResolveAddressOfOverloadedFunction:
4634 OS << "resolve address of overloaded function";
4635 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004636
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004637 case SK_CastDerivedToBaseRValue:
4638 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640
Sebastian Redl906082e2010-07-20 04:20:21 +00004641 case SK_CastDerivedToBaseXValue:
4642 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4643 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004645 case SK_CastDerivedToBaseLValue:
4646 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4647 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004649 case SK_BindReference:
4650 OS << "bind reference to lvalue";
4651 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004653 case SK_BindReferenceToTemporary:
4654 OS << "bind reference to a temporary";
4655 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004656
Douglas Gregor523d46a2010-04-18 07:40:54 +00004657 case SK_ExtraneousCopyToTemporary:
4658 OS << "extraneous C++03 copy to temporary";
4659 break;
4660
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004661 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004662 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004663 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004664
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004665 case SK_QualificationConversionRValue:
4666 OS << "qualification conversion (rvalue)";
4667
Sebastian Redl906082e2010-07-20 04:20:21 +00004668 case SK_QualificationConversionXValue:
4669 OS << "qualification conversion (xvalue)";
4670
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004671 case SK_QualificationConversionLValue:
4672 OS << "qualification conversion (lvalue)";
4673 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004674
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004675 case SK_ConversionSequence:
4676 OS << "implicit conversion sequence (";
4677 S->ICS->DebugPrint(); // FIXME: use OS
4678 OS << ")";
4679 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004681 case SK_ListInitialization:
4682 OS << "list initialization";
4683 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004685 case SK_ConstructorInitialization:
4686 OS << "constructor initialization";
4687 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004689 case SK_ZeroInitialization:
4690 OS << "zero initialization";
4691 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004692
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004693 case SK_CAssignment:
4694 OS << "C assignment";
4695 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004697 case SK_StringInit:
4698 OS << "string initialization";
4699 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004700
4701 case SK_ObjCObjectConversion:
4702 OS << "Objective-C object conversion";
4703 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004704
4705 case SK_ArrayInit:
4706 OS << "array initialization";
4707 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004708 }
4709 }
4710}
4711
4712void InitializationSequence::dump() const {
4713 dump(llvm::errs());
4714}
4715
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004716//===----------------------------------------------------------------------===//
4717// Initialization helper functions
4718//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004720Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4721 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004722 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004723 if (Init.isInvalid())
4724 return ExprError();
4725
John McCall15d7d122010-11-11 03:21:53 +00004726 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004727 assert(InitE && "No initialization expression?");
4728
4729 if (EqualLoc.isInvalid())
4730 EqualLoc = InitE->getLocStart();
4731
4732 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4733 EqualLoc);
4734 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4735 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004736 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004737}