blob: 358e5fb5015d8100e34a818c2a5e6e558b7adff5 [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 Friedman8718a6a2009-05-29 18:22:49 +000095 // C99 6.7.8p14. We have an array of character type with known size. However,
96 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
98 if (StrLength-1 > CAT->getSize().getZExtValue())
99 S.Diag(Str->getSourceRange().getBegin(),
100 diag::warn_initializer_string_for_char_array_too_long)
101 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 // Set the type to the actual size that we are initializing. If we have
104 // something like:
105 // char x[1] = "foo";
106 // then this will set the string literal's type to char[1].
107 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108}
109
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110//===----------------------------------------------------------------------===//
111// Semantic checking for initializer lists.
112//===----------------------------------------------------------------------===//
113
Douglas Gregor9e80f722009-01-29 01:05:33 +0000114/// @brief Semantic checking for initializer lists.
115///
116/// The InitListChecker class contains a set of routines that each
117/// handle the initialization of a certain kind of entity, e.g.,
118/// arrays, vectors, struct/union types, scalars, etc. The
119/// InitListChecker itself performs a recursive walk of the subobject
120/// structure of the type to be initialized, while stepping through
121/// the initializer list one element at a time. The IList and Index
122/// parameters to each of the Check* routines contain the active
123/// (syntactic) initializer list and the index into that initializer
124/// list that represents the current initializer. Each routine is
125/// responsible for moving that Index forward as it consumes elements.
126///
127/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000128/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000129/// initializer list and the index into that initializer list where we
130/// are copying initializers as we map them over to the semantic
131/// list. Once we have completed our recursive walk of the subobject
132/// structure, we will have constructed a full semantic initializer
133/// list.
134///
135/// C99 designators cause changes in the initializer list traversal,
136/// because they make the initialization "jump" into a specific
137/// subobject and then continue the initialization from that
138/// point. CheckDesignatedInitializer() recursively steps into the
139/// designated subobject and manages backing out the recursion to
140/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000141namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000142class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000143 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000144 bool hadError;
145 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
146 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000148 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000149 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000153 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000155 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000156 unsigned &StructuredIndex,
157 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000158 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000159 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000160 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000161 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000162 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000163 unsigned &StructuredIndex,
164 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000165 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000170 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000171 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckReferenceType(const InitializedEntity &Entity,
176 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000177 unsigned &Index,
178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000182 InitListExpr *StructuredList,
183 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000184 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000185 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000186 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000187 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000191 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000192 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000193 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000194 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000197 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000198 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000199 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000200 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000201 RecordDecl::field_iterator *NextField,
202 llvm::APSInt *NextElementIndex,
203 unsigned &Index,
204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000206 bool FinishSubobjectInit,
207 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000208 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
209 QualType CurrentObjectType,
210 InitListExpr *StructuredList,
211 unsigned StructuredIndex,
212 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000213 void UpdateStructuredListElement(InitListExpr *StructuredList,
214 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000215 Expr *expr);
216 int numArrayElements(QualType DeclType);
217 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000218
Douglas Gregord6d37de2009-12-22 00:05:34 +0000219 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
220 const InitializedEntity &ParentEntity,
221 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000222 void FillInValueInitializations(const InitializedEntity &Entity,
223 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000224public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000225 InitListChecker(Sema &S, const InitializedEntity &Entity,
226 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000227 bool HadError() { return hadError; }
228
229 // @brief Retrieves the fully-structured initializer list used for
230 // semantic analysis and code generation.
231 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
232};
Chris Lattner8b419b92009-02-24 22:48:58 +0000233} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000234
Douglas Gregord6d37de2009-12-22 00:05:34 +0000235void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
236 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000237 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000238 bool &RequiresSecondPass) {
239 SourceLocation Loc = ILE->getSourceRange().getBegin();
240 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000241 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000242 = InitializedEntity::InitializeMember(Field, &ParentEntity);
243 if (Init >= NumInits || !ILE->getInit(Init)) {
244 // FIXME: We probably don't need to handle references
245 // specially here, since value-initialization of references is
246 // handled in InitializationSequence.
247 if (Field->getType()->isReferenceType()) {
248 // C++ [dcl.init.aggr]p9:
249 // If an incomplete or empty initializer-list leaves a
250 // member of reference type uninitialized, the program is
251 // ill-formed.
252 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
253 << Field->getType()
254 << ILE->getSyntacticForm()->getSourceRange();
255 SemaRef.Diag(Field->getLocation(),
256 diag::note_uninit_reference_member);
257 hadError = true;
258 return;
259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000260
Douglas Gregord6d37de2009-12-22 00:05:34 +0000261 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
262 true);
263 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
264 if (!InitSeq) {
265 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
266 hadError = true;
267 return;
268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000269
John McCall60d7b3a2010-08-24 06:29:42 +0000270 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000271 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000272 if (MemberInit.isInvalid()) {
273 hadError = true;
274 return;
275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276
Douglas Gregord6d37de2009-12-22 00:05:34 +0000277 if (hadError) {
278 // Do nothing
279 } else if (Init < NumInits) {
280 ILE->setInit(Init, MemberInit.takeAs<Expr>());
281 } else if (InitSeq.getKind()
282 == InitializationSequence::ConstructorInitialization) {
283 // Value-initialization requires a constructor call, so
284 // extend the initializer list to include the constructor
285 // call and make a note that we'll need to take another pass
286 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000287 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000288 RequiresSecondPass = true;
289 }
290 } else if (InitListExpr *InnerILE
291 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 FillInValueInitializations(MemberEntity, InnerILE,
293 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294}
295
Douglas Gregor4c678342009-01-28 21:54:33 +0000296/// Recursively replaces NULL values within the given initializer list
297/// with expressions that perform value-initialization of the
298/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000299void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000300InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
301 InitListExpr *ILE,
302 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000303 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000304 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000305 SourceLocation Loc = ILE->getSourceRange().getBegin();
306 if (ILE->getSyntacticForm())
307 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Ted Kremenek6217b802009-07-29 21:53:49 +0000309 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000310 if (RType->getDecl()->isUnion() &&
311 ILE->getInitializedFieldInUnion())
312 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
313 Entity, ILE, RequiresSecondPass);
314 else {
315 unsigned Init = 0;
316 for (RecordDecl::field_iterator
317 Field = RType->getDecl()->field_begin(),
318 FieldEnd = RType->getDecl()->field_end();
319 Field != FieldEnd; ++Field) {
320 if (Field->isUnnamedBitfield())
321 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000322
Douglas Gregord6d37de2009-12-22 00:05:34 +0000323 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325
326 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
327 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000328 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000329
Douglas Gregord6d37de2009-12-22 00:05:34 +0000330 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000331
Douglas Gregord6d37de2009-12-22 00:05:34 +0000332 // Only look at the first initialization of a union.
333 if (RType->getDecl()->isUnion())
334 break;
335 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000336 }
337
338 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000339 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000340
341 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000343 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000344 unsigned NumInits = ILE->getNumInits();
345 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000346 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000347 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000348 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
349 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000352 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000354 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000356 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000357 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000358 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000360
Douglas Gregor87fd7032009-02-02 17:43:21 +0000361 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000362 if (hadError)
363 return;
364
Anders Carlssond3d824d2010-01-23 04:34:47 +0000365 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
366 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367 ElementEntity.setElementIndex(Init);
368
Douglas Gregor87fd7032009-02-02 17:43:21 +0000369 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000370 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
371 true);
372 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
373 if (!InitSeq) {
374 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000375 hadError = true;
376 return;
377 }
378
John McCall60d7b3a2010-08-24 06:29:42 +0000379 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000380 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000382 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000383 return;
384 }
385
386 if (hadError) {
387 // Do nothing
388 } else if (Init < NumInits) {
389 ILE->setInit(Init, ElementInit.takeAs<Expr>());
390 } else if (InitSeq.getKind()
391 == InitializationSequence::ConstructorInitialization) {
392 // Value-initialization requires a constructor call, so
393 // extend the initializer list to include the constructor
394 // call and make a note that we'll need to take another pass
395 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000396 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 RequiresSecondPass = true;
398 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000399 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000400 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
401 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000402 }
403}
404
Chris Lattner68355a52009-01-29 05:10:57 +0000405
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000406InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
407 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000408 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000409 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000410
Eli Friedmanb85f7072008-05-19 19:16:24 +0000411 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000412 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000413 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000414 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000415 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000416 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000417 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000418
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 if (!hadError) {
420 bool RequiresSecondPass = false;
421 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000422 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000424 RequiresSecondPass);
425 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000426}
427
428int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000429 // FIXME: use a proper constant
430 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000431 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000432 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000433 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
434 }
435 return maxElements;
436}
437
438int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000439 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000440 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000441 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000442 Field = structDecl->field_begin(),
443 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000444 Field != FieldEnd; ++Field) {
445 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
446 ++InitializableMembers;
447 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000448 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000449 return std::min(InitializableMembers, 1);
450 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000451}
452
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000453void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000454 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000455 QualType T, unsigned &Index,
456 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000457 unsigned &StructuredIndex,
458 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff0cca7492008-05-01 22:18:59 +0000461 if (T->isArrayType())
462 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000463 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000464 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000465 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000466 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000467 else
468 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000469
Eli Friedman402256f2008-05-25 13:49:22 +0000470 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000471 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000472 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000474 hadError = true;
475 return;
476 }
477
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 // Build a structured initializer list corresponding to this subobject.
479 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000480 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
481 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000482 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
483 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000485
Douglas Gregor4c678342009-01-28 21:54:33 +0000486 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000487 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000489 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000490 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000491 StructuredSubobjectInitIndex,
492 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000493 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000494 StructuredSubobjectInitList->setType(T);
495
Douglas Gregored8a93d2009-03-01 17:12:46 +0000496 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000497 // range corresponds with the end of the last initializer it used.
498 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000499 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000500 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
501 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000503
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000504 // Warn about missing braces.
505 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000506 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
507 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000508 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000509 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000510 "{")
511 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000512 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000513 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000514 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000515}
516
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000517void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000518 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 unsigned &Index,
520 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000521 unsigned &StructuredIndex,
522 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000523 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000524 SyntacticToSemantic[IList] = StructuredList;
525 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000527 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000528 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
529 IList->setType(ExprTy);
530 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (hadError)
532 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000533
Eli Friedman638e1442008-05-25 13:22:35 +0000534 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000535 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (StructuredIndex == 1 &&
537 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000538 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000539 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000540 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000541 hadError = true;
542 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000543 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000544 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000545 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000546 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000547 // Don't complain for incomplete types, since we'll get an error
548 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000549 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000550 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000551 CurrentObjectType->isArrayType()? 0 :
552 CurrentObjectType->isVectorType()? 1 :
553 CurrentObjectType->isScalarType()? 2 :
554 CurrentObjectType->isUnionType()? 3 :
555 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000556
557 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000558 if (SemaRef.getLangOptions().CPlusPlus) {
559 DK = diag::err_excess_initializers;
560 hadError = true;
561 }
Nate Begeman08634522009-07-07 21:53:06 +0000562 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
563 DK = diag::err_excess_initializers;
564 hadError = true;
565 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000566
Chris Lattner08202542009-02-24 22:50:46 +0000567 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000568 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000569 }
570 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000571
Eli Friedman759f2522009-05-16 11:45:48 +0000572 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000573 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000574 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000575 << FixItHint::CreateRemoval(IList->getLocStart())
576 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000577}
578
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000579void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000580 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000581 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000582 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000585 unsigned &StructuredIndex,
586 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000588 CheckScalarType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000590 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000591 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000592 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000593 } else if (DeclType->isAggregateType()) {
594 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000595 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000596 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000597 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000598 StructuredList, StructuredIndex,
599 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000600 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000601 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000602 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000603 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000605 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000607 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000609 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
610 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000611 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000613 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000614 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000615 } else if (DeclType->isRecordType()) {
616 // C++ [dcl.init]p14:
617 // [...] If the class is an aggregate (8.5.1), and the initializer
618 // is a brace-enclosed list, see 8.5.1.
619 //
620 // Note: 8.5.1 is handled below; here, we diagnose the case where
621 // we have an initializer list and a destination type that is not
622 // an aggregate.
623 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000624 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000625 << DeclType << IList->getSourceRange();
626 hadError = true;
627 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000628 CheckReferenceType(Entity, IList, DeclType, Index,
629 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000630 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000631 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
632 << DeclType;
633 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000634 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000635 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
636 << DeclType;
637 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000638 }
639}
640
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000641void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000642 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000643 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000644 unsigned &Index,
645 InitListExpr *StructuredList,
646 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000647 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000648 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
649 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000650 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000651 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 = getStructuredSubobjectInit(IList, Index, ElemType,
653 StructuredList, StructuredIndex,
654 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000655 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000656 newStructuredList, newStructuredIndex);
657 ++StructuredIndex;
658 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000659 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000661 return CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000664 return CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
666 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000667
John McCallfef8b342011-02-21 07:57:55 +0000668 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
669 // arrayType can be incomplete if we're initializing a flexible
670 // array member. There's nothing we can do with the completed
671 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
John McCallfef8b342011-02-21 07:57:55 +0000673 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
674 CheckStringInit(Str, ElemType, arrayType, SemaRef);
675 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000676 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000677 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000678 }
John McCallfef8b342011-02-21 07:57:55 +0000679
680 // Fall through for subaggregate initialization.
681
682 } else if (SemaRef.getLangOptions().CPlusPlus) {
683 // C++ [dcl.init.aggr]p12:
684 // All implicit type conversions (clause 4) are considered when
685 // initializing the aggregate member with an ini- tializer from
686 // an initializer-list. If the initializer can initialize a
687 // member, the member is initialized. [...]
688
689 // FIXME: Better EqualLoc?
690 InitializationKind Kind =
691 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
692 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
693
694 if (Seq) {
695 ExprResult Result =
696 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
697 if (Result.isInvalid())
698 hadError = true;
699
700 UpdateStructuredListElement(StructuredList, StructuredIndex,
701 Result.takeAs<Expr>());
702 ++Index;
703 return;
704 }
705
706 // Fall through for subaggregate initialization
707 } else {
708 // C99 6.7.8p13:
709 //
710 // The initializer for a structure or union object that has
711 // automatic storage duration shall be either an initializer
712 // list as described below, or a single expression that has
713 // compatible structure or union type. In the latter case, the
714 // initial value of the object, including unnamed members, is
715 // that of the expression.
716 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
717 SemaRef.CheckSingleAssignmentConstraints(ElemType, expr)
718 == Sema::Compatible) {
719 SemaRef.DefaultFunctionArrayLvalueConversion(expr);
720 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
721 ++Index;
722 return;
723 }
724
725 // Fall through for subaggregate initialization
726 }
727
728 // C++ [dcl.init.aggr]p12:
729 //
730 // [...] Otherwise, if the member is itself a non-empty
731 // subaggregate, brace elision is assumed and the initializer is
732 // considered for the initialization of the first member of
733 // the subaggregate.
734 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
735 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
736 StructuredIndex);
737 ++StructuredIndex;
738 } else {
739 // We cannot initialize this element, so let
740 // PerformCopyInitialization produce the appropriate diagnostic.
741 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
742 SemaRef.Owned(expr));
743 hadError = true;
744 ++Index;
745 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000746 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000747}
748
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000749void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000750 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000751 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000752 InitListExpr *StructuredList,
753 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000754 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000755 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000756 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000757 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000758 ++Index;
759 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000760 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000761 }
John McCallb934c2d2010-11-11 00:46:36 +0000762
763 Expr *expr = IList->getInit(Index);
764 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
765 SemaRef.Diag(SubIList->getLocStart(),
766 diag::warn_many_braces_around_scalar_init)
767 << SubIList->getSourceRange();
768
769 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
770 StructuredIndex);
771 return;
772 } else if (isa<DesignatedInitExpr>(expr)) {
773 SemaRef.Diag(expr->getSourceRange().getBegin(),
774 diag::err_designator_for_scalar_init)
775 << DeclType << expr->getSourceRange();
776 hadError = true;
777 ++Index;
778 ++StructuredIndex;
779 return;
780 }
781
782 ExprResult Result =
783 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
784 SemaRef.Owned(expr));
785
786 Expr *ResultExpr = 0;
787
788 if (Result.isInvalid())
789 hadError = true; // types weren't compatible.
790 else {
791 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792
John McCallb934c2d2010-11-11 00:46:36 +0000793 if (ResultExpr != expr) {
794 // The type was promoted, update initializer list.
795 IList->setInit(Index, ResultExpr);
796 }
797 }
798 if (hadError)
799 ++StructuredIndex;
800 else
801 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
802 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000803}
804
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000805void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
806 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000807 unsigned &Index,
808 InitListExpr *StructuredList,
809 unsigned &StructuredIndex) {
810 if (Index < IList->getNumInits()) {
811 Expr *expr = IList->getInit(Index);
812 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000813 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 << DeclType << IList->getSourceRange();
815 hadError = true;
816 ++Index;
817 ++StructuredIndex;
818 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000819 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000820
John McCall60d7b3a2010-08-24 06:29:42 +0000821 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000822 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
823 SemaRef.Owned(expr));
824
825 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000826 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000827
828 expr = Result.takeAs<Expr>();
829 IList->setInit(Index, expr);
830
Douglas Gregor930d8b52009-01-30 22:09:00 +0000831 if (hadError)
832 ++StructuredIndex;
833 else
834 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
835 ++Index;
836 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000837 // FIXME: It would be wonderful if we could point at the actual member. In
838 // general, it would be useful to pass location information down the stack,
839 // so that we know the location (or decl) of the "current object" being
840 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000841 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000842 diag::err_init_reference_member_uninitialized)
843 << DeclType
844 << IList->getSourceRange();
845 hadError = true;
846 ++Index;
847 ++StructuredIndex;
848 return;
849 }
850}
851
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000852void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000853 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000854 unsigned &Index,
855 InitListExpr *StructuredList,
856 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000857 if (Index >= IList->getNumInits())
858 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000859
John McCall20e047a2010-10-30 00:11:39 +0000860 const VectorType *VT = DeclType->getAs<VectorType>();
861 unsigned maxElements = VT->getNumElements();
862 unsigned numEltsInit = 0;
863 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000864
John McCall20e047a2010-10-30 00:11:39 +0000865 if (!SemaRef.getLangOptions().OpenCL) {
866 // If the initializing element is a vector, try to copy-initialize
867 // instead of breaking it apart (which is doomed to failure anyway).
868 Expr *Init = IList->getInit(Index);
869 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
870 ExprResult Result =
871 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
872 SemaRef.Owned(Init));
873
874 Expr *ResultExpr = 0;
875 if (Result.isInvalid())
876 hadError = true; // types weren't compatible.
877 else {
878 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000879
John McCall20e047a2010-10-30 00:11:39 +0000880 if (ResultExpr != Init) {
881 // The type was promoted, update initializer list.
882 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000883 }
884 }
John McCall20e047a2010-10-30 00:11:39 +0000885 if (hadError)
886 ++StructuredIndex;
887 else
888 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
889 ++Index;
890 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
John McCall20e047a2010-10-30 00:11:39 +0000893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000895
John McCall20e047a2010-10-30 00:11:39 +0000896 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
897 // Don't attempt to go past the end of the init list
898 if (Index >= IList->getNumInits())
899 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000900
John McCall20e047a2010-10-30 00:11:39 +0000901 ElementEntity.setElementIndex(Index);
902 CheckSubElementType(ElementEntity, IList, elementType, Index,
903 StructuredList, StructuredIndex);
904 }
905 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000906 }
John McCall20e047a2010-10-30 00:11:39 +0000907
908 InitializedEntity ElementEntity =
909 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000910
John McCall20e047a2010-10-30 00:11:39 +0000911 // OpenCL initializers allows vectors to be constructed from vectors.
912 for (unsigned i = 0; i < maxElements; ++i) {
913 // Don't attempt to go past the end of the init list
914 if (Index >= IList->getNumInits())
915 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916
John McCall20e047a2010-10-30 00:11:39 +0000917 ElementEntity.setElementIndex(Index);
918
919 QualType IType = IList->getInit(Index)->getType();
920 if (!IType->isVectorType()) {
921 CheckSubElementType(ElementEntity, IList, elementType, Index,
922 StructuredList, StructuredIndex);
923 ++numEltsInit;
924 } else {
925 QualType VecType;
926 const VectorType *IVT = IType->getAs<VectorType>();
927 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000928
John McCall20e047a2010-10-30 00:11:39 +0000929 if (IType->isExtVectorType())
930 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
931 else
932 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000933 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000934 CheckSubElementType(ElementEntity, IList, VecType, Index,
935 StructuredList, StructuredIndex);
936 numEltsInit += numIElts;
937 }
938 }
939
940 // OpenCL requires all elements to be initialized.
941 if (numEltsInit != maxElements)
942 if (SemaRef.getLangOptions().OpenCL)
943 SemaRef.Diag(IList->getSourceRange().getBegin(),
944 diag::err_vector_incorrect_num_initializers)
945 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000946}
947
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000948void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000949 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000950 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000951 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000952 unsigned &Index,
953 InitListExpr *StructuredList,
954 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +0000955 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
956
Steve Naroff0cca7492008-05-01 22:18:59 +0000957 // Check for the special-case of initializing an array with a string.
958 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +0000959 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +0000960 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +0000961 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000962 // We place the string literal directly into the resulting
963 // initializer list. This is the only place where the structure
964 // of the structured initializer list doesn't match exactly,
965 // because doing so would involve allocating one character
966 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000967 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000968 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000969 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000970 return;
971 }
972 }
John McCallce6c9b72011-02-21 07:22:22 +0000973 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000974 // Check for VLAs; in standard C it would be possible to check this
975 // earlier, but I don't know where clang accepts VLAs (gcc accepts
976 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000977 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000978 diag::err_variable_object_no_init)
979 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000980 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000981 ++Index;
982 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000983 return;
984 }
985
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000987 llvm::APSInt maxElements(elementIndex.getBitWidth(),
988 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000989 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +0000990 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000991 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +0000992 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000993 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994 maxElementsKnown = true;
995 }
996
John McCallce6c9b72011-02-21 07:22:22 +0000997 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000998 while (Index < IList->getNumInits()) {
999 Expr *Init = IList->getInit(Index);
1000 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001001 // If we're not the subobject that matches up with the '{' for
1002 // the designator, we shouldn't be handling the
1003 // designator. Return immediately.
1004 if (!SubobjectIsDesignatorContext)
1005 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001006
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001007 // Handle this designated initializer. elementIndex will be
1008 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001009 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001010 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001011 StructuredList, StructuredIndex, true,
1012 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001013 hadError = true;
1014 continue;
1015 }
1016
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001017 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001018 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001019 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001020 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001021 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001022
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001023 // If the array is of incomplete type, keep track of the number of
1024 // elements in the initializer.
1025 if (!maxElementsKnown && elementIndex > maxElements)
1026 maxElements = elementIndex;
1027
Douglas Gregor05c13a32009-01-22 00:58:24 +00001028 continue;
1029 }
1030
1031 // If we know the maximum number of elements, and we've already
1032 // hit it, stop consuming elements in the initializer list.
1033 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001034 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001035
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001036 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001038 Entity);
1039 // Check this element.
1040 CheckSubElementType(ElementEntity, IList, elementType, Index,
1041 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001042 ++elementIndex;
1043
1044 // If the array is of incomplete type, keep track of the number of
1045 // elements in the initializer.
1046 if (!maxElementsKnown && elementIndex > maxElements)
1047 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001048 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001049 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001050 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001051 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001052 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001053 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001054 // Sizing an array implicitly to zero is not allowed by ISO C,
1055 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001056 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001057 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001058 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001059
Mike Stump1eb44332009-09-09 15:08:12 +00001060 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001061 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001062 }
1063}
1064
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001065void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001066 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001067 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001068 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001069 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001070 unsigned &Index,
1071 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001072 unsigned &StructuredIndex,
1073 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001074 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Eli Friedmanb85f7072008-05-19 19:16:24 +00001076 // If the record is invalid, some of it's members are invalid. To avoid
1077 // confusion, we forgo checking the intializer for the entire record.
1078 if (structDecl->isInvalidDecl()) {
1079 hadError = true;
1080 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001081 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001082
1083 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1084 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001086 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001087 Field != FieldEnd; ++Field) {
1088 if (Field->getDeclName()) {
1089 StructuredList->setInitializedFieldInUnion(*Field);
1090 break;
1091 }
1092 }
1093 return;
1094 }
1095
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 // If structDecl is a forward declaration, this loop won't do
1097 // anything except look at designated initializers; That's okay,
1098 // because an error should get printed out elsewhere. It might be
1099 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001100 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001101 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001102 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001103 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001104 while (Index < IList->getNumInits()) {
1105 Expr *Init = IList->getInit(Index);
1106
1107 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001108 // If we're not the subobject that matches up with the '{' for
1109 // the designator, we shouldn't be handling the
1110 // designator. Return immediately.
1111 if (!SubobjectIsDesignatorContext)
1112 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001113
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001114 // Handle this designated initializer. Field will be updated to
1115 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001116 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001117 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001118 StructuredList, StructuredIndex,
1119 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001120 hadError = true;
1121
Douglas Gregordfb5e592009-02-12 19:00:39 +00001122 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001123
1124 // Disable check for missing fields when designators are used.
1125 // This matches gcc behaviour.
1126 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001127 continue;
1128 }
1129
1130 if (Field == FieldEnd) {
1131 // We've run out of fields. We're done.
1132 break;
1133 }
1134
Douglas Gregordfb5e592009-02-12 19:00:39 +00001135 // We've already initialized a member of a union. We're done.
1136 if (InitializedSomething && DeclType->isUnionType())
1137 break;
1138
Douglas Gregor44b43212008-12-11 16:49:14 +00001139 // If we've hit the flexible array member at the end, we're done.
1140 if (Field->getType()->isIncompleteArrayType())
1141 break;
1142
Douglas Gregor0bb76892009-01-29 16:53:55 +00001143 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001144 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001145 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001146 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001147 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001148
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001149 InitializedEntity MemberEntity =
1150 InitializedEntity::InitializeMember(*Field, &Entity);
1151 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1152 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001153 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001154
1155 if (DeclType->isUnionType()) {
1156 // Initialize the first field within the union.
1157 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001158 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001159
1160 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001161 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001162
John McCall80639de2010-03-11 19:32:38 +00001163 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001164 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001165 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1166 // It is possible we have one or more unnamed bitfields remaining.
1167 // Find first (if any) named field and emit warning.
1168 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1169 it != end; ++it) {
1170 if (!it->isUnnamedBitfield()) {
1171 SemaRef.Diag(IList->getSourceRange().getEnd(),
1172 diag::warn_missing_field_initializers) << it->getName();
1173 break;
1174 }
1175 }
1176 }
1177
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001179 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001180 return;
1181
1182 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001183 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001184 (!isa<InitListExpr>(IList->getInit(Index)) ||
1185 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001186 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001187 diag::err_flexible_array_init_nonempty)
1188 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001189 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001190 << *Field;
1191 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001192 ++Index;
1193 return;
1194 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001195 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001196 diag::ext_flexible_array_init)
1197 << IList->getInit(Index)->getSourceRange().getBegin();
1198 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1199 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001200 }
1201
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001202 InitializedEntity MemberEntity =
1203 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001205 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001206 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001207 StructuredList, StructuredIndex);
1208 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001210 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001211}
Steve Naroff0cca7492008-05-01 22:18:59 +00001212
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001213/// \brief Expand a field designator that refers to a member of an
1214/// anonymous struct or union into a series of field designators that
1215/// refers to the field within the appropriate subobject.
1216///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001217static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001218 DesignatedInitExpr *DIE,
1219 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001220 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001221 typedef DesignatedInitExpr::Designator Designator;
1222
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001223 // Build the replacement designators.
1224 llvm::SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001225 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1226 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1227 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001229 DIE->getDesignator(DesigIdx)->getDotLoc(),
1230 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1231 else
1232 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1233 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001234 assert(isa<FieldDecl>(*PI));
1235 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001236 }
1237
1238 // Expand the current designator into the set of replacement
1239 // designators, so we have a full subobject path down to where the
1240 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001241 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001242 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001243}
Mike Stump1eb44332009-09-09 15:08:12 +00001244
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001245/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001246/// corresponds to FieldName.
1247static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1248 IdentifierInfo *FieldName) {
1249 assert(AnonField->isAnonymousStructOrUnion());
1250 Decl *NextDecl = AnonField->getNextDeclInContext();
1251 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1252 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1253 return IF;
1254 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001255 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001256 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001257}
1258
Douglas Gregor05c13a32009-01-22 00:58:24 +00001259/// @brief Check the well-formedness of a C99 designated initializer.
1260///
1261/// Determines whether the designated initializer @p DIE, which
1262/// resides at the given @p Index within the initializer list @p
1263/// IList, is well-formed for a current object of type @p DeclType
1264/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001265/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001266/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001267///
1268/// @param IList The initializer list in which this designated
1269/// initializer occurs.
1270///
Douglas Gregor71199712009-04-15 04:56:10 +00001271/// @param DIE The designated initializer expression.
1272///
1273/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001274///
1275/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1276/// into which the designation in @p DIE should refer.
1277///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001278/// @param NextField If non-NULL and the first designator in @p DIE is
1279/// a field, this will be set to the field declaration corresponding
1280/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001281///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001282/// @param NextElementIndex If non-NULL and the first designator in @p
1283/// DIE is an array designator or GNU array-range designator, this
1284/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001285///
1286/// @param Index Index into @p IList where the designated initializer
1287/// @p DIE occurs.
1288///
Douglas Gregor4c678342009-01-28 21:54:33 +00001289/// @param StructuredList The initializer list expression that
1290/// describes all of the subobject initializers in the order they'll
1291/// actually be initialized.
1292///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001293/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001294bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001295InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001296 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001297 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001298 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001299 QualType &CurrentObjectType,
1300 RecordDecl::field_iterator *NextField,
1301 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 unsigned &Index,
1303 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001304 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001305 bool FinishSubobjectInit,
1306 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001307 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 // Check the actual initialization for the designated object type.
1309 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001310
1311 // Temporarily remove the designator expression from the
1312 // initializer list that the child calls see, so that we don't try
1313 // to re-process the designator.
1314 unsigned OldIndex = Index;
1315 IList->setInit(OldIndex, DIE->getInit());
1316
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001317 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001319
1320 // Restore the designated initializer expression in the syntactic
1321 // form of the initializer list.
1322 if (IList->getInit(OldIndex) != DIE->getInit())
1323 DIE->setInit(IList->getInit(OldIndex));
1324 IList->setInit(OldIndex, DIE);
1325
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001326 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001327 }
1328
Douglas Gregor71199712009-04-15 04:56:10 +00001329 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001330 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001331 "Need a non-designated initializer list to start from");
1332
Douglas Gregor71199712009-04-15 04:56:10 +00001333 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 // Determine the structural initializer list that corresponds to the
1335 // current subobject.
1336 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001337 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001338 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001339 SourceRange(D->getStartLocation(),
1340 DIE->getSourceRange().getEnd()));
1341 assert(StructuredList && "Expected a structured initializer list");
1342
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343 if (D->isFieldDesignator()) {
1344 // C99 6.7.8p7:
1345 //
1346 // If a designator has the form
1347 //
1348 // . identifier
1349 //
1350 // then the current object (defined below) shall have
1351 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001352 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001353 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001354 if (!RT) {
1355 SourceLocation Loc = D->getDotLoc();
1356 if (Loc.isInvalid())
1357 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001358 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1359 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 ++Index;
1361 return true;
1362 }
1363
Douglas Gregor4c678342009-01-28 21:54:33 +00001364 // Note: we perform a linear search of the fields here, despite
1365 // the fact that we have a faster lookup method, because we always
1366 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001367 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001368 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001369 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001370 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001371 Field = RT->getDecl()->field_begin(),
1372 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001373 for (; Field != FieldEnd; ++Field) {
1374 if (Field->isUnnamedBitfield())
1375 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376
Francois Picheta0e27f02010-12-22 03:46:10 +00001377 // If we find a field representing an anonymous field, look in the
1378 // IndirectFieldDecl that follow for the designated initializer.
1379 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1380 if (IndirectFieldDecl *IF =
1381 FindIndirectFieldDesignator(*Field, FieldName)) {
1382 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1383 D = DIE->getDesignator(DesigIdx);
1384 break;
1385 }
1386 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001387 if (KnownField && KnownField == *Field)
1388 break;
1389 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001390 break;
1391
1392 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001393 }
1394
Douglas Gregor4c678342009-01-28 21:54:33 +00001395 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001396 // There was no normal field in the struct with the designated
1397 // name. Perform another lookup for this name, which may find
1398 // something that we can't designate (e.g., a member function),
1399 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001400 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001401 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001402 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001404 // Name lookup didn't find anything. Determine whether this
1405 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001406 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001407 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001408 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001410 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001411 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001412 ->Equals(RT->getDecl())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001414 diag::err_field_designator_unknown_suggest)
1415 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001416 << FixItHint::CreateReplacement(D->getFieldLoc(),
1417 R.getLookupName().getAsString());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001419 diag::note_previous_decl)
1420 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001421 } else {
1422 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1423 << FieldName << CurrentObjectType;
1424 ++Index;
1425 return true;
1426 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001427 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001429 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001431 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001432 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001433 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001434 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001435 ++Index;
1436 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001437 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001438
Francois Picheta0e27f02010-12-22 03:46:10 +00001439 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001440 // The replacement field comes from typo correction; find it
1441 // in the list of fields.
1442 FieldIndex = 0;
1443 Field = RT->getDecl()->field_begin();
1444 for (; Field != FieldEnd; ++Field) {
1445 if (Field->isUnnamedBitfield())
1446 continue;
1447
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001448 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001449 Field->getIdentifier() == ReplacementField->getIdentifier())
1450 break;
1451
1452 ++FieldIndex;
1453 }
1454 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001455 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001456
1457 // All of the fields of a union are located at the same place in
1458 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001459 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001460 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001461 StructuredList->setInitializedFieldInUnion(*Field);
1462 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001463
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001464 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001465 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Douglas Gregor4c678342009-01-28 21:54:33 +00001467 // Make sure that our non-designated initializer list has space
1468 // for a subobject corresponding to this field.
1469 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001470 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001471
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 // This designator names a flexible array member.
1473 if (Field->getType()->isIncompleteArrayType()) {
1474 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001475 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001476 // We can't designate an object within the flexible array
1477 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001478 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001479 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001480 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001481 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001482 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001483 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001484 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001485 << *Field;
1486 Invalid = true;
1487 }
1488
Chris Lattner9046c222010-10-10 17:49:49 +00001489 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1490 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001492 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001493 diag::err_flexible_array_init_needs_braces)
1494 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001495 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001496 << *Field;
1497 Invalid = true;
1498 }
1499
1500 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001501 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001502 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001503 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001504 diag::err_flexible_array_init_nonempty)
1505 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001506 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001507 << *Field;
1508 Invalid = true;
1509 }
1510
1511 if (Invalid) {
1512 ++Index;
1513 return true;
1514 }
1515
1516 // Initialize the array.
1517 bool prevHadError = hadError;
1518 unsigned newStructuredIndex = FieldIndex;
1519 unsigned OldIndex = Index;
1520 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001521
1522 InitializedEntity MemberEntity =
1523 InitializedEntity::InitializeMember(*Field, &Entity);
1524 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001525 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001526
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001527 IList->setInit(OldIndex, DIE);
1528 if (hadError && !prevHadError) {
1529 ++Field;
1530 ++FieldIndex;
1531 if (NextField)
1532 *NextField = Field;
1533 StructuredIndex = FieldIndex;
1534 return true;
1535 }
1536 } else {
1537 // Recurse to check later designated subobjects.
1538 QualType FieldType = (*Field)->getType();
1539 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001540
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001541 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001542 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001543 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1544 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001545 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001546 true, false))
1547 return true;
1548 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001549
1550 // Find the position of the next field to be initialized in this
1551 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001553 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001554
1555 // If this the first designator, our caller will continue checking
1556 // the rest of this struct/class/union subobject.
1557 if (IsFirstDesignator) {
1558 if (NextField)
1559 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001560 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 return false;
1562 }
1563
Douglas Gregor34e79462009-01-28 23:36:17 +00001564 if (!FinishSubobjectInit)
1565 return false;
1566
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001567 // We've already initialized something in the union; we're done.
1568 if (RT->getDecl()->isUnion())
1569 return hadError;
1570
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 // Check the remaining fields within this class/struct/union subobject.
1572 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001573
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001574 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001575 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576 return hadError && !prevHadError;
1577 }
1578
1579 // C99 6.7.8p6:
1580 //
1581 // If a designator has the form
1582 //
1583 // [ constant-expression ]
1584 //
1585 // then the current object (defined below) shall have array
1586 // type and the expression shall be an integer constant
1587 // expression. If the array is of unknown size, any
1588 // nonnegative value is valid.
1589 //
1590 // Additionally, cope with the GNU extension that permits
1591 // designators of the form
1592 //
1593 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001594 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001595 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001596 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 << CurrentObjectType;
1598 ++Index;
1599 return true;
1600 }
1601
1602 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001603 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1604 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001605 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001606 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001607 DesignatedEndIndex = DesignatedStartIndex;
1608 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001609 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001610
Mike Stump1eb44332009-09-09 15:08:12 +00001611 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001612 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001613 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001614 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001615 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001616
Chris Lattnere0fd8322011-02-19 22:28:58 +00001617 // Codegen can't handle evaluating array range designators that have side
1618 // effects, because we replicate the AST value for each initialized element.
1619 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1620 // elements with something that has a side effect, so codegen can emit an
1621 // "error unsupported" error instead of miscompiling the app.
1622 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1623 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001624 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625 }
1626
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001627 if (isa<ConstantArrayType>(AT)) {
1628 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001629 DesignatedStartIndex
1630 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001631 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001632 DesignatedEndIndex
1633 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001634 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1635 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001636 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001637 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001638 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001639 << IndexExpr->getSourceRange();
1640 ++Index;
1641 return true;
1642 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001643 } else {
1644 // Make sure the bit-widths and signedness match.
1645 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001646 DesignatedEndIndex
1647 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001648 else if (DesignatedStartIndex.getBitWidth() <
1649 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001650 DesignatedStartIndex
1651 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001652 DesignatedStartIndex.setIsUnsigned(true);
1653 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregor4c678342009-01-28 21:54:33 +00001656 // Make sure that our non-designated initializer list has space
1657 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001658 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001659 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001660 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001661
Douglas Gregor34e79462009-01-28 23:36:17 +00001662 // Repeatedly perform subobject initializations in the range
1663 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001664
Douglas Gregor34e79462009-01-28 23:36:17 +00001665 // Move to the next designator
1666 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1667 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001669 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001670 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001671
Douglas Gregor34e79462009-01-28 23:36:17 +00001672 while (DesignatedStartIndex <= DesignatedEndIndex) {
1673 // Recurse to check later designated subobjects.
1674 QualType ElementType = AT->getElementType();
1675 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001677 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1679 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001680 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001681 (DesignatedStartIndex == DesignatedEndIndex),
1682 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001683 return true;
1684
1685 // Move to the next index in the array that we'll be initializing.
1686 ++DesignatedStartIndex;
1687 ElementIndex = DesignatedStartIndex.getZExtValue();
1688 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001689
1690 // If this the first designator, our caller will continue checking
1691 // the rest of this array subobject.
1692 if (IsFirstDesignator) {
1693 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001694 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001695 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001696 return false;
1697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor34e79462009-01-28 23:36:17 +00001699 if (!FinishSubobjectInit)
1700 return false;
1701
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001702 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001703 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001705 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001706 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001707 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001708}
1709
Douglas Gregor4c678342009-01-28 21:54:33 +00001710// Get the structured initializer list for a subobject of type
1711// @p CurrentObjectType.
1712InitListExpr *
1713InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1714 QualType CurrentObjectType,
1715 InitListExpr *StructuredList,
1716 unsigned StructuredIndex,
1717 SourceRange InitRange) {
1718 Expr *ExistingInit = 0;
1719 if (!StructuredList)
1720 ExistingInit = SyntacticToSemantic[IList];
1721 else if (StructuredIndex < StructuredList->getNumInits())
1722 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregor4c678342009-01-28 21:54:33 +00001724 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1725 return Result;
1726
1727 if (ExistingInit) {
1728 // We are creating an initializer list that initializes the
1729 // subobjects of the current object, but there was already an
1730 // initialization that completely initialized the current
1731 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001732 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001733 // struct X { int a, b; };
1734 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001735 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1737 // designated initializer re-initializes the whole
1738 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001739 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001740 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001741 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001744 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001745 << ExistingInit->getSourceRange();
1746 }
1747
Mike Stump1eb44332009-09-09 15:08:12 +00001748 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001749 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1750 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001751 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001752
Douglas Gregor63982352010-07-13 18:40:04 +00001753 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001754
Douglas Gregorfa219202009-03-20 23:58:33 +00001755 // Pre-allocate storage for the structured initializer list.
1756 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001757 unsigned NumInits = 0;
1758 if (!StructuredList)
1759 NumInits = IList->getNumInits();
1760 else if (Index < IList->getNumInits()) {
1761 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1762 NumInits = SubList->getNumInits();
1763 }
1764
Mike Stump1eb44332009-09-09 15:08:12 +00001765 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001766 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1767 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1768 NumElements = CAType->getSize().getZExtValue();
1769 // Simple heuristic so that we don't allocate a very large
1770 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001771 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001772 NumElements = 0;
1773 }
John McCall183700f2009-09-21 23:43:11 +00001774 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001775 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001776 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001777 RecordDecl *RDecl = RType->getDecl();
1778 if (RDecl->isUnion())
1779 NumElements = 1;
1780 else
Mike Stump1eb44332009-09-09 15:08:12 +00001781 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001782 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001783 }
1784
Douglas Gregor08457732009-03-21 18:13:52 +00001785 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001786 NumElements = IList->getNumInits();
1787
Ted Kremenek709210f2010-04-13 23:39:13 +00001788 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001789
Douglas Gregor4c678342009-01-28 21:54:33 +00001790 // Link this new initializer list into the structured initializer
1791 // lists.
1792 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001793 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001794 else {
1795 Result->setSyntacticForm(IList);
1796 SyntacticToSemantic[IList] = Result;
1797 }
1798
1799 return Result;
1800}
1801
1802/// Update the initializer at index @p StructuredIndex within the
1803/// structured initializer list to the value @p expr.
1804void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1805 unsigned &StructuredIndex,
1806 Expr *expr) {
1807 // No structured initializer list to update
1808 if (!StructuredList)
1809 return;
1810
Ted Kremenek709210f2010-04-13 23:39:13 +00001811 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1812 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001813 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001814 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001815 diag::warn_initializer_overrides)
1816 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001817 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001818 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001819 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001820 << PrevInit->getSourceRange();
1821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregor4c678342009-01-28 21:54:33 +00001823 ++StructuredIndex;
1824}
1825
Douglas Gregor05c13a32009-01-22 00:58:24 +00001826/// Check that the given Index expression is a valid array designator
1827/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001828/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001829/// and produces a reasonable diagnostic if there is a
1830/// failure. Returns true if there was an error, false otherwise. If
1831/// everything went okay, Value will receive the value of the constant
1832/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001833static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001834CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 SourceLocation Loc = Index->getSourceRange().getBegin();
1836
1837 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001838 if (S.VerifyIntegerConstantExpression(Index, &Value))
1839 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001840
Chris Lattner3bf68932009-04-25 21:59:05 +00001841 if (Value.isSigned() && Value.isNegative())
1842 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001843 << Value.toString(10) << Index->getSourceRange();
1844
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001845 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001846 return false;
1847}
1848
John McCall60d7b3a2010-08-24 06:29:42 +00001849ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001850 SourceLocation Loc,
1851 bool GNUSyntax,
1852 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001853 typedef DesignatedInitExpr::Designator ASTDesignator;
1854
1855 bool Invalid = false;
1856 llvm::SmallVector<ASTDesignator, 32> Designators;
1857 llvm::SmallVector<Expr *, 32> InitExpressions;
1858
1859 // Build designators and check array designator expressions.
1860 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1861 const Designator &D = Desig.getDesignator(Idx);
1862 switch (D.getKind()) {
1863 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001864 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001865 D.getFieldLoc()));
1866 break;
1867
1868 case Designator::ArrayDesignator: {
1869 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1870 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001871 if (!Index->isTypeDependent() &&
1872 !Index->isValueDependent() &&
1873 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001874 Invalid = true;
1875 else {
1876 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001877 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001878 D.getRBracketLoc()));
1879 InitExpressions.push_back(Index);
1880 }
1881 break;
1882 }
1883
1884 case Designator::ArrayRangeDesignator: {
1885 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1886 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1887 llvm::APSInt StartValue;
1888 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001889 bool StartDependent = StartIndex->isTypeDependent() ||
1890 StartIndex->isValueDependent();
1891 bool EndDependent = EndIndex->isTypeDependent() ||
1892 EndIndex->isValueDependent();
1893 if ((!StartDependent &&
1894 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1895 (!EndDependent &&
1896 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001897 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001898 else {
1899 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001900 if (StartDependent || EndDependent) {
1901 // Nothing to compute.
1902 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001903 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001904 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001905 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001906
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001907 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001908 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001909 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001910 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1911 Invalid = true;
1912 } else {
1913 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001914 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001915 D.getEllipsisLoc(),
1916 D.getRBracketLoc()));
1917 InitExpressions.push_back(StartIndex);
1918 InitExpressions.push_back(EndIndex);
1919 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001920 }
1921 break;
1922 }
1923 }
1924 }
1925
1926 if (Invalid || Init.isInvalid())
1927 return ExprError();
1928
1929 // Clear out the expressions within the designation.
1930 Desig.ClearExprs(*this);
1931
1932 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001933 = DesignatedInitExpr::Create(Context,
1934 Designators.data(), Designators.size(),
1935 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001936 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001937
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001938 if (getLangOptions().CPlusPlus)
1939 Diag(DIE->getLocStart(), diag::ext_designated_init)
1940 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001941
Douglas Gregor05c13a32009-01-22 00:58:24 +00001942 return Owned(DIE);
1943}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001944
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001945bool Sema::CheckInitList(const InitializedEntity &Entity,
1946 InitListExpr *&InitList, QualType &DeclType) {
1947 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001948 if (!CheckInitList.HadError())
1949 InitList = CheckInitList.getFullyStructuredList();
1950
1951 return CheckInitList.HadError();
1952}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001953
Douglas Gregor20093b42009-12-09 23:02:17 +00001954//===----------------------------------------------------------------------===//
1955// Initialization entity
1956//===----------------------------------------------------------------------===//
1957
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001959 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001960 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001961{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001962 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1963 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001964 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001965 } else {
1966 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001967 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001968 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001969}
1970
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001971InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001972 CXXBaseSpecifier *Base,
1973 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001974{
1975 InitializedEntity Result;
1976 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001977 Result.Base = reinterpret_cast<uintptr_t>(Base);
1978 if (IsInheritedVirtualBase)
1979 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980
Douglas Gregord6542d82009-12-22 15:35:07 +00001981 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001982 return Result;
1983}
1984
Douglas Gregor99a2e602009-12-16 01:38:02 +00001985DeclarationName InitializedEntity::getName() const {
1986 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001987 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001988 if (!VariableOrMember)
1989 return DeclarationName();
1990 // Fall through
1991
1992 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001993 case EK_Member:
1994 return VariableOrMember->getDeclName();
1995
1996 case EK_Result:
1997 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001998 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001999 case EK_Temporary:
2000 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002001 case EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002002 case EK_ArrayElement:
2003 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002004 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002005 return DeclarationName();
2006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002007
Douglas Gregor99a2e602009-12-16 01:38:02 +00002008 // Silence GCC warning
2009 return DeclarationName();
2010}
2011
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002012DeclaratorDecl *InitializedEntity::getDecl() const {
2013 switch (getKind()) {
2014 case EK_Variable:
2015 case EK_Parameter:
2016 case EK_Member:
2017 return VariableOrMember;
2018
2019 case EK_Result:
2020 case EK_Exception:
2021 case EK_New:
2022 case EK_Temporary:
2023 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002024 case EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002025 case EK_ArrayElement:
2026 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002027 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002028 return 0;
2029 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002030
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002031 // Silence GCC warning
2032 return 0;
2033}
2034
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002035bool InitializedEntity::allowsNRVO() const {
2036 switch (getKind()) {
2037 case EK_Result:
2038 case EK_Exception:
2039 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002041 case EK_Variable:
2042 case EK_Parameter:
2043 case EK_Member:
2044 case EK_New:
2045 case EK_Temporary:
2046 case EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00002047 case EK_Delegation:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002048 case EK_ArrayElement:
2049 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002050 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002051 break;
2052 }
2053
2054 return false;
2055}
2056
Douglas Gregor20093b42009-12-09 23:02:17 +00002057//===----------------------------------------------------------------------===//
2058// Initialization sequence
2059//===----------------------------------------------------------------------===//
2060
2061void InitializationSequence::Step::Destroy() {
2062 switch (Kind) {
2063 case SK_ResolveAddressOfOverloadedFunction:
2064 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002065 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002066 case SK_CastDerivedToBaseLValue:
2067 case SK_BindReference:
2068 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002069 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002070 case SK_UserConversion:
2071 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002072 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002073 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002074 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002075 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002076 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002077 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002078 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002079 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002080 case SK_ArrayInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002081 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082
Douglas Gregor20093b42009-12-09 23:02:17 +00002083 case SK_ConversionSequence:
2084 delete ICS;
2085 }
2086}
2087
Douglas Gregorb70cf442010-03-26 20:14:36 +00002088bool InitializationSequence::isDirectReferenceBinding() const {
2089 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2090}
2091
2092bool InitializationSequence::isAmbiguous() const {
2093 if (getKind() != FailedSequence)
2094 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
Douglas Gregorb70cf442010-03-26 20:14:36 +00002096 switch (getFailureKind()) {
2097 case FK_TooManyInitsForReference:
2098 case FK_ArrayNeedsInitList:
2099 case FK_ArrayNeedsInitListOrStringLiteral:
2100 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2101 case FK_NonConstLValueReferenceBindingToTemporary:
2102 case FK_NonConstLValueReferenceBindingToUnrelated:
2103 case FK_RValueReferenceBindingToLValue:
2104 case FK_ReferenceInitDropsQualifiers:
2105 case FK_ReferenceInitFailed:
2106 case FK_ConversionFailed:
2107 case FK_TooManyInitsForScalar:
2108 case FK_ReferenceBindingToInitList:
2109 case FK_InitListBadDestinationType:
2110 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002111 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002112 case FK_ArrayTypeMismatch:
2113 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002114 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002115
Douglas Gregorb70cf442010-03-26 20:14:36 +00002116 case FK_ReferenceInitOverloadFailed:
2117 case FK_UserConversionOverloadFailed:
2118 case FK_ConstructorOverloadFailed:
2119 return FailedOverloadResult == OR_Ambiguous;
2120 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002121
Douglas Gregorb70cf442010-03-26 20:14:36 +00002122 return false;
2123}
2124
Douglas Gregord6e44a32010-04-16 22:09:46 +00002125bool InitializationSequence::isConstructorInitialization() const {
2126 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2127}
2128
Douglas Gregor20093b42009-12-09 23:02:17 +00002129void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002130 FunctionDecl *Function,
2131 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002132 Step S;
2133 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2134 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002135 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002136 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002137 Steps.push_back(S);
2138}
2139
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002141 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002142 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002143 switch (VK) {
2144 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2145 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2146 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002147 default: llvm_unreachable("No such category");
2148 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 S.Type = BaseType;
2150 Steps.push_back(S);
2151}
2152
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002154 bool BindingTemporary) {
2155 Step S;
2156 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2157 S.Type = T;
2158 Steps.push_back(S);
2159}
2160
Douglas Gregor523d46a2010-04-18 07:40:54 +00002161void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2162 Step S;
2163 S.Kind = SK_ExtraneousCopyToTemporary;
2164 S.Type = T;
2165 Steps.push_back(S);
2166}
2167
Eli Friedman03981012009-12-11 02:42:07 +00002168void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002169 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002170 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002171 Step S;
2172 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002173 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002174 S.Function.Function = Function;
2175 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002176 Steps.push_back(S);
2177}
2178
2179void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002180 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002181 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002182 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002183 switch (VK) {
2184 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002185 S.Kind = SK_QualificationConversionRValue;
2186 break;
John McCall5baba9d2010-08-25 10:28:54 +00002187 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002188 S.Kind = SK_QualificationConversionXValue;
2189 break;
John McCall5baba9d2010-08-25 10:28:54 +00002190 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002191 S.Kind = SK_QualificationConversionLValue;
2192 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002193 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002194 S.Type = Ty;
2195 Steps.push_back(S);
2196}
2197
2198void InitializationSequence::AddConversionSequenceStep(
2199 const ImplicitConversionSequence &ICS,
2200 QualType T) {
2201 Step S;
2202 S.Kind = SK_ConversionSequence;
2203 S.Type = T;
2204 S.ICS = new ImplicitConversionSequence(ICS);
2205 Steps.push_back(S);
2206}
2207
Douglas Gregord87b61f2009-12-10 17:56:55 +00002208void InitializationSequence::AddListInitializationStep(QualType T) {
2209 Step S;
2210 S.Kind = SK_ListInitialization;
2211 S.Type = T;
2212 Steps.push_back(S);
2213}
2214
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002215void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002216InitializationSequence::AddConstructorInitializationStep(
2217 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002218 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002219 QualType T) {
2220 Step S;
2221 S.Kind = SK_ConstructorInitialization;
2222 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002223 S.Function.Function = Constructor;
2224 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002225 Steps.push_back(S);
2226}
2227
Douglas Gregor71d17402009-12-15 00:01:57 +00002228void InitializationSequence::AddZeroInitializationStep(QualType T) {
2229 Step S;
2230 S.Kind = SK_ZeroInitialization;
2231 S.Type = T;
2232 Steps.push_back(S);
2233}
2234
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002235void InitializationSequence::AddCAssignmentStep(QualType T) {
2236 Step S;
2237 S.Kind = SK_CAssignment;
2238 S.Type = T;
2239 Steps.push_back(S);
2240}
2241
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002242void InitializationSequence::AddStringInitStep(QualType T) {
2243 Step S;
2244 S.Kind = SK_StringInit;
2245 S.Type = T;
2246 Steps.push_back(S);
2247}
2248
Douglas Gregor569c3162010-08-07 11:51:51 +00002249void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2250 Step S;
2251 S.Kind = SK_ObjCObjectConversion;
2252 S.Type = T;
2253 Steps.push_back(S);
2254}
2255
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002256void InitializationSequence::AddArrayInitStep(QualType T) {
2257 Step S;
2258 S.Kind = SK_ArrayInit;
2259 S.Type = T;
2260 Steps.push_back(S);
2261}
2262
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002264 OverloadingResult Result) {
2265 SequenceKind = FailedSequence;
2266 this->Failure = Failure;
2267 this->FailedOverloadResult = Result;
2268}
2269
2270//===----------------------------------------------------------------------===//
2271// Attempt initialization
2272//===----------------------------------------------------------------------===//
2273
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002274/// \brief Attempt list initialization (C++0x [dcl.init.list])
2275static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002276 const InitializedEntity &Entity,
2277 const InitializationKind &Kind,
2278 InitListExpr *InitList,
2279 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002280 // FIXME: We only perform rudimentary checking of list
2281 // initializations at this point, then assume that any list
2282 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002283 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002284 // do all of the necessary checking. C++0x initializer lists will
2285 // force us to perform more checking here.
2286 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2287
Douglas Gregord6542d82009-12-22 15:35:07 +00002288 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002289
2290 // C++ [dcl.init]p13:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002291 // If T is a scalar type, then a declaration of the form
Douglas Gregord87b61f2009-12-10 17:56:55 +00002292 //
2293 // T x = { a };
2294 //
2295 // is equivalent to
2296 //
2297 // T x = a;
2298 if (DestType->isScalarType()) {
2299 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2300 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2301 return;
2302 }
2303
2304 // Assume scalar initialization from a single value works.
2305 } else if (DestType->isAggregateType()) {
2306 // Assume aggregate initialization works.
2307 } else if (DestType->isVectorType()) {
2308 // Assume vector initialization works.
2309 } else if (DestType->isReferenceType()) {
2310 // FIXME: C++0x defines behavior for this.
2311 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2312 return;
2313 } else if (DestType->isRecordType()) {
2314 // FIXME: C++0x defines behavior for this
2315 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2316 }
2317
2318 // Add a general "list initialization" step.
2319 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002320}
2321
2322/// \brief Try a reference initialization that involves calling a conversion
2323/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002324static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2325 const InitializedEntity &Entity,
2326 const InitializationKind &Kind,
2327 Expr *Initializer,
2328 bool AllowRValues,
2329 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002330 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002331 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2332 QualType T1 = cv1T1.getUnqualifiedType();
2333 QualType cv2T2 = Initializer->getType();
2334 QualType T2 = cv2T2.getUnqualifiedType();
2335
2336 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002337 bool ObjCConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002338 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002339 T1, T2, DerivedToBase,
2340 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002341 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002342 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002343 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002344
2345 // Build the candidate set directly in the initialization sequence
2346 // structure, so that it will persist if we fail.
2347 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2348 CandidateSet.clear();
2349
2350 // Determine whether we are allowed to call explicit constructors or
2351 // explicit conversion operators.
2352 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002353
Douglas Gregor20093b42009-12-09 23:02:17 +00002354 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002355 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2356 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002357 // The type we're converting to is a class type. Enumerate its constructors
2358 // to see if there is a suitable conversion.
2359 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002360
Douglas Gregor20093b42009-12-09 23:02:17 +00002361 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002362 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002363 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002364 NamedDecl *D = *Con;
2365 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2366
Douglas Gregor20093b42009-12-09 23:02:17 +00002367 // Find the constructor (which may be a template).
2368 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002369 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 if (ConstructorTmpl)
2371 Constructor = cast<CXXConstructorDecl>(
2372 ConstructorTmpl->getTemplatedDecl());
2373 else
John McCall9aa472c2010-03-19 07:35:19 +00002374 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375
Douglas Gregor20093b42009-12-09 23:02:17 +00002376 if (!Constructor->isInvalidDecl() &&
2377 Constructor->isConvertingConstructor(AllowExplicit)) {
2378 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002379 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002380 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002381 &Initializer, 1, CandidateSet,
2382 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002383 else
John McCall9aa472c2010-03-19 07:35:19 +00002384 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002385 &Initializer, 1, CandidateSet,
2386 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002388 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002389 }
John McCall572fc622010-08-17 07:23:57 +00002390 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2391 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002392
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002393 const RecordType *T2RecordType = 0;
2394 if ((T2RecordType = T2->getAs<RecordType>()) &&
2395 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002396 // The type we're converting from is a class type, enumerate its conversion
2397 // functions.
2398 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2399
John McCalleec51cf2010-01-20 00:46:10 +00002400 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002401 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002402 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2403 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002404 NamedDecl *D = *I;
2405 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2406 if (isa<UsingShadowDecl>(D))
2407 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002408
Douglas Gregor20093b42009-12-09 23:02:17 +00002409 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2410 CXXConversionDecl *Conv;
2411 if (ConvTemplate)
2412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2413 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002414 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002415
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 // If the conversion function doesn't return a reference type,
2417 // it can't be considered for this conversion unless we're allowed to
2418 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002419 // FIXME: Do we need to make sure that we only consider conversion
2420 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002421 // break recursion.
2422 if ((AllowExplicit || !Conv->isExplicit()) &&
2423 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2424 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002425 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002426 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002427 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 else
John McCall9aa472c2010-03-19 07:35:19 +00002429 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002430 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002431 }
2432 }
2433 }
John McCall572fc622010-08-17 07:23:57 +00002434 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2435 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002436
Douglas Gregor20093b42009-12-09 23:02:17 +00002437 SourceLocation DeclLoc = Initializer->getLocStart();
2438
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002441 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002442 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002444
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002446
Chandler Carruth25ca4212011-02-25 19:41:05 +00002447 // This is the overload that will actually be used for the initialization, so
2448 // mark it as used.
2449 S.MarkDeclarationReferenced(DeclLoc, Function);
2450
Eli Friedman03981012009-12-11 02:42:07 +00002451 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002452 if (isa<CXXConversionDecl>(Function))
2453 T2 = Function->getResultType();
2454 else
2455 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002456
2457 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002458 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002459 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002460
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002461 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002462 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002463 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002464 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002465 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002466 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002467 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002468
Douglas Gregor20093b42009-12-09 23:02:17 +00002469 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002470 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002473 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002474 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002475 if (NewRefRelationship == Sema::Ref_Incompatible) {
2476 // If the type we've converted to is not reference-related to the
2477 // type we're looking for, then there is another conversion step
2478 // we need to perform to produce a temporary of the right type
2479 // that we'll be binding to.
2480 ImplicitConversionSequence ICS;
2481 ICS.setStandard();
2482 ICS.Standard = Best->FinalConversion;
2483 T2 = ICS.Standard.getToType(2);
2484 Sequence.AddConversionSequenceStep(ICS, T2);
2485 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002486 Sequence.AddDerivedToBaseCastStep(
2487 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002489 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002490 else if (NewObjCConversion)
2491 Sequence.AddObjCObjectConversionStep(
2492 S.Context.getQualifiedType(T1,
2493 T2.getNonReferenceType().getQualifiers()));
2494
Douglas Gregor20093b42009-12-09 23:02:17 +00002495 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002496 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002497
Douglas Gregor20093b42009-12-09 23:02:17 +00002498 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2499 return OR_Success;
2500}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002501
2502/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2503static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 const InitializedEntity &Entity,
2505 const InitializationKind &Kind,
2506 Expr *Initializer,
2507 InitializationSequence &Sequence) {
2508 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002509
Douglas Gregord6542d82009-12-22 15:35:07 +00002510 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002512 Qualifiers T1Quals;
2513 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002514 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002515 Qualifiers T2Quals;
2516 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002517 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002518
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 // If the initializer is the address of an overloaded function, try
2520 // to resolve the overloaded function. If all goes well, T2 is the
2521 // type of the resulting function.
2522 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002523 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002524 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002525 T1,
2526 false,
2527 Found)) {
2528 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2529 cv2T2 = Fn->getType();
2530 T2 = cv2T2.getUnqualifiedType();
2531 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2533 return;
2534 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002536
Douglas Gregor20093b42009-12-09 23:02:17 +00002537 // Compute some basic properties of the types and the initializer.
2538 bool isLValueRef = DestType->isLValueReferenceType();
2539 bool isRValueRef = !isLValueRef;
2540 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002541 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002542 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002543 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002544 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2545 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002546
Douglas Gregor20093b42009-12-09 23:02:17 +00002547 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002548 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 // "cv2 T2" as follows:
2550 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002553 // Note the analogous bullet points for rvlaue refs to functions. Because
2554 // there are no function rvalues in C++, rvalue refs to functions are treated
2555 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002556 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002557 bool T1Function = T1->isFunctionType();
2558 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002559 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002560 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002561 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002562 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002563 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002564 // reference-compatible with "cv2 T2," or
2565 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002567 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002568 // can occur. However, we do pay attention to whether it is a bit-field
2569 // to decide whether we're actually binding to a temporary created from
2570 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002571 if (DerivedToBase)
2572 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002573 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002574 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002575 else if (ObjCConversion)
2576 Sequence.AddObjCObjectConversionStep(
2577 S.Context.getQualifiedType(T1, T2Quals));
2578
Chandler Carruth5535c382010-01-12 20:32:25 +00002579 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002580 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002581 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002582 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002583 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002584 return;
2585 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002586
2587 // - has a class type (i.e., T2 is a class type), where T1 is not
2588 // reference-related to T2, and can be implicitly converted to an
2589 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2590 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002591 // applicable conversion functions (13.3.1.6) and choosing the best
2592 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002593 // If we have an rvalue ref to function type here, the rhs must be
2594 // an rvalue.
2595 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2596 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002597 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002598 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002599 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002600 Sequence);
2601 if (ConvOvlResult == OR_Success)
2602 return;
John McCall1d318332010-01-12 00:44:57 +00002603 if (ConvOvlResult != OR_No_Viable_Function) {
2604 Sequence.SetOverloadFailure(
2605 InitializationSequence::FK_ReferenceInitOverloadFailed,
2606 ConvOvlResult);
2607 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002608 }
2609 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002610
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002611 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002613 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002614 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002615 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2616 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2617 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002618 Sequence.SetOverloadFailure(
2619 InitializationSequence::FK_ReferenceInitOverloadFailed,
2620 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002621 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002622 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002623 ? (RefRelationship == Sema::Ref_Related
2624 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2625 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2626 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002627
Douglas Gregor20093b42009-12-09 23:02:17 +00002628 return;
2629 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002630
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002631 // - If the initializer expression
2632 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2633 // "cv1 T1" is reference-compatible with "cv2 T2"
2634 // Note: functions are handled below.
2635 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002636 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002638 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002639 (InitCategory.isXValue() ||
2640 (InitCategory.isPRValue() && T2->isRecordType()) ||
2641 (InitCategory.isPRValue() && T2->isArrayType()))) {
2642 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2643 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002644 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2645 // compiler the freedom to perform a copy here or bind to the
2646 // object, while C++0x requires that we bind directly to the
2647 // object. Hence, we always bind to the object without making an
2648 // extra copy. However, in C++03 requires that we check for the
2649 // presence of a suitable copy constructor:
2650 //
2651 // The constructor that would be used to make the copy shall
2652 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002653 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002654 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002657 if (DerivedToBase)
2658 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2659 ValueKind);
2660 else if (ObjCConversion)
2661 Sequence.AddObjCObjectConversionStep(
2662 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002664 if (T1Quals != T2Quals)
2665 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002666 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002667 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002668 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002669 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002670
2671 // - has a class type (i.e., T2 is a class type), where T1 is not
2672 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002673 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2674 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002675 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002676 if (RefRelationship == Sema::Ref_Incompatible) {
2677 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2678 Kind, Initializer,
2679 /*AllowRValues=*/true,
2680 Sequence);
2681 if (ConvOvlResult)
2682 Sequence.SetOverloadFailure(
2683 InitializationSequence::FK_ReferenceInitOverloadFailed,
2684 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002685
Douglas Gregor20093b42009-12-09 23:02:17 +00002686 return;
2687 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002688
Douglas Gregor20093b42009-12-09 23:02:17 +00002689 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2690 return;
2691 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002692
2693 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002694 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002695 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002696 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002697
Douglas Gregor20093b42009-12-09 23:02:17 +00002698 // Determine whether we are allowed to call explicit constructors or
2699 // explicit conversion operators.
2700 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002701
2702 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2703
2704 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2705 /*SuppressUserConversions*/ false,
2706 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002707 /*FIXME:InOverloadResolution=*/false,
2708 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002709 // FIXME: Use the conversion function set stored in ICS to turn
2710 // this into an overloading ambiguity diagnostic. However, we need
2711 // to keep that set as an OverloadCandidateSet rather than as some
2712 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002713 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2714 Sequence.SetOverloadFailure(
2715 InitializationSequence::FK_ReferenceInitOverloadFailed,
2716 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002717 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2718 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002719 else
2720 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002721 return;
2722 }
2723
2724 // [...] If T1 is reference-related to T2, cv1 must be the
2725 // same cv-qualification as, or greater cv-qualification
2726 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002727 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2728 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002729 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002730 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002731 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2732 return;
2733 }
2734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002735 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002736 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002737 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002738 InitCategory.isLValue()) {
2739 Sequence.SetFailed(
2740 InitializationSequence::FK_RValueReferenceBindingToLValue);
2741 return;
2742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002743
Douglas Gregor20093b42009-12-09 23:02:17 +00002744 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2745 return;
2746}
2747
2748/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002749/// (C++ [dcl.init.string], C99 6.7.8).
2750static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002751 const InitializedEntity &Entity,
2752 const InitializationKind &Kind,
2753 Expr *Initializer,
2754 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002755 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002756 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002757}
2758
Douglas Gregor20093b42009-12-09 23:02:17 +00002759/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2760/// enumerates the constructors of the initialized entity and performs overload
2761/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002762static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002763 const InitializedEntity &Entity,
2764 const InitializationKind &Kind,
2765 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002766 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002767 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002768 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002769
Douglas Gregor51c56d62009-12-14 20:49:26 +00002770 // Build the candidate set directly in the initialization sequence
2771 // structure, so that it will persist if we fail.
2772 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2773 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002774
Douglas Gregor51c56d62009-12-14 20:49:26 +00002775 // Determine whether we are allowed to call explicit constructors or
2776 // explicit conversion operators.
2777 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2778 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002779 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002780
2781 // The type we're constructing needs to be complete.
2782 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002783 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002784 return;
2785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002786
Douglas Gregor51c56d62009-12-14 20:49:26 +00002787 // The type we're converting to is a class type. Enumerate its constructors
2788 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002789 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002790 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00002791 CXXRecordDecl *DestRecordDecl
2792 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793
Douglas Gregor51c56d62009-12-14 20:49:26 +00002794 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002795 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002796 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002797 NamedDecl *D = *Con;
2798 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002799 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002800
Douglas Gregor51c56d62009-12-14 20:49:26 +00002801 // Find the constructor (which may be a template).
2802 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002803 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002804 if (ConstructorTmpl)
2805 Constructor = cast<CXXConstructorDecl>(
2806 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002807 else {
John McCall9aa472c2010-03-19 07:35:19 +00002808 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002809
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00002811 // suppress user-defined conversions on the arguments.
2812 // FIXME: Move constructors?
2813 if (Kind.getKind() == InitializationKind::IK_Copy &&
2814 Constructor->isCopyConstructor())
2815 SuppressUserConversions = true;
2816 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002817
Douglas Gregor51c56d62009-12-14 20:49:26 +00002818 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002819 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002820 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002821 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002822 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002823 Args, NumArgs, CandidateSet,
2824 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002825 else
John McCall9aa472c2010-03-19 07:35:19 +00002826 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002827 Args, NumArgs, CandidateSet,
2828 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830 }
2831
Douglas Gregor51c56d62009-12-14 20:49:26 +00002832 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
2834 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002835 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002837 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002838 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002840 Result);
2841 return;
2842 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002843
2844 // C++0x [dcl.init]p6:
2845 // If a program calls for the default initialization of an object
2846 // of a const-qualified type T, T shall be a class type with a
2847 // user-provided default constructor.
2848 if (Kind.getKind() == InitializationKind::IK_Default &&
2849 Entity.getType().isConstQualified() &&
2850 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2851 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2852 return;
2853 }
2854
Douglas Gregor51c56d62009-12-14 20:49:26 +00002855 // Add the constructor initialization step. Any cv-qualification conversion is
2856 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002857 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002859 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002860 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002861}
2862
Douglas Gregor71d17402009-12-15 00:01:57 +00002863/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002864static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00002865 const InitializedEntity &Entity,
2866 const InitializationKind &Kind,
2867 InitializationSequence &Sequence) {
2868 // C++ [dcl.init]p5:
2869 //
2870 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002871 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872
Douglas Gregor71d17402009-12-15 00:01:57 +00002873 // -- if T is an array type, then each element is value-initialized;
2874 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2875 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregor71d17402009-12-15 00:01:57 +00002877 if (const RecordType *RT = T->getAs<RecordType>()) {
2878 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2879 // -- if T is a class type (clause 9) with a user-declared
2880 // constructor (12.1), then the default constructor for T is
2881 // called (and the initialization is ill-formed if T has no
2882 // accessible default constructor);
2883 //
2884 // FIXME: we really want to refer to a single subobject of the array,
2885 // but Entity doesn't have a way to capture that (yet).
2886 if (ClassDecl->hasUserDeclaredConstructor())
2887 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregor16006c92009-12-16 18:50:27 +00002889 // -- if T is a (possibly cv-qualified) non-union class type
2890 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002891 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00002892 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002893 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002894 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002895 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00002897 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002898 }
2899 }
2900
Douglas Gregord6542d82009-12-22 15:35:07 +00002901 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002902 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2903}
2904
Douglas Gregor99a2e602009-12-16 01:38:02 +00002905/// \brief Attempt default initialization (C++ [dcl.init]p6).
2906static void TryDefaultInitialization(Sema &S,
2907 const InitializedEntity &Entity,
2908 const InitializationKind &Kind,
2909 InitializationSequence &Sequence) {
2910 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002911
Douglas Gregor99a2e602009-12-16 01:38:02 +00002912 // C++ [dcl.init]p6:
2913 // To default-initialize an object of type T means:
2914 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002915 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002916 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2917 DestType = Array->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002918
Douglas Gregor99a2e602009-12-16 01:38:02 +00002919 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2920 // constructor for T is called (and the initialization is ill-formed if
2921 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002922 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002923 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2924 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002926
Douglas Gregor99a2e602009-12-16 01:38:02 +00002927 // - otherwise, no initialization is performed.
2928 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929
Douglas Gregor99a2e602009-12-16 01:38:02 +00002930 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002931 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00002932 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002933 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002934 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2935}
2936
Douglas Gregor20093b42009-12-09 23:02:17 +00002937/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2938/// which enumerates all conversion functions and performs overload resolution
2939/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002940static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002941 const InitializedEntity &Entity,
2942 const InitializationKind &Kind,
2943 Expr *Initializer,
2944 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002945 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002946
Douglas Gregord6542d82009-12-22 15:35:07 +00002947 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002948 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2949 QualType SourceType = Initializer->getType();
2950 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2951 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002952
Douglas Gregor4a520a22009-12-14 17:27:33 +00002953 // Build the candidate set directly in the initialization sequence
2954 // structure, so that it will persist if we fail.
2955 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2956 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957
Douglas Gregor4a520a22009-12-14 17:27:33 +00002958 // Determine whether we are allowed to call explicit constructors or
2959 // explicit conversion operators.
2960 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002961
Douglas Gregor4a520a22009-12-14 17:27:33 +00002962 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2963 // The type we're converting to is a class type. Enumerate its constructors
2964 // to see if there is a suitable conversion.
2965 CXXRecordDecl *DestRecordDecl
2966 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002968 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002969 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002970 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002971 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002972 Con != ConEnd; ++Con) {
2973 NamedDecl *D = *Con;
2974 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002975
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002976 // Find the constructor (which may be a template).
2977 CXXConstructorDecl *Constructor = 0;
2978 FunctionTemplateDecl *ConstructorTmpl
2979 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002980 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002981 Constructor = cast<CXXConstructorDecl>(
2982 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002983 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002984 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002985
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002986 if (!Constructor->isInvalidDecl() &&
2987 Constructor->isConvertingConstructor(AllowExplicit)) {
2988 if (ConstructorTmpl)
2989 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2990 /*ExplicitArgs*/ 0,
2991 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002992 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002993 else
2994 S.AddOverloadCandidate(Constructor, FoundDecl,
2995 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002996 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002997 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002998 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002999 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003000 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003001
3002 SourceLocation DeclLoc = Initializer->getLocStart();
3003
Douglas Gregor4a520a22009-12-14 17:27:33 +00003004 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3005 // The type we're converting from is a class type, enumerate its conversion
3006 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003007
Eli Friedman33c2da92009-12-20 22:12:03 +00003008 // We can only enumerate the conversion functions for a complete type; if
3009 // the type isn't complete, simply skip this step.
3010 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3011 CXXRecordDecl *SourceRecordDecl
3012 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013
John McCalleec51cf2010-01-20 00:46:10 +00003014 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003015 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003016 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003018 I != E; ++I) {
3019 NamedDecl *D = *I;
3020 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3021 if (isa<UsingShadowDecl>(D))
3022 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003023
Eli Friedman33c2da92009-12-20 22:12:03 +00003024 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3025 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003026 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003027 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003028 else
John McCall32daa422010-03-31 01:36:47 +00003029 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003030
Eli Friedman33c2da92009-12-20 22:12:03 +00003031 if (AllowExplicit || !Conv->isExplicit()) {
3032 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003033 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003034 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003035 CandidateSet);
3036 else
John McCall9aa472c2010-03-19 07:35:19 +00003037 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003038 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003039 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003040 }
3041 }
3042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043
3044 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003045 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003046 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003047 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003048 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003050 Result);
3051 return;
3052 }
John McCall1d318332010-01-12 00:44:57 +00003053
Douglas Gregor4a520a22009-12-14 17:27:33 +00003054 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003055 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056
Douglas Gregor4a520a22009-12-14 17:27:33 +00003057 if (isa<CXXConstructorDecl>(Function)) {
3058 // Add the user-defined conversion step. Any cv-qualification conversion is
3059 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003060 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003061 return;
3062 }
3063
3064 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003065 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003066 if (ConvType->getAs<RecordType>()) {
3067 // If we're converting to a class type, there may be an copy if
3068 // the resulting temporary object (possible to create an object of
3069 // a base class type). That copy is not a separate conversion, so
3070 // we just make a note of the actual destination type (possibly a
3071 // base class of the type returned by the conversion function) and
3072 // let the user-defined conversion step handle the conversion.
3073 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3074 return;
3075 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003076
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003077 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003079 // If the conversion following the call to the conversion function
3080 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003081 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3082 Best->FinalConversion.Third) {
3083 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003084 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003085 ICS.Standard = Best->FinalConversion;
3086 Sequence.AddConversionSequenceStep(ICS, DestType);
3087 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003088}
3089
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003090/// \brief Determine whether we have compatible array types for the
3091/// purposes of GNU by-copy array initialization.
3092static bool hasCompatibleArrayTypes(ASTContext &Context,
3093 const ArrayType *Dest,
3094 const ArrayType *Source) {
3095 // If the source and destination array types are equivalent, we're
3096 // done.
3097 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3098 return true;
3099
3100 // Make sure that the element types are the same.
3101 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3102 return false;
3103
3104 // The only mismatch we allow is when the destination is an
3105 // incomplete array type and the source is a constant array type.
3106 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3107}
3108
Douglas Gregor20093b42009-12-09 23:02:17 +00003109InitializationSequence::InitializationSequence(Sema &S,
3110 const InitializedEntity &Entity,
3111 const InitializationKind &Kind,
3112 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003113 unsigned NumArgs)
3114 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003115 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116
Douglas Gregor20093b42009-12-09 23:02:17 +00003117 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 // The semantics of initializers are as follows. The destination type is
3119 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003120 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003122 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003123 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003124
3125 if (DestType->isDependentType() ||
3126 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3127 SequenceKind = DependentSequence;
3128 return;
3129 }
3130
John McCall241d5582010-12-07 22:54:16 +00003131 for (unsigned I = 0; I != NumArgs; ++I)
3132 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3133 S.ConvertPropertyForRValue(Args[I]);
3134
Douglas Gregor20093b42009-12-09 23:02:17 +00003135 QualType SourceType;
3136 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003137 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003138 Initializer = Args[0];
3139 if (!isa<InitListExpr>(Initializer))
3140 SourceType = Initializer->getType();
3141 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
3143 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003144 // list-initialized (8.5.4).
3145 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3146 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003147 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregor20093b42009-12-09 23:02:17 +00003150 // - If the destination type is a reference type, see 8.5.3.
3151 if (DestType->isReferenceType()) {
3152 // C++0x [dcl.init.ref]p1:
3153 // A variable declared to be a T& or T&&, that is, "reference to type T"
3154 // (8.3.2), shall be initialized by an object, or function, of type T or
3155 // by an object that can be converted into a T.
3156 // (Therefore, multiple arguments are not permitted.)
3157 if (NumArgs != 1)
3158 SetFailed(FK_TooManyInitsForReference);
3159 else
3160 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3161 return;
3162 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregor20093b42009-12-09 23:02:17 +00003164 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003165 if (Kind.getKind() == InitializationKind::IK_Value ||
3166 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003167 TryValueInitialization(S, Entity, Kind, *this);
3168 return;
3169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170
Douglas Gregor99a2e602009-12-16 01:38:02 +00003171 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003172 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003173 TryDefaultInitialization(S, Entity, Kind, *this);
3174 return;
3175 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003176
John McCallce6c9b72011-02-21 07:22:22 +00003177 // - If the destination type is an array of characters, an array of
3178 // char16_t, an array of char32_t, or an array of wchar_t, and the
3179 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003182 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3183 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCallce6c9b72011-02-21 07:22:22 +00003184 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3185 return;
3186 }
3187
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003188 // Note: as an GNU C extension, we allow initialization of an
3189 // array from a compound literal that creates an array of the same
3190 // type, so long as the initializer has no side effects.
3191 if (!S.getLangOptions().CPlusPlus && Initializer &&
3192 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3193 Initializer->getType()->isArrayType()) {
3194 const ArrayType *SourceAT
3195 = Context.getAsArrayType(Initializer->getType());
3196 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3197 SetFailed(FK_ArrayTypeMismatch);
3198 else if (Initializer->HasSideEffects(S.Context))
3199 SetFailed(FK_NonConstantArrayInit);
3200 else {
3201 setSequenceKind(ArrayInit);
3202 AddArrayInitStep(DestType);
3203 }
3204 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor20093b42009-12-09 23:02:17 +00003205 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3206 else
3207 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 return;
3210 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003211
3212 // Handle initialization in C
3213 if (!S.getLangOptions().CPlusPlus) {
3214 setSequenceKind(CAssignment);
3215 AddCAssignmentStep(DestType);
3216 return;
3217 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218
Douglas Gregor20093b42009-12-09 23:02:17 +00003219 // - If the destination type is a (possibly cv-qualified) class type:
3220 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221 // - If the initialization is direct-initialization, or if it is
3222 // copy-initialization where the cv-unqualified version of the
3223 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003224 // class of the destination, constructors are considered. [...]
3225 if (Kind.getKind() == InitializationKind::IK_Direct ||
3226 (Kind.getKind() == InitializationKind::IK_Copy &&
3227 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3228 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003230 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003231 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003232 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003233 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003234 // used) to a derived class thereof are enumerated as described in
3235 // 13.3.1.4, and the best one is chosen through overload resolution
3236 // (13.3).
3237 else
3238 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3239 return;
3240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor99a2e602009-12-16 01:38:02 +00003242 if (NumArgs > 1) {
3243 SetFailed(FK_TooManyInitsForScalar);
3244 return;
3245 }
3246 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003247
3248 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003249 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003250 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3252 return;
3253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003256 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003257 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003259 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003260 if (S.TryImplicitConversion(*this, Entity, Initializer,
3261 /*SuppressUserConversions*/ true,
3262 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003263 /*InOverloadResolution*/ false,
3264 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregor8e960432010-11-08 03:40:48 +00003265 {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003266 DeclAccessPair dap;
3267 if (Initializer->getType() == Context.OverloadTy &&
3268 !S.ResolveAddressOfOverloadedFunction(Initializer
3269 , DestType, false, dap))
Douglas Gregor8e960432010-11-08 03:40:48 +00003270 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3271 else
3272 SetFailed(InitializationSequence::FK_ConversionFailed);
3273 }
John McCall369371c2010-06-04 02:29:22 +00003274 else
3275 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003276}
3277
3278InitializationSequence::~InitializationSequence() {
3279 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3280 StepEnd = Steps.end();
3281 Step != StepEnd; ++Step)
3282 Step->Destroy();
3283}
3284
3285//===----------------------------------------------------------------------===//
3286// Perform initialization
3287//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003289getAssignmentAction(const InitializedEntity &Entity) {
3290 switch(Entity.getKind()) {
3291 case InitializedEntity::EK_Variable:
3292 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003293 case InitializedEntity::EK_Exception:
3294 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003295 case InitializedEntity::EK_Delegation:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003296 return Sema::AA_Initializing;
3297
3298 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003299 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003300 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3301 return Sema::AA_Sending;
3302
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003303 return Sema::AA_Passing;
3304
3305 case InitializedEntity::EK_Result:
3306 return Sema::AA_Returning;
3307
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003308 case InitializedEntity::EK_Temporary:
3309 // FIXME: Can we tell apart casting vs. converting?
3310 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003312 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003313 case InitializedEntity::EK_ArrayElement:
3314 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003315 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003316 return Sema::AA_Initializing;
3317 }
3318
3319 return Sema::AA_Converting;
3320}
3321
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003322/// \brief Whether we should binding a created object as a temporary when
3323/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003324static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003325 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003326 case InitializedEntity::EK_ArrayElement:
3327 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003328 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003329 case InitializedEntity::EK_New:
3330 case InitializedEntity::EK_Variable:
3331 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003332 case InitializedEntity::EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003333 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003334 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003335 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003336 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003337
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 case InitializedEntity::EK_Parameter:
3339 case InitializedEntity::EK_Temporary:
3340 return true;
3341 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003343 llvm_unreachable("missed an InitializedEntity kind?");
3344}
3345
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003346/// \brief Whether the given entity, when initialized with an object
3347/// created for that initialization, requires destruction.
3348static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3349 switch (Entity.getKind()) {
3350 case InitializedEntity::EK_Member:
3351 case InitializedEntity::EK_Result:
3352 case InitializedEntity::EK_New:
3353 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003354 case InitializedEntity::EK_Delegation:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003355 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003356 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003357 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003359 case InitializedEntity::EK_Variable:
3360 case InitializedEntity::EK_Parameter:
3361 case InitializedEntity::EK_Temporary:
3362 case InitializedEntity::EK_ArrayElement:
3363 case InitializedEntity::EK_Exception:
3364 return true;
3365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366
3367 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003368}
3369
Douglas Gregor523d46a2010-04-18 07:40:54 +00003370/// \brief Make a (potentially elidable) temporary copy of the object
3371/// provided by the given initializer by calling the appropriate copy
3372/// constructor.
3373///
3374/// \param S The Sema object used for type-checking.
3375///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003376/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003377/// the type of the initializer expression or a superclass thereof.
3378///
3379/// \param Enter The entity being initialized.
3380///
3381/// \param CurInit The initializer expression.
3382///
3383/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3384/// is permitted in C++03 (but not C++0x) when binding a reference to
3385/// an rvalue.
3386///
3387/// \returns An expression that copies the initializer expression into
3388/// a temporary object, or an error expression if a copy could not be
3389/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003390static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003391 QualType T,
3392 const InitializedEntity &Entity,
3393 ExprResult CurInit,
3394 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003395 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003396 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003397 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003398 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003399 Class = cast<CXXRecordDecl>(Record->getDecl());
3400 if (!Class)
3401 return move(CurInit);
3402
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003403 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003404 // When certain criteria are met, an implementation is allowed to
3405 // omit the copy/move construction of a class object, even if the
3406 // copy/move constructor and/or destructor for the object have
3407 // side effects. [...]
3408 // - when a temporary class object that has not been bound to a
3409 // reference (12.2) would be copied/moved to a class object
3410 // with the same cv-unqualified type, the copy/move operation
3411 // can be omitted by constructing the temporary object
3412 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003414 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003415 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003416 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003417 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003418 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003419 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003420 switch (Entity.getKind()) {
3421 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003422 Loc = Entity.getReturnLoc();
3423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003424
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003425 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003426 Loc = Entity.getThrowLoc();
3427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003428
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003429 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003430 Loc = Entity.getDecl()->getLocation();
3431 break;
3432
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003433 case InitializedEntity::EK_ArrayElement:
3434 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003435 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003436 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003437 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003438 case InitializedEntity::EK_Base:
Sean Hunt41717662011-02-26 19:13:13 +00003439 case InitializedEntity::EK_Delegation:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003440 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003441 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003442 Loc = CurInitExpr->getLocStart();
3443 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003444 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003445
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003446 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003447 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3448 return move(CurInit);
3449
Douglas Gregorcc15f012011-01-21 19:38:21 +00003450 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003451 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003452 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003453 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003454 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003455 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003456 // C++0x [dcl.init]p16, second bullet to class types, this
3457 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003458 CXXConstructorDecl *Constructor = 0;
3459
3460 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003461 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003462 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003463 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003464 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003465 continue;
3466
3467 DeclAccessPair FoundDecl
3468 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3469 S.AddOverloadCandidate(Constructor, FoundDecl,
3470 &CurInitExpr, 1, CandidateSet);
3471 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003472 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003473
3474 // Handle constructor templates.
3475 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3476 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003477 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003478
Douglas Gregor6493cc52010-11-08 17:16:59 +00003479 Constructor = cast<CXXConstructorDecl>(
3480 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003481 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003482 continue;
3483
3484 // FIXME: Do we need to limit this to copy-constructor-like
3485 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003486 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003487 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3488 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3489 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003491
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003492 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003493 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003494 case OR_Success:
3495 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003497 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003498 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3499 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3500 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003501 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003502 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003503 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003504 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003505 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003506 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003508 case OR_Ambiguous:
3509 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003510 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003511 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003512 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003513 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003515 case OR_Deleted:
3516 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003517 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003518 << CurInitExpr->getSourceRange();
3519 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3520 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003521 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003522 }
3523
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003524 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003525 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003526 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003527
Anders Carlsson9a68a672010-04-21 18:47:17 +00003528 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003529 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003530
3531 if (IsExtraneousCopy) {
3532 // If this is a totally extraneous copy for C++03 reference
3533 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003534 // expression. We don't generate an (elided) copy operation here
3535 // because doing so would require us to pass down a flag to avoid
3536 // infinite recursion, where each step adds another extraneous,
3537 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003538
Douglas Gregor2559a702010-04-18 07:57:34 +00003539 // Instantiate the default arguments of any extra parameters in
3540 // the selected copy constructor, as if we were going to create a
3541 // proper call to the copy constructor.
3542 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3543 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3544 if (S.RequireCompleteType(Loc, Parm->getType(),
3545 S.PDiag(diag::err_call_incomplete_argument)))
3546 break;
3547
3548 // Build the default argument expression; we don't actually care
3549 // if this succeeds or not, because this routine will complain
3550 // if there was a problem.
3551 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3552 }
3553
Douglas Gregor523d46a2010-04-18 07:40:54 +00003554 return S.Owned(CurInitExpr);
3555 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556
Chandler Carruth25ca4212011-02-25 19:41:05 +00003557 S.MarkDeclarationReferenced(Loc, Constructor);
3558
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003559 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003560 // constructor call (we might have derived-to-base conversions, or
3561 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003562 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003563 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003564 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003565
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003566 // Actually perform the constructor call.
3567 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003568 move_arg(ConstructorArgs),
3569 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003570 CXXConstructExpr::CK_Complete,
3571 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003573 // If we're supposed to bind temporaries, do so.
3574 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3575 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3576 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003577}
Douglas Gregor20093b42009-12-09 23:02:17 +00003578
Douglas Gregora41a8c52010-04-22 00:20:18 +00003579void InitializationSequence::PrintInitLocationNote(Sema &S,
3580 const InitializedEntity &Entity) {
3581 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3582 if (Entity.getDecl()->getLocation().isInvalid())
3583 return;
3584
3585 if (Entity.getDecl()->getDeclName())
3586 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3587 << Entity.getDecl()->getDeclName();
3588 else
3589 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3590 }
3591}
3592
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003593ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003594InitializationSequence::Perform(Sema &S,
3595 const InitializedEntity &Entity,
3596 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003597 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003598 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003599 if (SequenceKind == FailedSequence) {
3600 unsigned NumArgs = Args.size();
3601 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003602 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003604
Douglas Gregor20093b42009-12-09 23:02:17 +00003605 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003606 // If the declaration is a non-dependent, incomplete array type
3607 // that has an initializer, then its type will be completed once
3608 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003609 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003610 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003611 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003612 if (const IncompleteArrayType *ArrayT
3613 = S.Context.getAsIncompleteArrayType(DeclType)) {
3614 // FIXME: We don't currently have the ability to accurately
3615 // compute the length of an initializer list without
3616 // performing full type-checking of the initializer list
3617 // (since we have to determine where braces are implicitly
3618 // introduced and such). So, we fall back to making the array
3619 // type a dependently-sized array type with no specified
3620 // bound.
3621 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3622 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003623
Douglas Gregord87b61f2009-12-10 17:56:55 +00003624 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003625 if (DeclaratorDecl *DD = Entity.getDecl()) {
3626 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3627 TypeLoc TL = TInfo->getTypeLoc();
3628 if (IncompleteArrayTypeLoc *ArrayLoc
3629 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3630 Brackets = ArrayLoc->getBracketsRange();
3631 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003632 }
3633
3634 *ResultType
3635 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3636 /*NumElts=*/0,
3637 ArrayT->getSizeModifier(),
3638 ArrayT->getIndexTypeCVRQualifiers(),
3639 Brackets);
3640 }
3641
3642 }
3643 }
3644
Eli Friedman08544622009-12-22 02:35:53 +00003645 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003646 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003647
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003648 if (Args.size() == 0)
3649 return S.Owned((Expr *)0);
3650
Douglas Gregor20093b42009-12-09 23:02:17 +00003651 unsigned NumArgs = Args.size();
3652 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3653 SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003654 (Expr **)Args.release(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 NumArgs,
3656 SourceLocation()));
3657 }
3658
Douglas Gregor99a2e602009-12-16 01:38:02 +00003659 if (SequenceKind == NoInitialization)
3660 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661
Douglas Gregord6542d82009-12-22 15:35:07 +00003662 QualType DestType = Entity.getType().getNonReferenceType();
3663 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003664 // the same as Entity.getDecl()->getType() in cases involving type merging,
3665 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003666 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003667 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003668 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003669
John McCall60d7b3a2010-08-24 06:29:42 +00003670 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671
Douglas Gregor99a2e602009-12-16 01:38:02 +00003672 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673
3674 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00003675 // grab the only argument out the Args and place it into the "current"
3676 // initializer.
3677 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003678 case SK_ResolveAddressOfOverloadedFunction:
3679 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003680 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003681 case SK_CastDerivedToBaseLValue:
3682 case SK_BindReference:
3683 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003684 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003685 case SK_UserConversion:
3686 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003687 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003688 case SK_QualificationConversionRValue:
3689 case SK_ConversionSequence:
3690 case SK_ListInitialization:
3691 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003692 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003693 case SK_ObjCObjectConversion:
3694 case SK_ArrayInit: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003695 assert(Args.size() == 1);
John McCallf6a16482010-12-04 03:47:34 +00003696 Expr *CurInitExpr = Args.get()[0];
3697 if (!CurInitExpr) return ExprError();
3698
3699 // Read from a property when initializing something with it.
3700 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3701 S.ConvertPropertyForRValue(CurInitExpr);
3702
3703 CurInit = ExprResult(CurInitExpr);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003704 break;
John McCallf6a16482010-12-04 03:47:34 +00003705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003707 case SK_ConstructorInitialization:
3708 case SK_ZeroInitialization:
3709 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711
3712 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00003713 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003714 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 for (step_iterator Step = step_begin(), StepEnd = step_end();
3716 Step != StepEnd; ++Step) {
3717 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003718 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719
John McCallf6a16482010-12-04 03:47:34 +00003720 Expr *CurInitExpr = CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003721 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722
Douglas Gregor20093b42009-12-09 23:02:17 +00003723 switch (Step->Kind) {
3724 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003725 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00003726 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003727 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003728 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003729 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003730 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003731 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003732 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003733
Douglas Gregor20093b42009-12-09 23:02:17 +00003734 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003735 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003736 case SK_CastDerivedToBaseLValue: {
3737 // We have a derived-to-base cast that produces either an rvalue or an
3738 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739
John McCallf871d0c2010-08-07 06:22:56 +00003740 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003741
Douglas Gregor20093b42009-12-09 23:02:17 +00003742 // Casts to inaccessible base classes are allowed with C-style casts.
3743 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3744 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3745 CurInitExpr->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746 CurInitExpr->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003747 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003748 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003750 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3751 QualType T = SourceType;
3752 if (const PointerType *Pointer = T->getAs<PointerType>())
3753 T = Pointer->getPointeeType();
3754 if (const RecordType *RecordTy = T->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003755 S.MarkVTableUsed(CurInitExpr->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003756 cast<CXXRecordDecl>(RecordTy->getDecl()));
3757 }
3758
John McCall5baba9d2010-08-25 10:28:54 +00003759 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003760 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003761 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003762 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003763 VK_XValue :
3764 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003765 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3766 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003767 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003768 CurInit.get(),
3769 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 break;
3771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 case SK_BindReference:
3774 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3775 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3776 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003777 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003778 << BitField->getDeclName()
3779 << CurInitExpr->getSourceRange();
3780 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003781 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003782 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003783
Anders Carlsson09380262010-01-31 17:18:49 +00003784 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003785 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003786 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3787 << Entity.getType().isVolatileQualified()
3788 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003789 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003790 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor20093b42009-12-09 23:02:17 +00003793 // Reference binding does not have any corresponding ASTs.
3794
3795 // Check exception specifications
3796 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003797 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003798
Douglas Gregor20093b42009-12-09 23:02:17 +00003799 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003800
Douglas Gregor20093b42009-12-09 23:02:17 +00003801 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003802 // Reference binding does not have any corresponding ASTs.
3803
Douglas Gregor20093b42009-12-09 23:02:17 +00003804 // Check exception specifications
3805 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003806 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003807
Douglas Gregor20093b42009-12-09 23:02:17 +00003808 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809
Douglas Gregor523d46a2010-04-18 07:40:54 +00003810 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00003812 /*IsExtraneousCopy=*/true);
3813 break;
3814
Douglas Gregor20093b42009-12-09 23:02:17 +00003815 case SK_UserConversion: {
3816 // We have a user-defined conversion that invokes either a constructor
3817 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003818 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003819 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003820 FunctionDecl *Fn = Step->Function.Function;
3821 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003822 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003823 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003824 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003825 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003826 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003827 SourceLocation Loc = CurInitExpr->getLocStart();
3828 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003829
Douglas Gregor20093b42009-12-09 23:02:17 +00003830 // Determine the arguments required to actually perform the constructor
3831 // call.
3832 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003833 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003834 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003835 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836
Douglas Gregor20093b42009-12-09 23:02:17 +00003837 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003839 move_arg(ConstructorArgs),
3840 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003841 CXXConstructExpr::CK_Complete,
3842 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003844 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003845
Anders Carlsson9a68a672010-04-21 18:47:17 +00003846 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003847 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003848 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849
John McCall2de56d12010-08-25 11:45:40 +00003850 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003851 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3852 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3853 S.IsDerivedFrom(SourceType, Class))
3854 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003855
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003856 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003857 } else {
3858 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003859 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003860 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003861 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003862 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003863 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864
3865 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00003866 // derived-to-base conversion? I believe the answer is "no", because
3867 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003868 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003869 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003870 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003871
3872 // Do a little dance to make sure that CurInit has the proper
3873 // pointer.
3874 CurInit.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875
Douglas Gregor20093b42009-12-09 23:02:17 +00003876 // Build the actual call to the conversion function.
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003877 CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003878 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003879 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880
John McCall2de56d12010-08-25 11:45:40 +00003881 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003883 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
3886 bool RequiresCopy = !IsCopy &&
Douglas Gregor2f599792010-04-02 18:24:57 +00003887 getKind() != InitializationSequence::ReferenceBinding;
3888 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003889 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003890 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3891 CurInitExpr = static_cast<Expr *>(CurInit.get());
3892 QualType T = CurInitExpr->getType();
3893 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003894 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00003895 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003897 S.PDiag(diag::err_access_dtor_temp) << T);
3898 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003899 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003900 }
3901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
Douglas Gregor20093b42009-12-09 23:02:17 +00003903 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003904 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003905 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3906 CurInitExpr->getType(),
3907 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003908 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003909
Douglas Gregor2f599792010-04-02 18:24:57 +00003910 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003911 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3912 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003913
Douglas Gregor20093b42009-12-09 23:02:17 +00003914 break;
3915 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003916
Douglas Gregor20093b42009-12-09 23:02:17 +00003917 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003918 case SK_QualificationConversionXValue:
3919 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003920 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003921 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003922 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003923 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003924 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003925 VK_XValue :
3926 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003927 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003928 CurInit.release();
3929 CurInit = S.Owned(CurInitExpr);
3930 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003931 }
3932
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003933 case SK_ConversionSequence: {
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003934 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregora3998bd2010-12-02 21:47:04 +00003935 getAssignmentAction(Entity),
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003936 Kind.isCStyleOrFunctionalCast()))
John McCallf312b1e2010-08-26 23:41:50 +00003937 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
Douglas Gregor20093b42009-12-09 23:02:17 +00003939 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003940 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003941 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003942 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943
Douglas Gregord87b61f2009-12-10 17:56:55 +00003944 case SK_ListInitialization: {
3945 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3946 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003947 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003948 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003949
3950 CurInit.release();
3951 CurInit = S.Owned(InitList);
3952 break;
3953 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003954
3955 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003956 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003957 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003958 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959
Douglas Gregor51c56d62009-12-14 20:49:26 +00003960 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003961 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003962 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3963 ? Kind.getEqualLoc()
3964 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003965
3966 if (Kind.getKind() == InitializationKind::IK_Default) {
3967 // Force even a trivial, implicit default constructor to be
3968 // semantically checked. We do this explicitly because we don't build
3969 // the definition for completely trivial constructors.
3970 CXXRecordDecl *ClassDecl = Constructor->getParent();
3971 assert(ClassDecl && "No parent class for constructor.");
3972 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3973 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3974 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3975 }
3976
Douglas Gregor51c56d62009-12-14 20:49:26 +00003977 // Determine the arguments required to actually perform the constructor
3978 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003979 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00003980 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003981 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982
3983
Douglas Gregor91be6f52010-03-02 17:18:33 +00003984 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003985 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003986 (Kind.getKind() == InitializationKind::IK_Direct ||
3987 Kind.getKind() == InitializationKind::IK_Value)) {
3988 // An explicitly-constructed temporary, e.g., X(1, 2).
3989 unsigned NumExprs = ConstructorArgs.size();
3990 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003991 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003992 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003993
Douglas Gregorab6677e2010-09-08 00:15:04 +00003994 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3995 if (!TSInfo)
3996 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997
Douglas Gregor91be6f52010-03-02 17:18:33 +00003998 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3999 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004000 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004002 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004003 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004004 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004005 } else {
4006 CXXConstructExpr::ConstructionKind ConstructKind =
4007 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004008
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004009 if (Entity.getKind() == InitializedEntity::EK_Base) {
4010 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004012 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013 }
4014
Chandler Carruth428edaf2010-10-25 08:47:36 +00004015 // Only get the parenthesis range if it is a direct construction.
4016 SourceRange parenRange =
4017 Kind.getKind() == InitializationKind::IK_Direct ?
4018 Kind.getParenRange() : SourceRange();
4019
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004020 // If the entity allows NRVO, mark the construction as elidable
4021 // unconditionally.
4022 if (Entity.allowsNRVO())
4023 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4024 Constructor, /*Elidable=*/true,
4025 move_arg(ConstructorArgs),
4026 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004027 ConstructKind,
4028 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004029 else
4030 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004031 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004032 move_arg(ConstructorArgs),
4033 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004034 ConstructKind,
4035 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004036 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004037 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004038 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004039
4040 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004041 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004042 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004043 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor2f599792010-04-02 18:24:57 +00004045 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004046 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047
Douglas Gregor51c56d62009-12-14 20:49:26 +00004048 break;
4049 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050
Douglas Gregor71d17402009-12-15 00:01:57 +00004051 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004052 step_iterator NextStep = Step;
4053 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004054 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004055 NextStep->Kind == SK_ConstructorInitialization) {
4056 // The need for zero-initialization is recorded directly into
4057 // the call to the object's constructor within the next step.
4058 ConstructorInitRequiresZeroInit = true;
4059 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4060 S.getLangOptions().CPlusPlus &&
4061 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004062 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4063 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004065 Kind.getRange().getBegin());
4066
4067 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4068 TSInfo->getType().getNonLValueExprType(S.Context),
4069 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004070 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004071 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004072 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004073 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004074 break;
4075 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004076
4077 case SK_CAssignment: {
4078 QualType SourceType = CurInitExpr->getType();
4079 Sema::AssignConvertType ConvTy =
4080 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00004081
4082 // If this is a call, allow conversion to a transparent union.
4083 if (ConvTy != Sema::Compatible &&
4084 Entity.getKind() == InitializedEntity::EK_Parameter &&
4085 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4086 == Sema::Compatible)
4087 ConvTy = Sema::Compatible;
4088
Douglas Gregora41a8c52010-04-22 00:20:18 +00004089 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004090 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4091 Step->Type, SourceType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004092 CurInitExpr,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004093 getAssignmentAction(Entity),
4094 &Complained)) {
4095 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004096 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004097 } else if (Complained)
4098 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004099
4100 CurInit.release();
4101 CurInit = S.Owned(CurInitExpr);
4102 break;
4103 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004104
4105 case SK_StringInit: {
4106 QualType Ty = Step->Type;
John McCallfef8b342011-02-21 07:57:55 +00004107 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty,
4108 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004109 break;
4110 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004111
4112 case SK_ObjCObjectConversion:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004113 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004114 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004115 S.CastCategory(CurInitExpr));
4116 CurInit.release();
4117 CurInit = S.Owned(CurInitExpr);
4118 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004119
4120 case SK_ArrayInit:
4121 // Okay: we checked everything before creating this step. Note that
4122 // this is a GNU extension.
4123 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
4124 << Step->Type << CurInitExpr->getType()
4125 << CurInitExpr->getSourceRange();
4126
4127 // If the destination type is an incomplete array type, update the
4128 // type accordingly.
4129 if (ResultType) {
4130 if (const IncompleteArrayType *IncompleteDest
4131 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4132 if (const ConstantArrayType *ConstantSource
4133 = S.Context.getAsConstantArrayType(CurInitExpr->getType())) {
4134 *ResultType = S.Context.getConstantArrayType(
4135 IncompleteDest->getElementType(),
4136 ConstantSource->getSize(),
4137 ArrayType::Normal, 0);
4138 }
4139 }
4140 }
4141
4142 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004143 }
4144 }
John McCall15d7d122010-11-11 03:21:53 +00004145
4146 // Diagnose non-fatal problems with the completed initialization.
4147 if (Entity.getKind() == InitializedEntity::EK_Member &&
4148 cast<FieldDecl>(Entity.getDecl())->isBitField())
4149 S.CheckBitFieldInitialization(Kind.getLocation(),
4150 cast<FieldDecl>(Entity.getDecl()),
4151 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
Douglas Gregor20093b42009-12-09 23:02:17 +00004153 return move(CurInit);
4154}
4155
4156//===----------------------------------------------------------------------===//
4157// Diagnose initialization failures
4158//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004160 const InitializedEntity &Entity,
4161 const InitializationKind &Kind,
4162 Expr **Args, unsigned NumArgs) {
4163 if (SequenceKind != FailedSequence)
4164 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004165
Douglas Gregord6542d82009-12-22 15:35:07 +00004166 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004167 switch (Failure) {
4168 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004169 // FIXME: Customize for the initialized entity?
4170 if (NumArgs == 0)
4171 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4172 << DestType.getNonReferenceType();
4173 else // FIXME: diagnostic below could be better!
4174 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4175 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004176 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177
Douglas Gregor20093b42009-12-09 23:02:17 +00004178 case FK_ArrayNeedsInitList:
4179 case FK_ArrayNeedsInitListOrStringLiteral:
4180 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4181 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4182 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004183
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004184 case FK_ArrayTypeMismatch:
4185 case FK_NonConstantArrayInit:
4186 S.Diag(Kind.getLocation(),
4187 (Failure == FK_ArrayTypeMismatch
4188 ? diag::err_array_init_different_type
4189 : diag::err_array_init_non_constant_array))
4190 << DestType.getNonReferenceType()
4191 << Args[0]->getType()
4192 << Args[0]->getSourceRange();
4193 break;
4194
John McCall6bb80172010-03-30 21:47:33 +00004195 case FK_AddressOfOverloadFailed: {
4196 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004198 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004199 true,
4200 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004201 break;
John McCall6bb80172010-03-30 21:47:33 +00004202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004203
Douglas Gregor20093b42009-12-09 23:02:17 +00004204 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004205 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004206 switch (FailedOverloadResult) {
4207 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004208 if (Failure == FK_UserConversionOverloadFailed)
4209 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4210 << Args[0]->getType() << DestType
4211 << Args[0]->getSourceRange();
4212 else
4213 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4214 << DestType << Args[0]->getType()
4215 << Args[0]->getSourceRange();
4216
John McCall120d63c2010-08-24 20:38:10 +00004217 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004218 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219
Douglas Gregor20093b42009-12-09 23:02:17 +00004220 case OR_No_Viable_Function:
4221 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4222 << Args[0]->getType() << DestType.getNonReferenceType()
4223 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004224 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
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 OR_Deleted: {
4228 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4229 << Args[0]->getType() << DestType.getNonReferenceType()
4230 << Args[0]->getSourceRange();
4231 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004232 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004233 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4234 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004235 if (Ovl == OR_Deleted) {
4236 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4237 << Best->Function->isDeleted();
4238 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004239 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004240 }
4241 break;
4242 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243
Douglas Gregor20093b42009-12-09 23:02:17 +00004244 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004245 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004246 break;
4247 }
4248 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249
Douglas Gregor20093b42009-12-09 23:02:17 +00004250 case FK_NonConstLValueReferenceBindingToTemporary:
4251 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004252 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004253 Failure == FK_NonConstLValueReferenceBindingToTemporary
4254 ? diag::err_lvalue_reference_bind_to_temporary
4255 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004256 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004257 << DestType.getNonReferenceType()
4258 << Args[0]->getType()
4259 << Args[0]->getSourceRange();
4260 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
Douglas Gregor20093b42009-12-09 23:02:17 +00004262 case FK_RValueReferenceBindingToLValue:
4263 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004264 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004265 << Args[0]->getSourceRange();
4266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267
Douglas Gregor20093b42009-12-09 23:02:17 +00004268 case FK_ReferenceInitDropsQualifiers:
4269 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4270 << DestType.getNonReferenceType()
4271 << Args[0]->getType()
4272 << Args[0]->getSourceRange();
4273 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
Douglas Gregor20093b42009-12-09 23:02:17 +00004275 case FK_ReferenceInitFailed:
4276 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4277 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004278 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004279 << Args[0]->getType()
4280 << Args[0]->getSourceRange();
4281 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004282
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004283 case FK_ConversionFailed: {
4284 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004285 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4286 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004287 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004288 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004289 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004290 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004291 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004292 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004293 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004294 SourceRange R;
4295
4296 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004297 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004298 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004299 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004300 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004301
Douglas Gregor19311e72010-09-08 21:40:08 +00004302 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4303 if (Kind.isCStyleOrFunctionalCast())
4304 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4305 << R;
4306 else
4307 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4308 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004309 break;
4310 }
4311
4312 case FK_ReferenceBindingToInitList:
4313 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4314 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4315 break;
4316
4317 case FK_InitListBadDestinationType:
4318 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4319 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4320 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004321
Douglas Gregor51c56d62009-12-14 20:49:26 +00004322 case FK_ConstructorOverloadFailed: {
4323 SourceRange ArgsRange;
4324 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004326 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
Douglas Gregor51c56d62009-12-14 20:49:26 +00004328 // FIXME: Using "DestType" for the entity we're printing is probably
4329 // bad.
4330 switch (FailedOverloadResult) {
4331 case OR_Ambiguous:
4332 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4333 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004334 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4335 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004337
Douglas Gregor51c56d62009-12-14 20:49:26 +00004338 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004339 if (Kind.getKind() == InitializationKind::IK_Default &&
4340 (Entity.getKind() == InitializedEntity::EK_Base ||
4341 Entity.getKind() == InitializedEntity::EK_Member) &&
4342 isa<CXXConstructorDecl>(S.CurContext)) {
4343 // This is implicit default initialization of a member or
4344 // base within a constructor. If no viable function was
4345 // found, notify the user that she needs to explicitly
4346 // initialize this base/member.
4347 CXXConstructorDecl *Constructor
4348 = cast<CXXConstructorDecl>(S.CurContext);
4349 if (Entity.getKind() == InitializedEntity::EK_Base) {
4350 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4351 << Constructor->isImplicit()
4352 << S.Context.getTypeDeclType(Constructor->getParent())
4353 << /*base=*/0
4354 << Entity.getType();
4355
4356 RecordDecl *BaseDecl
4357 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4358 ->getDecl();
4359 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4360 << S.Context.getTagDeclType(BaseDecl);
4361 } else {
4362 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4363 << Constructor->isImplicit()
4364 << S.Context.getTypeDeclType(Constructor->getParent())
4365 << /*member=*/1
4366 << Entity.getName();
4367 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4368
4369 if (const RecordType *Record
4370 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004371 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004372 diag::note_previous_decl)
4373 << S.Context.getTagDeclType(Record->getDecl());
4374 }
4375 break;
4376 }
4377
Douglas Gregor51c56d62009-12-14 20:49:26 +00004378 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4379 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004380 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004381 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregor51c56d62009-12-14 20:49:26 +00004383 case OR_Deleted: {
4384 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4385 << true << DestType << ArgsRange;
4386 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004387 OverloadingResult Ovl
4388 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004389 if (Ovl == OR_Deleted) {
4390 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4391 << Best->Function->isDeleted();
4392 } else {
4393 llvm_unreachable("Inconsistent overload resolution?");
4394 }
4395 break;
4396 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004397
Douglas Gregor51c56d62009-12-14 20:49:26 +00004398 case OR_Success:
4399 llvm_unreachable("Conversion did not fail!");
4400 break;
4401 }
4402 break;
4403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004404
Douglas Gregor99a2e602009-12-16 01:38:02 +00004405 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004406 if (Entity.getKind() == InitializedEntity::EK_Member &&
4407 isa<CXXConstructorDecl>(S.CurContext)) {
4408 // This is implicit default-initialization of a const member in
4409 // a constructor. Complain that it needs to be explicitly
4410 // initialized.
4411 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4412 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4413 << Constructor->isImplicit()
4414 << S.Context.getTypeDeclType(Constructor->getParent())
4415 << /*const=*/1
4416 << Entity.getName();
4417 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4418 << Entity.getName();
4419 } else {
4420 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4421 << DestType << (bool)DestType->getAs<RecordType>();
4422 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004424
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004425 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004427 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004428 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004430
Douglas Gregora41a8c52010-04-22 00:20:18 +00004431 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004432 return true;
4433}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004434
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004435void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4436 switch (SequenceKind) {
4437 case FailedSequence: {
4438 OS << "Failed sequence: ";
4439 switch (Failure) {
4440 case FK_TooManyInitsForReference:
4441 OS << "too many initializers for reference";
4442 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004444 case FK_ArrayNeedsInitList:
4445 OS << "array requires initializer list";
4446 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004448 case FK_ArrayNeedsInitListOrStringLiteral:
4449 OS << "array requires initializer list or string literal";
4450 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004452 case FK_ArrayTypeMismatch:
4453 OS << "array type mismatch";
4454 break;
4455
4456 case FK_NonConstantArrayInit:
4457 OS << "non-constant array initializer";
4458 break;
4459
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004460 case FK_AddressOfOverloadFailed:
4461 OS << "address of overloaded function failed";
4462 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004463
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004464 case FK_ReferenceInitOverloadFailed:
4465 OS << "overload resolution for reference initialization failed";
4466 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004468 case FK_NonConstLValueReferenceBindingToTemporary:
4469 OS << "non-const lvalue reference bound to temporary";
4470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004471
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004472 case FK_NonConstLValueReferenceBindingToUnrelated:
4473 OS << "non-const lvalue reference bound to unrelated type";
4474 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004476 case FK_RValueReferenceBindingToLValue:
4477 OS << "rvalue reference bound to an lvalue";
4478 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004479
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004480 case FK_ReferenceInitDropsQualifiers:
4481 OS << "reference initialization drops qualifiers";
4482 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004483
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004484 case FK_ReferenceInitFailed:
4485 OS << "reference initialization failed";
4486 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004488 case FK_ConversionFailed:
4489 OS << "conversion failed";
4490 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004491
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004492 case FK_TooManyInitsForScalar:
4493 OS << "too many initializers for scalar";
4494 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004496 case FK_ReferenceBindingToInitList:
4497 OS << "referencing binding to initializer list";
4498 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004500 case FK_InitListBadDestinationType:
4501 OS << "initializer list for non-aggregate, non-scalar type";
4502 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004503
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004504 case FK_UserConversionOverloadFailed:
4505 OS << "overloading failed for user-defined conversion";
4506 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004508 case FK_ConstructorOverloadFailed:
4509 OS << "constructor overloading failed";
4510 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004511
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004512 case FK_DefaultInitOfConst:
4513 OS << "default initialization of a const variable";
4514 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004516 case FK_Incomplete:
4517 OS << "initialization of incomplete type";
4518 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004519 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004520 OS << '\n';
4521 return;
4522 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004524 case DependentSequence:
4525 OS << "Dependent sequence: ";
4526 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004527
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004528 case UserDefinedConversion:
4529 OS << "User-defined conversion sequence: ";
4530 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004532 case ConstructorInitialization:
4533 OS << "Constructor initialization sequence: ";
4534 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004536 case ReferenceBinding:
4537 OS << "Reference binding: ";
4538 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004539
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004540 case ListInitialization:
4541 OS << "List initialization: ";
4542 break;
4543
4544 case ZeroInitialization:
4545 OS << "Zero initialization\n";
4546 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004547
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004548 case NoInitialization:
4549 OS << "No initialization\n";
4550 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004552 case StandardConversion:
4553 OS << "Standard conversion: ";
4554 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004555
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004556 case CAssignment:
4557 OS << "C assignment: ";
4558 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004559
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004560 case StringInit:
4561 OS << "String initialization: ";
4562 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004563
4564 case ArrayInit:
4565 OS << "Array initialization: ";
4566 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004569 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4570 if (S != step_begin()) {
4571 OS << " -> ";
4572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004574 switch (S->Kind) {
4575 case SK_ResolveAddressOfOverloadedFunction:
4576 OS << "resolve address of overloaded function";
4577 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004578
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004579 case SK_CastDerivedToBaseRValue:
4580 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4581 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004582
Sebastian Redl906082e2010-07-20 04:20:21 +00004583 case SK_CastDerivedToBaseXValue:
4584 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4585 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004586
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004587 case SK_CastDerivedToBaseLValue:
4588 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4589 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004590
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004591 case SK_BindReference:
4592 OS << "bind reference to lvalue";
4593 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004595 case SK_BindReferenceToTemporary:
4596 OS << "bind reference to a temporary";
4597 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004598
Douglas Gregor523d46a2010-04-18 07:40:54 +00004599 case SK_ExtraneousCopyToTemporary:
4600 OS << "extraneous C++03 copy to temporary";
4601 break;
4602
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004603 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004604 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004605 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004606
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004607 case SK_QualificationConversionRValue:
4608 OS << "qualification conversion (rvalue)";
4609
Sebastian Redl906082e2010-07-20 04:20:21 +00004610 case SK_QualificationConversionXValue:
4611 OS << "qualification conversion (xvalue)";
4612
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004613 case SK_QualificationConversionLValue:
4614 OS << "qualification conversion (lvalue)";
4615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004616
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004617 case SK_ConversionSequence:
4618 OS << "implicit conversion sequence (";
4619 S->ICS->DebugPrint(); // FIXME: use OS
4620 OS << ")";
4621 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004623 case SK_ListInitialization:
4624 OS << "list initialization";
4625 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004626
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004627 case SK_ConstructorInitialization:
4628 OS << "constructor initialization";
4629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004630
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004631 case SK_ZeroInitialization:
4632 OS << "zero initialization";
4633 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004635 case SK_CAssignment:
4636 OS << "C assignment";
4637 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004638
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004639 case SK_StringInit:
4640 OS << "string initialization";
4641 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004642
4643 case SK_ObjCObjectConversion:
4644 OS << "Objective-C object conversion";
4645 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004646
4647 case SK_ArrayInit:
4648 OS << "array initialization";
4649 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004650 }
4651 }
4652}
4653
4654void InitializationSequence::dump() const {
4655 dump(llvm::errs());
4656}
4657
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004658//===----------------------------------------------------------------------===//
4659// Initialization helper functions
4660//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004661ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004662Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4663 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004664 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004665 if (Init.isInvalid())
4666 return ExprError();
4667
John McCall15d7d122010-11-11 03:21:53 +00004668 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004669 assert(InitE && "No initialization expression?");
4670
4671 if (EqualLoc.isInvalid())
4672 EqualLoc = InitE->getLocStart();
4673
4674 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4675 EqualLoc);
4676 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4677 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004678 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004679}