blob: 5882da0eab46050c88e8c7f05303e285e81b96e1 [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:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002001 case EK_ArrayElement:
2002 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002003 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002004 return DeclarationName();
2005 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002006
Douglas Gregor99a2e602009-12-16 01:38:02 +00002007 // Silence GCC warning
2008 return DeclarationName();
2009}
2010
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002011DeclaratorDecl *InitializedEntity::getDecl() const {
2012 switch (getKind()) {
2013 case EK_Variable:
2014 case EK_Parameter:
2015 case EK_Member:
2016 return VariableOrMember;
2017
2018 case EK_Result:
2019 case EK_Exception:
2020 case EK_New:
2021 case EK_Temporary:
2022 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002023 case EK_ArrayElement:
2024 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002025 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002026 return 0;
2027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002028
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002029 // Silence GCC warning
2030 return 0;
2031}
2032
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002033bool InitializedEntity::allowsNRVO() const {
2034 switch (getKind()) {
2035 case EK_Result:
2036 case EK_Exception:
2037 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002038
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002039 case EK_Variable:
2040 case EK_Parameter:
2041 case EK_Member:
2042 case EK_New:
2043 case EK_Temporary:
2044 case EK_Base:
2045 case EK_ArrayElement:
2046 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002047 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002048 break;
2049 }
2050
2051 return false;
2052}
2053
Douglas Gregor20093b42009-12-09 23:02:17 +00002054//===----------------------------------------------------------------------===//
2055// Initialization sequence
2056//===----------------------------------------------------------------------===//
2057
2058void InitializationSequence::Step::Destroy() {
2059 switch (Kind) {
2060 case SK_ResolveAddressOfOverloadedFunction:
2061 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002062 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002063 case SK_CastDerivedToBaseLValue:
2064 case SK_BindReference:
2065 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002066 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002067 case SK_UserConversion:
2068 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002069 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002070 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002071 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002072 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002073 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002074 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002075 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002076 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002077 case SK_ArrayInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002078 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
Douglas Gregor20093b42009-12-09 23:02:17 +00002080 case SK_ConversionSequence:
2081 delete ICS;
2082 }
2083}
2084
Douglas Gregorb70cf442010-03-26 20:14:36 +00002085bool InitializationSequence::isDirectReferenceBinding() const {
2086 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2087}
2088
2089bool InitializationSequence::isAmbiguous() const {
2090 if (getKind() != FailedSequence)
2091 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002092
Douglas Gregorb70cf442010-03-26 20:14:36 +00002093 switch (getFailureKind()) {
2094 case FK_TooManyInitsForReference:
2095 case FK_ArrayNeedsInitList:
2096 case FK_ArrayNeedsInitListOrStringLiteral:
2097 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2098 case FK_NonConstLValueReferenceBindingToTemporary:
2099 case FK_NonConstLValueReferenceBindingToUnrelated:
2100 case FK_RValueReferenceBindingToLValue:
2101 case FK_ReferenceInitDropsQualifiers:
2102 case FK_ReferenceInitFailed:
2103 case FK_ConversionFailed:
2104 case FK_TooManyInitsForScalar:
2105 case FK_ReferenceBindingToInitList:
2106 case FK_InitListBadDestinationType:
2107 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002108 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002109 case FK_ArrayTypeMismatch:
2110 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002111 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Douglas Gregorb70cf442010-03-26 20:14:36 +00002113 case FK_ReferenceInitOverloadFailed:
2114 case FK_UserConversionOverloadFailed:
2115 case FK_ConstructorOverloadFailed:
2116 return FailedOverloadResult == OR_Ambiguous;
2117 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002118
Douglas Gregorb70cf442010-03-26 20:14:36 +00002119 return false;
2120}
2121
Douglas Gregord6e44a32010-04-16 22:09:46 +00002122bool InitializationSequence::isConstructorInitialization() const {
2123 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2124}
2125
Douglas Gregor20093b42009-12-09 23:02:17 +00002126void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002127 FunctionDecl *Function,
2128 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002129 Step S;
2130 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2131 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002132 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002133 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002134 Steps.push_back(S);
2135}
2136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002137void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002138 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002139 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002140 switch (VK) {
2141 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2142 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2143 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002144 default: llvm_unreachable("No such category");
2145 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002146 S.Type = BaseType;
2147 Steps.push_back(S);
2148}
2149
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002150void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002151 bool BindingTemporary) {
2152 Step S;
2153 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2154 S.Type = T;
2155 Steps.push_back(S);
2156}
2157
Douglas Gregor523d46a2010-04-18 07:40:54 +00002158void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2159 Step S;
2160 S.Kind = SK_ExtraneousCopyToTemporary;
2161 S.Type = T;
2162 Steps.push_back(S);
2163}
2164
Eli Friedman03981012009-12-11 02:42:07 +00002165void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002166 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002167 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002168 Step S;
2169 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002170 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002171 S.Function.Function = Function;
2172 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002173 Steps.push_back(S);
2174}
2175
2176void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002177 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002178 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002179 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002180 switch (VK) {
2181 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002182 S.Kind = SK_QualificationConversionRValue;
2183 break;
John McCall5baba9d2010-08-25 10:28:54 +00002184 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002185 S.Kind = SK_QualificationConversionXValue;
2186 break;
John McCall5baba9d2010-08-25 10:28:54 +00002187 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002188 S.Kind = SK_QualificationConversionLValue;
2189 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002190 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002191 S.Type = Ty;
2192 Steps.push_back(S);
2193}
2194
2195void InitializationSequence::AddConversionSequenceStep(
2196 const ImplicitConversionSequence &ICS,
2197 QualType T) {
2198 Step S;
2199 S.Kind = SK_ConversionSequence;
2200 S.Type = T;
2201 S.ICS = new ImplicitConversionSequence(ICS);
2202 Steps.push_back(S);
2203}
2204
Douglas Gregord87b61f2009-12-10 17:56:55 +00002205void InitializationSequence::AddListInitializationStep(QualType T) {
2206 Step S;
2207 S.Kind = SK_ListInitialization;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002213InitializationSequence::AddConstructorInitializationStep(
2214 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002215 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002216 QualType T) {
2217 Step S;
2218 S.Kind = SK_ConstructorInitialization;
2219 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002220 S.Function.Function = Constructor;
2221 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002222 Steps.push_back(S);
2223}
2224
Douglas Gregor71d17402009-12-15 00:01:57 +00002225void InitializationSequence::AddZeroInitializationStep(QualType T) {
2226 Step S;
2227 S.Kind = SK_ZeroInitialization;
2228 S.Type = T;
2229 Steps.push_back(S);
2230}
2231
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002232void InitializationSequence::AddCAssignmentStep(QualType T) {
2233 Step S;
2234 S.Kind = SK_CAssignment;
2235 S.Type = T;
2236 Steps.push_back(S);
2237}
2238
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002239void InitializationSequence::AddStringInitStep(QualType T) {
2240 Step S;
2241 S.Kind = SK_StringInit;
2242 S.Type = T;
2243 Steps.push_back(S);
2244}
2245
Douglas Gregor569c3162010-08-07 11:51:51 +00002246void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2247 Step S;
2248 S.Kind = SK_ObjCObjectConversion;
2249 S.Type = T;
2250 Steps.push_back(S);
2251}
2252
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002253void InitializationSequence::AddArrayInitStep(QualType T) {
2254 Step S;
2255 S.Kind = SK_ArrayInit;
2256 S.Type = T;
2257 Steps.push_back(S);
2258}
2259
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002260void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002261 OverloadingResult Result) {
2262 SequenceKind = FailedSequence;
2263 this->Failure = Failure;
2264 this->FailedOverloadResult = Result;
2265}
2266
2267//===----------------------------------------------------------------------===//
2268// Attempt initialization
2269//===----------------------------------------------------------------------===//
2270
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002271/// \brief Attempt list initialization (C++0x [dcl.init.list])
2272static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002273 const InitializedEntity &Entity,
2274 const InitializationKind &Kind,
2275 InitListExpr *InitList,
2276 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002277 // FIXME: We only perform rudimentary checking of list
2278 // initializations at this point, then assume that any list
2279 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002280 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002281 // do all of the necessary checking. C++0x initializer lists will
2282 // force us to perform more checking here.
2283 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2284
Douglas Gregord6542d82009-12-22 15:35:07 +00002285 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002286
2287 // C++ [dcl.init]p13:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288 // If T is a scalar type, then a declaration of the form
Douglas Gregord87b61f2009-12-10 17:56:55 +00002289 //
2290 // T x = { a };
2291 //
2292 // is equivalent to
2293 //
2294 // T x = a;
2295 if (DestType->isScalarType()) {
2296 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2297 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2298 return;
2299 }
2300
2301 // Assume scalar initialization from a single value works.
2302 } else if (DestType->isAggregateType()) {
2303 // Assume aggregate initialization works.
2304 } else if (DestType->isVectorType()) {
2305 // Assume vector initialization works.
2306 } else if (DestType->isReferenceType()) {
2307 // FIXME: C++0x defines behavior for this.
2308 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2309 return;
2310 } else if (DestType->isRecordType()) {
2311 // FIXME: C++0x defines behavior for this
2312 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2313 }
2314
2315 // Add a general "list initialization" step.
2316 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002317}
2318
2319/// \brief Try a reference initialization that involves calling a conversion
2320/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002321static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2322 const InitializedEntity &Entity,
2323 const InitializationKind &Kind,
2324 Expr *Initializer,
2325 bool AllowRValues,
2326 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002327 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2329 QualType T1 = cv1T1.getUnqualifiedType();
2330 QualType cv2T2 = Initializer->getType();
2331 QualType T2 = cv2T2.getUnqualifiedType();
2332
2333 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002334 bool ObjCConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002336 T1, T2, DerivedToBase,
2337 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002338 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002339 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002340 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002341
2342 // Build the candidate set directly in the initialization sequence
2343 // structure, so that it will persist if we fail.
2344 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2345 CandidateSet.clear();
2346
2347 // Determine whether we are allowed to call explicit constructors or
2348 // explicit conversion operators.
2349 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002352 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2353 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002354 // The type we're converting to is a class type. Enumerate its constructors
2355 // to see if there is a suitable conversion.
2356 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002357
Douglas Gregor20093b42009-12-09 23:02:17 +00002358 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002359 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002360 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002361 NamedDecl *D = *Con;
2362 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2363
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 // Find the constructor (which may be a template).
2365 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002366 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002367 if (ConstructorTmpl)
2368 Constructor = cast<CXXConstructorDecl>(
2369 ConstructorTmpl->getTemplatedDecl());
2370 else
John McCall9aa472c2010-03-19 07:35:19 +00002371 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002372
Douglas Gregor20093b42009-12-09 23:02:17 +00002373 if (!Constructor->isInvalidDecl() &&
2374 Constructor->isConvertingConstructor(AllowExplicit)) {
2375 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002376 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002377 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002378 &Initializer, 1, CandidateSet,
2379 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002380 else
John McCall9aa472c2010-03-19 07:35:19 +00002381 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002382 &Initializer, 1, CandidateSet,
2383 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002385 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002386 }
John McCall572fc622010-08-17 07:23:57 +00002387 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2388 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002389
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002390 const RecordType *T2RecordType = 0;
2391 if ((T2RecordType = T2->getAs<RecordType>()) &&
2392 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 // The type we're converting from is a class type, enumerate its conversion
2394 // functions.
2395 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2396
John McCalleec51cf2010-01-20 00:46:10 +00002397 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002399 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2400 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002401 NamedDecl *D = *I;
2402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2403 if (isa<UsingShadowDecl>(D))
2404 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002405
Douglas Gregor20093b42009-12-09 23:02:17 +00002406 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2407 CXXConversionDecl *Conv;
2408 if (ConvTemplate)
2409 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2410 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002411 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002412
Douglas Gregor20093b42009-12-09 23:02:17 +00002413 // If the conversion function doesn't return a reference type,
2414 // it can't be considered for this conversion unless we're allowed to
2415 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416 // FIXME: Do we need to make sure that we only consider conversion
2417 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002418 // break recursion.
2419 if ((AllowExplicit || !Conv->isExplicit()) &&
2420 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2421 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002422 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002423 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002424 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002425 else
John McCall9aa472c2010-03-19 07:35:19 +00002426 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002427 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 }
2429 }
2430 }
John McCall572fc622010-08-17 07:23:57 +00002431 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2432 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002433
Douglas Gregor20093b42009-12-09 23:02:17 +00002434 SourceLocation DeclLoc = Initializer->getLocStart();
2435
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002436 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002437 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002438 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002439 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002441
Douglas Gregor20093b42009-12-09 23:02:17 +00002442 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002443
Chandler Carruth25ca4212011-02-25 19:41:05 +00002444 // This is the overload that will actually be used for the initialization, so
2445 // mark it as used.
2446 S.MarkDeclarationReferenced(DeclLoc, Function);
2447
Eli Friedman03981012009-12-11 02:42:07 +00002448 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002449 if (isa<CXXConversionDecl>(Function))
2450 T2 = Function->getResultType();
2451 else
2452 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002453
2454 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002455 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002456 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002457
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002458 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002459 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002460 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002461 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002462 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002463 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002464 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002465
Douglas Gregor20093b42009-12-09 23:02:17 +00002466 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002467 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002468 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002469 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002470 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002471 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002472 if (NewRefRelationship == Sema::Ref_Incompatible) {
2473 // If the type we've converted to is not reference-related to the
2474 // type we're looking for, then there is another conversion step
2475 // we need to perform to produce a temporary of the right type
2476 // that we'll be binding to.
2477 ImplicitConversionSequence ICS;
2478 ICS.setStandard();
2479 ICS.Standard = Best->FinalConversion;
2480 T2 = ICS.Standard.getToType(2);
2481 Sequence.AddConversionSequenceStep(ICS, T2);
2482 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 Sequence.AddDerivedToBaseCastStep(
2484 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002485 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002486 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002487 else if (NewObjCConversion)
2488 Sequence.AddObjCObjectConversionStep(
2489 S.Context.getQualifiedType(T1,
2490 T2.getNonReferenceType().getQualifiers()));
2491
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002493 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002494
Douglas Gregor20093b42009-12-09 23:02:17 +00002495 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2496 return OR_Success;
2497}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002498
2499/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2500static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002501 const InitializedEntity &Entity,
2502 const InitializationKind &Kind,
2503 Expr *Initializer,
2504 InitializationSequence &Sequence) {
2505 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002506
Douglas Gregord6542d82009-12-22 15:35:07 +00002507 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002508 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002509 Qualifiers T1Quals;
2510 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002512 Qualifiers T2Quals;
2513 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002514 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002515
Douglas Gregor20093b42009-12-09 23:02:17 +00002516 // If the initializer is the address of an overloaded function, try
2517 // to resolve the overloaded function. If all goes well, T2 is the
2518 // type of the resulting function.
2519 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002520 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002522 T1,
2523 false,
2524 Found)) {
2525 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2526 cv2T2 = Fn->getType();
2527 T2 = cv2T2.getUnqualifiedType();
2528 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002529 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2530 return;
2531 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002533
Douglas Gregor20093b42009-12-09 23:02:17 +00002534 // Compute some basic properties of the types and the initializer.
2535 bool isLValueRef = DestType->isLValueReferenceType();
2536 bool isRValueRef = !isLValueRef;
2537 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002538 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002539 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002540 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002541 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2542 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002543
Douglas Gregor20093b42009-12-09 23:02:17 +00002544 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002545 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 // "cv2 T2" as follows:
2547 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002548 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002550 // Note the analogous bullet points for rvlaue refs to functions. Because
2551 // there are no function rvalues in C++, rvalue refs to functions are treated
2552 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002554 bool T1Function = T1->isFunctionType();
2555 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002556 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002557 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002559 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002560 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002561 // reference-compatible with "cv2 T2," or
2562 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002563 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002564 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002565 // can occur. However, we do pay attention to whether it is a bit-field
2566 // to decide whether we're actually binding to a temporary created from
2567 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002568 if (DerivedToBase)
2569 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002570 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002571 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002572 else if (ObjCConversion)
2573 Sequence.AddObjCObjectConversionStep(
2574 S.Context.getQualifiedType(T1, T2Quals));
2575
Chandler Carruth5535c382010-01-12 20:32:25 +00002576 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002577 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002578 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002579 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002580 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002581 return;
2582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583
2584 // - has a class type (i.e., T2 is a class type), where T1 is not
2585 // reference-related to T2, and can be implicitly converted to an
2586 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2587 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002588 // applicable conversion functions (13.3.1.6) and choosing the best
2589 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002590 // If we have an rvalue ref to function type here, the rhs must be
2591 // an rvalue.
2592 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2593 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002594 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002595 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002596 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002597 Sequence);
2598 if (ConvOvlResult == OR_Success)
2599 return;
John McCall1d318332010-01-12 00:44:57 +00002600 if (ConvOvlResult != OR_No_Viable_Function) {
2601 Sequence.SetOverloadFailure(
2602 InitializationSequence::FK_ReferenceInitOverloadFailed,
2603 ConvOvlResult);
2604 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002605 }
2606 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002607
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002608 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002609 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002610 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002611 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002612 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2613 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2614 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 Sequence.SetOverloadFailure(
2616 InitializationSequence::FK_ReferenceInitOverloadFailed,
2617 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002618 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002619 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002620 ? (RefRelationship == Sema::Ref_Related
2621 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2622 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2623 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002624
Douglas Gregor20093b42009-12-09 23:02:17 +00002625 return;
2626 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002627
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002628 // - If the initializer expression
2629 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2630 // "cv1 T1" is reference-compatible with "cv2 T2"
2631 // Note: functions are handled below.
2632 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002633 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002634 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002635 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002636 (InitCategory.isXValue() ||
2637 (InitCategory.isPRValue() && T2->isRecordType()) ||
2638 (InitCategory.isPRValue() && T2->isArrayType()))) {
2639 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2640 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002641 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2642 // compiler the freedom to perform a copy here or bind to the
2643 // object, while C++0x requires that we bind directly to the
2644 // object. Hence, we always bind to the object without making an
2645 // extra copy. However, in C++03 requires that we check for the
2646 // presence of a suitable copy constructor:
2647 //
2648 // The constructor that would be used to make the copy shall
2649 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002650 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002651 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002653
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002654 if (DerivedToBase)
2655 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2656 ValueKind);
2657 else if (ObjCConversion)
2658 Sequence.AddObjCObjectConversionStep(
2659 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002661 if (T1Quals != T2Quals)
2662 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002664 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002666 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667
2668 // - has a class type (i.e., T2 is a class type), where T1 is not
2669 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002670 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2671 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002672 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002673 if (RefRelationship == Sema::Ref_Incompatible) {
2674 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2675 Kind, Initializer,
2676 /*AllowRValues=*/true,
2677 Sequence);
2678 if (ConvOvlResult)
2679 Sequence.SetOverloadFailure(
2680 InitializationSequence::FK_ReferenceInitOverloadFailed,
2681 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 return;
2684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002685
Douglas Gregor20093b42009-12-09 23:02:17 +00002686 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2687 return;
2688 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002689
2690 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002691 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002693 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002694
Douglas Gregor20093b42009-12-09 23:02:17 +00002695 // Determine whether we are allowed to call explicit constructors or
2696 // explicit conversion operators.
2697 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002698
2699 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2700
2701 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2702 /*SuppressUserConversions*/ false,
2703 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002704 /*FIXME:InOverloadResolution=*/false,
2705 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002706 // FIXME: Use the conversion function set stored in ICS to turn
2707 // this into an overloading ambiguity diagnostic. However, we need
2708 // to keep that set as an OverloadCandidateSet rather than as some
2709 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002710 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2711 Sequence.SetOverloadFailure(
2712 InitializationSequence::FK_ReferenceInitOverloadFailed,
2713 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002714 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2715 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002716 else
2717 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002718 return;
2719 }
2720
2721 // [...] If T1 is reference-related to T2, cv1 must be the
2722 // same cv-qualification as, or greater cv-qualification
2723 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002724 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2725 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002727 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2729 return;
2730 }
2731
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002732 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002733 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002734 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002735 InitCategory.isLValue()) {
2736 Sequence.SetFailed(
2737 InitializationSequence::FK_RValueReferenceBindingToLValue);
2738 return;
2739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002740
Douglas Gregor20093b42009-12-09 23:02:17 +00002741 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2742 return;
2743}
2744
2745/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746/// (C++ [dcl.init.string], C99 6.7.8).
2747static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002748 const InitializedEntity &Entity,
2749 const InitializationKind &Kind,
2750 Expr *Initializer,
2751 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002752 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002753 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002754}
2755
Douglas Gregor20093b42009-12-09 23:02:17 +00002756/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2757/// enumerates the constructors of the initialized entity and performs overload
2758/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002760 const InitializedEntity &Entity,
2761 const InitializationKind &Kind,
2762 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002763 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002764 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002765 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002766
Douglas Gregor51c56d62009-12-14 20:49:26 +00002767 // Build the candidate set directly in the initialization sequence
2768 // structure, so that it will persist if we fail.
2769 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2770 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002771
Douglas Gregor51c56d62009-12-14 20:49:26 +00002772 // Determine whether we are allowed to call explicit constructors or
2773 // explicit conversion operators.
2774 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2775 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002776 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002777
2778 // The type we're constructing needs to be complete.
2779 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002780 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002781 return;
2782 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002783
Douglas Gregor51c56d62009-12-14 20:49:26 +00002784 // The type we're converting to is a class type. Enumerate its constructors
2785 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002786 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00002788 CXXRecordDecl *DestRecordDecl
2789 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002790
Douglas Gregor51c56d62009-12-14 20:49:26 +00002791 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002792 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002793 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002794 NamedDecl *D = *Con;
2795 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002796 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797
Douglas Gregor51c56d62009-12-14 20:49:26 +00002798 // Find the constructor (which may be a template).
2799 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002800 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002801 if (ConstructorTmpl)
2802 Constructor = cast<CXXConstructorDecl>(
2803 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002804 else {
John McCall9aa472c2010-03-19 07:35:19 +00002805 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002806
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00002808 // suppress user-defined conversions on the arguments.
2809 // FIXME: Move constructors?
2810 if (Kind.getKind() == InitializationKind::IK_Copy &&
2811 Constructor->isCopyConstructor())
2812 SuppressUserConversions = true;
2813 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814
Douglas Gregor51c56d62009-12-14 20:49:26 +00002815 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002816 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002817 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002818 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002819 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002820 Args, NumArgs, CandidateSet,
2821 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002822 else
John McCall9aa472c2010-03-19 07:35:19 +00002823 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002824 Args, NumArgs, CandidateSet,
2825 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002827 }
2828
Douglas Gregor51c56d62009-12-14 20:49:26 +00002829 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
2831 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002832 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002834 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002835 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002837 Result);
2838 return;
2839 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002840
2841 // C++0x [dcl.init]p6:
2842 // If a program calls for the default initialization of an object
2843 // of a const-qualified type T, T shall be a class type with a
2844 // user-provided default constructor.
2845 if (Kind.getKind() == InitializationKind::IK_Default &&
2846 Entity.getType().isConstQualified() &&
2847 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2848 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2849 return;
2850 }
2851
Douglas Gregor51c56d62009-12-14 20:49:26 +00002852 // Add the constructor initialization step. Any cv-qualification conversion is
2853 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002854 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002855 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002856 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002857 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002858}
2859
Douglas Gregor71d17402009-12-15 00:01:57 +00002860/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00002862 const InitializedEntity &Entity,
2863 const InitializationKind &Kind,
2864 InitializationSequence &Sequence) {
2865 // C++ [dcl.init]p5:
2866 //
2867 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002868 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869
Douglas Gregor71d17402009-12-15 00:01:57 +00002870 // -- if T is an array type, then each element is value-initialized;
2871 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2872 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002873
Douglas Gregor71d17402009-12-15 00:01:57 +00002874 if (const RecordType *RT = T->getAs<RecordType>()) {
2875 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2876 // -- if T is a class type (clause 9) with a user-declared
2877 // constructor (12.1), then the default constructor for T is
2878 // called (and the initialization is ill-formed if T has no
2879 // accessible default constructor);
2880 //
2881 // FIXME: we really want to refer to a single subobject of the array,
2882 // but Entity doesn't have a way to capture that (yet).
2883 if (ClassDecl->hasUserDeclaredConstructor())
2884 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885
Douglas Gregor16006c92009-12-16 18:50:27 +00002886 // -- if T is a (possibly cv-qualified) non-union class type
2887 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002888 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00002889 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002890 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002891 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002892 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00002894 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002895 }
2896 }
2897
Douglas Gregord6542d82009-12-22 15:35:07 +00002898 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002899 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2900}
2901
Douglas Gregor99a2e602009-12-16 01:38:02 +00002902/// \brief Attempt default initialization (C++ [dcl.init]p6).
2903static void TryDefaultInitialization(Sema &S,
2904 const InitializedEntity &Entity,
2905 const InitializationKind &Kind,
2906 InitializationSequence &Sequence) {
2907 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002908
Douglas Gregor99a2e602009-12-16 01:38:02 +00002909 // C++ [dcl.init]p6:
2910 // To default-initialize an object of type T means:
2911 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002912 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002913 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2914 DestType = Array->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002915
Douglas Gregor99a2e602009-12-16 01:38:02 +00002916 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2917 // constructor for T is called (and the initialization is ill-formed if
2918 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002919 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002920 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2921 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002923
Douglas Gregor99a2e602009-12-16 01:38:02 +00002924 // - otherwise, no initialization is performed.
2925 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002926
Douglas Gregor99a2e602009-12-16 01:38:02 +00002927 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00002929 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002930 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002931 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2932}
2933
Douglas Gregor20093b42009-12-09 23:02:17 +00002934/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2935/// which enumerates all conversion functions and performs overload resolution
2936/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002937static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002938 const InitializedEntity &Entity,
2939 const InitializationKind &Kind,
2940 Expr *Initializer,
2941 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002942 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002943
Douglas Gregord6542d82009-12-22 15:35:07 +00002944 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002945 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2946 QualType SourceType = Initializer->getType();
2947 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2948 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949
Douglas Gregor4a520a22009-12-14 17:27:33 +00002950 // Build the candidate set directly in the initialization sequence
2951 // structure, so that it will persist if we fail.
2952 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2953 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954
Douglas Gregor4a520a22009-12-14 17:27:33 +00002955 // Determine whether we are allowed to call explicit constructors or
2956 // explicit conversion operators.
2957 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958
Douglas Gregor4a520a22009-12-14 17:27:33 +00002959 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2960 // The type we're converting to is a class type. Enumerate its constructors
2961 // to see if there is a suitable conversion.
2962 CXXRecordDecl *DestRecordDecl
2963 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002964
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002965 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002966 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002967 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002968 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002969 Con != ConEnd; ++Con) {
2970 NamedDecl *D = *Con;
2971 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002973 // Find the constructor (which may be a template).
2974 CXXConstructorDecl *Constructor = 0;
2975 FunctionTemplateDecl *ConstructorTmpl
2976 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002977 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002978 Constructor = cast<CXXConstructorDecl>(
2979 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002980 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002981 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002982
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002983 if (!Constructor->isInvalidDecl() &&
2984 Constructor->isConvertingConstructor(AllowExplicit)) {
2985 if (ConstructorTmpl)
2986 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2987 /*ExplicitArgs*/ 0,
2988 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002989 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002990 else
2991 S.AddOverloadCandidate(Constructor, FoundDecl,
2992 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002993 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002994 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002995 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002996 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002997 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002998
2999 SourceLocation DeclLoc = Initializer->getLocStart();
3000
Douglas Gregor4a520a22009-12-14 17:27:33 +00003001 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3002 // The type we're converting from is a class type, enumerate its conversion
3003 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003004
Eli Friedman33c2da92009-12-20 22:12:03 +00003005 // We can only enumerate the conversion functions for a complete type; if
3006 // the type isn't complete, simply skip this step.
3007 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3008 CXXRecordDecl *SourceRecordDecl
3009 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003010
John McCalleec51cf2010-01-20 00:46:10 +00003011 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003012 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003013 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003014 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003015 I != E; ++I) {
3016 NamedDecl *D = *I;
3017 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3018 if (isa<UsingShadowDecl>(D))
3019 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003020
Eli Friedman33c2da92009-12-20 22:12:03 +00003021 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3022 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003023 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003024 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003025 else
John McCall32daa422010-03-31 01:36:47 +00003026 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003027
Eli Friedman33c2da92009-12-20 22:12:03 +00003028 if (AllowExplicit || !Conv->isExplicit()) {
3029 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003030 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003031 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003032 CandidateSet);
3033 else
John McCall9aa472c2010-03-19 07:35:19 +00003034 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003035 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003036 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003037 }
3038 }
3039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003040
3041 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003042 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003043 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003044 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003045 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003047 Result);
3048 return;
3049 }
John McCall1d318332010-01-12 00:44:57 +00003050
Douglas Gregor4a520a22009-12-14 17:27:33 +00003051 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003052 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053
Douglas Gregor4a520a22009-12-14 17:27:33 +00003054 if (isa<CXXConstructorDecl>(Function)) {
3055 // Add the user-defined conversion step. Any cv-qualification conversion is
3056 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003057 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003058 return;
3059 }
3060
3061 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003062 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003063 if (ConvType->getAs<RecordType>()) {
3064 // If we're converting to a class type, there may be an copy if
3065 // the resulting temporary object (possible to create an object of
3066 // a base class type). That copy is not a separate conversion, so
3067 // we just make a note of the actual destination type (possibly a
3068 // base class of the type returned by the conversion function) and
3069 // let the user-defined conversion step handle the conversion.
3070 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3071 return;
3072 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003073
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003074 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003075
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003076 // If the conversion following the call to the conversion function
3077 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003078 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3079 Best->FinalConversion.Third) {
3080 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003081 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003082 ICS.Standard = Best->FinalConversion;
3083 Sequence.AddConversionSequenceStep(ICS, DestType);
3084 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003085}
3086
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003087/// \brief Determine whether we have compatible array types for the
3088/// purposes of GNU by-copy array initialization.
3089static bool hasCompatibleArrayTypes(ASTContext &Context,
3090 const ArrayType *Dest,
3091 const ArrayType *Source) {
3092 // If the source and destination array types are equivalent, we're
3093 // done.
3094 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3095 return true;
3096
3097 // Make sure that the element types are the same.
3098 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3099 return false;
3100
3101 // The only mismatch we allow is when the destination is an
3102 // incomplete array type and the source is a constant array type.
3103 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3104}
3105
Douglas Gregor20093b42009-12-09 23:02:17 +00003106InitializationSequence::InitializationSequence(Sema &S,
3107 const InitializedEntity &Entity,
3108 const InitializationKind &Kind,
3109 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003110 unsigned NumArgs)
3111 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003112 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113
Douglas Gregor20093b42009-12-09 23:02:17 +00003114 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003115 // The semantics of initializers are as follows. The destination type is
3116 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003117 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003119 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003120 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003121
3122 if (DestType->isDependentType() ||
3123 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3124 SequenceKind = DependentSequence;
3125 return;
3126 }
3127
John McCall241d5582010-12-07 22:54:16 +00003128 for (unsigned I = 0; I != NumArgs; ++I)
3129 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3130 S.ConvertPropertyForRValue(Args[I]);
3131
Douglas Gregor20093b42009-12-09 23:02:17 +00003132 QualType SourceType;
3133 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003134 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003135 Initializer = Args[0];
3136 if (!isa<InitListExpr>(Initializer))
3137 SourceType = Initializer->getType();
3138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003139
3140 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003141 // list-initialized (8.5.4).
3142 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3143 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003144 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 // - If the destination type is a reference type, see 8.5.3.
3148 if (DestType->isReferenceType()) {
3149 // C++0x [dcl.init.ref]p1:
3150 // A variable declared to be a T& or T&&, that is, "reference to type T"
3151 // (8.3.2), shall be initialized by an object, or function, of type T or
3152 // by an object that can be converted into a T.
3153 // (Therefore, multiple arguments are not permitted.)
3154 if (NumArgs != 1)
3155 SetFailed(FK_TooManyInitsForReference);
3156 else
3157 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3158 return;
3159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160
Douglas Gregor20093b42009-12-09 23:02:17 +00003161 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003162 if (Kind.getKind() == InitializationKind::IK_Value ||
3163 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003164 TryValueInitialization(S, Entity, Kind, *this);
3165 return;
3166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
Douglas Gregor99a2e602009-12-16 01:38:02 +00003168 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003169 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003170 TryDefaultInitialization(S, Entity, Kind, *this);
3171 return;
3172 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003173
John McCallce6c9b72011-02-21 07:22:22 +00003174 // - If the destination type is an array of characters, an array of
3175 // char16_t, an array of char32_t, or an array of wchar_t, and the
3176 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003179 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3180 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCallce6c9b72011-02-21 07:22:22 +00003181 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3182 return;
3183 }
3184
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003185 // Note: as an GNU C extension, we allow initialization of an
3186 // array from a compound literal that creates an array of the same
3187 // type, so long as the initializer has no side effects.
3188 if (!S.getLangOptions().CPlusPlus && Initializer &&
3189 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3190 Initializer->getType()->isArrayType()) {
3191 const ArrayType *SourceAT
3192 = Context.getAsArrayType(Initializer->getType());
3193 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3194 SetFailed(FK_ArrayTypeMismatch);
3195 else if (Initializer->HasSideEffects(S.Context))
3196 SetFailed(FK_NonConstantArrayInit);
3197 else {
3198 setSequenceKind(ArrayInit);
3199 AddArrayInitStep(DestType);
3200 }
3201 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor20093b42009-12-09 23:02:17 +00003202 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3203 else
3204 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003205
Douglas Gregor20093b42009-12-09 23:02:17 +00003206 return;
3207 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003208
3209 // Handle initialization in C
3210 if (!S.getLangOptions().CPlusPlus) {
3211 setSequenceKind(CAssignment);
3212 AddCAssignmentStep(DestType);
3213 return;
3214 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
Douglas Gregor20093b42009-12-09 23:02:17 +00003216 // - If the destination type is a (possibly cv-qualified) class type:
3217 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 // - If the initialization is direct-initialization, or if it is
3219 // copy-initialization where the cv-unqualified version of the
3220 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003221 // class of the destination, constructors are considered. [...]
3222 if (Kind.getKind() == InitializationKind::IK_Direct ||
3223 (Kind.getKind() == InitializationKind::IK_Copy &&
3224 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3225 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003227 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003228 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003229 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003230 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 // used) to a derived class thereof are enumerated as described in
3232 // 13.3.1.4, and the best one is chosen through overload resolution
3233 // (13.3).
3234 else
3235 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3236 return;
3237 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003238
Douglas Gregor99a2e602009-12-16 01:38:02 +00003239 if (NumArgs > 1) {
3240 SetFailed(FK_TooManyInitsForScalar);
3241 return;
3242 }
3243 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003244
3245 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003246 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003247 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003248 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3249 return;
3250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003251
Douglas Gregor20093b42009-12-09 23:02:17 +00003252 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003253 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003254 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003257 if (S.TryImplicitConversion(*this, Entity, Initializer,
3258 /*SuppressUserConversions*/ true,
3259 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003260 /*InOverloadResolution*/ false,
3261 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregor8e960432010-11-08 03:40:48 +00003262 {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003263 DeclAccessPair dap;
3264 if (Initializer->getType() == Context.OverloadTy &&
3265 !S.ResolveAddressOfOverloadedFunction(Initializer
3266 , DestType, false, dap))
Douglas Gregor8e960432010-11-08 03:40:48 +00003267 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3268 else
3269 SetFailed(InitializationSequence::FK_ConversionFailed);
3270 }
John McCall369371c2010-06-04 02:29:22 +00003271 else
3272 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003273}
3274
3275InitializationSequence::~InitializationSequence() {
3276 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3277 StepEnd = Steps.end();
3278 Step != StepEnd; ++Step)
3279 Step->Destroy();
3280}
3281
3282//===----------------------------------------------------------------------===//
3283// Perform initialization
3284//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003286getAssignmentAction(const InitializedEntity &Entity) {
3287 switch(Entity.getKind()) {
3288 case InitializedEntity::EK_Variable:
3289 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003290 case InitializedEntity::EK_Exception:
3291 case InitializedEntity::EK_Base:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003292 return Sema::AA_Initializing;
3293
3294 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003296 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3297 return Sema::AA_Sending;
3298
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003299 return Sema::AA_Passing;
3300
3301 case InitializedEntity::EK_Result:
3302 return Sema::AA_Returning;
3303
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003304 case InitializedEntity::EK_Temporary:
3305 // FIXME: Can we tell apart casting vs. converting?
3306 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003307
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003308 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003309 case InitializedEntity::EK_ArrayElement:
3310 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003311 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003312 return Sema::AA_Initializing;
3313 }
3314
3315 return Sema::AA_Converting;
3316}
3317
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003318/// \brief Whether we should binding a created object as a temporary when
3319/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003320static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003321 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003322 case InitializedEntity::EK_ArrayElement:
3323 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003324 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003325 case InitializedEntity::EK_New:
3326 case InitializedEntity::EK_Variable:
3327 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003328 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003329 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003330 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003331 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003332
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003333 case InitializedEntity::EK_Parameter:
3334 case InitializedEntity::EK_Temporary:
3335 return true;
3336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003337
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 llvm_unreachable("missed an InitializedEntity kind?");
3339}
3340
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003341/// \brief Whether the given entity, when initialized with an object
3342/// created for that initialization, requires destruction.
3343static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3344 switch (Entity.getKind()) {
3345 case InitializedEntity::EK_Member:
3346 case InitializedEntity::EK_Result:
3347 case InitializedEntity::EK_New:
3348 case InitializedEntity::EK_Base:
3349 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003350 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003351 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003352
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003353 case InitializedEntity::EK_Variable:
3354 case InitializedEntity::EK_Parameter:
3355 case InitializedEntity::EK_Temporary:
3356 case InitializedEntity::EK_ArrayElement:
3357 case InitializedEntity::EK_Exception:
3358 return true;
3359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360
3361 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003362}
3363
Douglas Gregor523d46a2010-04-18 07:40:54 +00003364/// \brief Make a (potentially elidable) temporary copy of the object
3365/// provided by the given initializer by calling the appropriate copy
3366/// constructor.
3367///
3368/// \param S The Sema object used for type-checking.
3369///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003370/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003371/// the type of the initializer expression or a superclass thereof.
3372///
3373/// \param Enter The entity being initialized.
3374///
3375/// \param CurInit The initializer expression.
3376///
3377/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3378/// is permitted in C++03 (but not C++0x) when binding a reference to
3379/// an rvalue.
3380///
3381/// \returns An expression that copies the initializer expression into
3382/// a temporary object, or an error expression if a copy could not be
3383/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003384static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003385 QualType T,
3386 const InitializedEntity &Entity,
3387 ExprResult CurInit,
3388 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003389 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003390 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003392 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003393 Class = cast<CXXRecordDecl>(Record->getDecl());
3394 if (!Class)
3395 return move(CurInit);
3396
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003397 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003398 // When certain criteria are met, an implementation is allowed to
3399 // omit the copy/move construction of a class object, even if the
3400 // copy/move constructor and/or destructor for the object have
3401 // side effects. [...]
3402 // - when a temporary class object that has not been bound to a
3403 // reference (12.2) would be copied/moved to a class object
3404 // with the same cv-unqualified type, the copy/move operation
3405 // can be omitted by constructing the temporary object
3406 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003408 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003409 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003411 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003412 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003413 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003414 switch (Entity.getKind()) {
3415 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003416 Loc = Entity.getReturnLoc();
3417 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003419 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003420 Loc = Entity.getThrowLoc();
3421 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003423 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003424 Loc = Entity.getDecl()->getLocation();
3425 break;
3426
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003427 case InitializedEntity::EK_ArrayElement:
3428 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003429 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003430 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003431 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003432 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003433 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003434 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003435 Loc = CurInitExpr->getLocStart();
3436 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003437 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003438
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003439 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003440 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3441 return move(CurInit);
3442
Douglas Gregorcc15f012011-01-21 19:38:21 +00003443 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003444 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003445 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003446 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003447 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003448 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003449 // C++0x [dcl.init]p16, second bullet to class types, this
3450 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003451 CXXConstructorDecl *Constructor = 0;
3452
3453 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003454 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003455 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003456 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003457 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003458 continue;
3459
3460 DeclAccessPair FoundDecl
3461 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3462 S.AddOverloadCandidate(Constructor, FoundDecl,
3463 &CurInitExpr, 1, CandidateSet);
3464 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003465 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003466
3467 // Handle constructor templates.
3468 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3469 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003470 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003471
Douglas Gregor6493cc52010-11-08 17:16:59 +00003472 Constructor = cast<CXXConstructorDecl>(
3473 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003474 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003475 continue;
3476
3477 // FIXME: Do we need to limit this to copy-constructor-like
3478 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003479 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003480 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3481 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3482 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003485 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003486 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003487 case OR_Success:
3488 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003490 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003491 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3492 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3493 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003494 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003495 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003496 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003497 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003498 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003499 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003501 case OR_Ambiguous:
3502 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003503 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003504 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003505 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003506 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003508 case OR_Deleted:
3509 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003510 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003511 << CurInitExpr->getSourceRange();
3512 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3513 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003514 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003515 }
3516
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003517 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003518 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003519 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003520
Anders Carlsson9a68a672010-04-21 18:47:17 +00003521 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003522 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003523
3524 if (IsExtraneousCopy) {
3525 // If this is a totally extraneous copy for C++03 reference
3526 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003527 // expression. We don't generate an (elided) copy operation here
3528 // because doing so would require us to pass down a flag to avoid
3529 // infinite recursion, where each step adds another extraneous,
3530 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003531
Douglas Gregor2559a702010-04-18 07:57:34 +00003532 // Instantiate the default arguments of any extra parameters in
3533 // the selected copy constructor, as if we were going to create a
3534 // proper call to the copy constructor.
3535 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3536 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3537 if (S.RequireCompleteType(Loc, Parm->getType(),
3538 S.PDiag(diag::err_call_incomplete_argument)))
3539 break;
3540
3541 // Build the default argument expression; we don't actually care
3542 // if this succeeds or not, because this routine will complain
3543 // if there was a problem.
3544 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3545 }
3546
Douglas Gregor523d46a2010-04-18 07:40:54 +00003547 return S.Owned(CurInitExpr);
3548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549
Chandler Carruth25ca4212011-02-25 19:41:05 +00003550 S.MarkDeclarationReferenced(Loc, Constructor);
3551
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003552 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003553 // constructor call (we might have derived-to-base conversions, or
3554 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003555 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003556 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003557 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003558
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003559 // Actually perform the constructor call.
3560 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003561 move_arg(ConstructorArgs),
3562 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003563 CXXConstructExpr::CK_Complete,
3564 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003565
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003566 // If we're supposed to bind temporaries, do so.
3567 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3568 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3569 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003570}
Douglas Gregor20093b42009-12-09 23:02:17 +00003571
Douglas Gregora41a8c52010-04-22 00:20:18 +00003572void InitializationSequence::PrintInitLocationNote(Sema &S,
3573 const InitializedEntity &Entity) {
3574 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3575 if (Entity.getDecl()->getLocation().isInvalid())
3576 return;
3577
3578 if (Entity.getDecl()->getDeclName())
3579 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3580 << Entity.getDecl()->getDeclName();
3581 else
3582 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3583 }
3584}
3585
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003586ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003587InitializationSequence::Perform(Sema &S,
3588 const InitializedEntity &Entity,
3589 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003590 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003591 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003592 if (SequenceKind == FailedSequence) {
3593 unsigned NumArgs = Args.size();
3594 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003595 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003597
Douglas Gregor20093b42009-12-09 23:02:17 +00003598 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003599 // If the declaration is a non-dependent, incomplete array type
3600 // that has an initializer, then its type will be completed once
3601 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003602 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003603 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003604 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003605 if (const IncompleteArrayType *ArrayT
3606 = S.Context.getAsIncompleteArrayType(DeclType)) {
3607 // FIXME: We don't currently have the ability to accurately
3608 // compute the length of an initializer list without
3609 // performing full type-checking of the initializer list
3610 // (since we have to determine where braces are implicitly
3611 // introduced and such). So, we fall back to making the array
3612 // type a dependently-sized array type with no specified
3613 // bound.
3614 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3615 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003616
Douglas Gregord87b61f2009-12-10 17:56:55 +00003617 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003618 if (DeclaratorDecl *DD = Entity.getDecl()) {
3619 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3620 TypeLoc TL = TInfo->getTypeLoc();
3621 if (IncompleteArrayTypeLoc *ArrayLoc
3622 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3623 Brackets = ArrayLoc->getBracketsRange();
3624 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003625 }
3626
3627 *ResultType
3628 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3629 /*NumElts=*/0,
3630 ArrayT->getSizeModifier(),
3631 ArrayT->getIndexTypeCVRQualifiers(),
3632 Brackets);
3633 }
3634
3635 }
3636 }
3637
Eli Friedman08544622009-12-22 02:35:53 +00003638 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003639 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003640
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003641 if (Args.size() == 0)
3642 return S.Owned((Expr *)0);
3643
Douglas Gregor20093b42009-12-09 23:02:17 +00003644 unsigned NumArgs = Args.size();
3645 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3646 SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647 (Expr **)Args.release(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003648 NumArgs,
3649 SourceLocation()));
3650 }
3651
Douglas Gregor99a2e602009-12-16 01:38:02 +00003652 if (SequenceKind == NoInitialization)
3653 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003654
Douglas Gregord6542d82009-12-22 15:35:07 +00003655 QualType DestType = Entity.getType().getNonReferenceType();
3656 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003657 // the same as Entity.getDecl()->getType() in cases involving type merging,
3658 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003659 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003660 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003661 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003662
John McCall60d7b3a2010-08-24 06:29:42 +00003663 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor99a2e602009-12-16 01:38:02 +00003665 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666
3667 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00003668 // grab the only argument out the Args and place it into the "current"
3669 // initializer.
3670 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003671 case SK_ResolveAddressOfOverloadedFunction:
3672 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003673 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003674 case SK_CastDerivedToBaseLValue:
3675 case SK_BindReference:
3676 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003677 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003678 case SK_UserConversion:
3679 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003680 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003681 case SK_QualificationConversionRValue:
3682 case SK_ConversionSequence:
3683 case SK_ListInitialization:
3684 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003685 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003686 case SK_ObjCObjectConversion:
3687 case SK_ArrayInit: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003688 assert(Args.size() == 1);
John McCallf6a16482010-12-04 03:47:34 +00003689 Expr *CurInitExpr = Args.get()[0];
3690 if (!CurInitExpr) return ExprError();
3691
3692 // Read from a property when initializing something with it.
3693 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3694 S.ConvertPropertyForRValue(CurInitExpr);
3695
3696 CurInit = ExprResult(CurInitExpr);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003697 break;
John McCallf6a16482010-12-04 03:47:34 +00003698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003700 case SK_ConstructorInitialization:
3701 case SK_ZeroInitialization:
3702 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704
3705 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003707 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003708 for (step_iterator Step = step_begin(), StepEnd = step_end();
3709 Step != StepEnd; ++Step) {
3710 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003711 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003712
John McCallf6a16482010-12-04 03:47:34 +00003713 Expr *CurInitExpr = CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003714 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 switch (Step->Kind) {
3717 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00003719 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003720 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003721 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003722 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003723 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003724 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003725 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726
Douglas Gregor20093b42009-12-09 23:02:17 +00003727 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003728 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 case SK_CastDerivedToBaseLValue: {
3730 // We have a derived-to-base cast that produces either an rvalue or an
3731 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732
John McCallf871d0c2010-08-07 06:22:56 +00003733 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003734
Douglas Gregor20093b42009-12-09 23:02:17 +00003735 // Casts to inaccessible base classes are allowed with C-style casts.
3736 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3737 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3738 CurInitExpr->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739 CurInitExpr->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003740 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003741 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003743 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3744 QualType T = SourceType;
3745 if (const PointerType *Pointer = T->getAs<PointerType>())
3746 T = Pointer->getPointeeType();
3747 if (const RecordType *RecordTy = T->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748 S.MarkVTableUsed(CurInitExpr->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003749 cast<CXXRecordDecl>(RecordTy->getDecl()));
3750 }
3751
John McCall5baba9d2010-08-25 10:28:54 +00003752 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003753 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003754 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003755 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003756 VK_XValue :
3757 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003758 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3759 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003760 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003761 CurInit.get(),
3762 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003763 break;
3764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 case SK_BindReference:
3767 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3768 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3769 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003770 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003771 << BitField->getDeclName()
3772 << CurInitExpr->getSourceRange();
3773 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003774 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003775 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003776
Anders Carlsson09380262010-01-31 17:18:49 +00003777 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003778 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003779 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3780 << Entity.getType().isVolatileQualified()
3781 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003782 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003783 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003784 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785
Douglas Gregor20093b42009-12-09 23:02:17 +00003786 // Reference binding does not have any corresponding ASTs.
3787
3788 // Check exception specifications
3789 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003790 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003791
Douglas Gregor20093b42009-12-09 23:02:17 +00003792 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003793
Douglas Gregor20093b42009-12-09 23:02:17 +00003794 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003795 // Reference binding does not have any corresponding ASTs.
3796
Douglas Gregor20093b42009-12-09 23:02:17 +00003797 // Check exception specifications
3798 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003799 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003800
Douglas Gregor20093b42009-12-09 23:02:17 +00003801 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802
Douglas Gregor523d46a2010-04-18 07:40:54 +00003803 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003804 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00003805 /*IsExtraneousCopy=*/true);
3806 break;
3807
Douglas Gregor20093b42009-12-09 23:02:17 +00003808 case SK_UserConversion: {
3809 // We have a user-defined conversion that invokes either a constructor
3810 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003811 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003812 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003813 FunctionDecl *Fn = Step->Function.Function;
3814 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003815 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003816 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003817 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003818 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003819 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003820 SourceLocation Loc = CurInitExpr->getLocStart();
3821 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003822
Douglas Gregor20093b42009-12-09 23:02:17 +00003823 // Determine the arguments required to actually perform the constructor
3824 // call.
3825 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003826 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003827 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003828 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829
Douglas Gregor20093b42009-12-09 23:02:17 +00003830 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003832 move_arg(ConstructorArgs),
3833 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003834 CXXConstructExpr::CK_Complete,
3835 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003836 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003837 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003838
Anders Carlsson9a68a672010-04-21 18:47:17 +00003839 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003840 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003841 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
John McCall2de56d12010-08-25 11:45:40 +00003843 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003844 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3845 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3846 S.IsDerivedFrom(SourceType, Class))
3847 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003849 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003850 } else {
3851 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003852 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003853 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003854 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003855 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003856 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
3858 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00003859 // derived-to-base conversion? I believe the answer is "no", because
3860 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003861 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003862 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003863 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003864
3865 // Do a little dance to make sure that CurInit has the proper
3866 // pointer.
3867 CurInit.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868
Douglas Gregor20093b42009-12-09 23:02:17 +00003869 // Build the actual call to the conversion function.
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003870 CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003871 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003872 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
John McCall2de56d12010-08-25 11:45:40 +00003874 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003876 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003877 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878
3879 bool RequiresCopy = !IsCopy &&
Douglas Gregor2f599792010-04-02 18:24:57 +00003880 getKind() != InitializationSequence::ReferenceBinding;
3881 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003882 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003883 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3884 CurInitExpr = static_cast<Expr *>(CurInit.get());
3885 QualType T = CurInitExpr->getType();
3886 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00003888 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003890 S.PDiag(diag::err_access_dtor_temp) << T);
3891 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003892 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003893 }
3894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003895
Douglas Gregor20093b42009-12-09 23:02:17 +00003896 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003897 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003898 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3899 CurInitExpr->getType(),
3900 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003901 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
Douglas Gregor2f599792010-04-02 18:24:57 +00003903 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003904 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3905 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003906
Douglas Gregor20093b42009-12-09 23:02:17 +00003907 break;
3908 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003909
Douglas Gregor20093b42009-12-09 23:02:17 +00003910 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003911 case SK_QualificationConversionXValue:
3912 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003913 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003914 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003915 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003916 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003917 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003918 VK_XValue :
3919 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003920 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003921 CurInit.release();
3922 CurInit = S.Owned(CurInitExpr);
3923 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003924 }
3925
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003926 case SK_ConversionSequence: {
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003927 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregora3998bd2010-12-02 21:47:04 +00003928 getAssignmentAction(Entity),
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003929 Kind.isCStyleOrFunctionalCast()))
John McCallf312b1e2010-08-26 23:41:50 +00003930 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
Douglas Gregor20093b42009-12-09 23:02:17 +00003932 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003933 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003934 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003935 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936
Douglas Gregord87b61f2009-12-10 17:56:55 +00003937 case SK_ListInitialization: {
3938 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3939 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003940 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003941 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003942
3943 CurInit.release();
3944 CurInit = S.Owned(InitList);
3945 break;
3946 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003947
3948 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003949 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003950 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003951 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952
Douglas Gregor51c56d62009-12-14 20:49:26 +00003953 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003954 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003955 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3956 ? Kind.getEqualLoc()
3957 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003958
3959 if (Kind.getKind() == InitializationKind::IK_Default) {
3960 // Force even a trivial, implicit default constructor to be
3961 // semantically checked. We do this explicitly because we don't build
3962 // the definition for completely trivial constructors.
3963 CXXRecordDecl *ClassDecl = Constructor->getParent();
3964 assert(ClassDecl && "No parent class for constructor.");
3965 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3966 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3967 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3968 }
3969
Douglas Gregor51c56d62009-12-14 20:49:26 +00003970 // Determine the arguments required to actually perform the constructor
3971 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003972 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00003973 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003974 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003975
3976
Douglas Gregor91be6f52010-03-02 17:18:33 +00003977 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003978 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003979 (Kind.getKind() == InitializationKind::IK_Direct ||
3980 Kind.getKind() == InitializationKind::IK_Value)) {
3981 // An explicitly-constructed temporary, e.g., X(1, 2).
3982 unsigned NumExprs = ConstructorArgs.size();
3983 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003984 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003985 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003986
Douglas Gregorab6677e2010-09-08 00:15:04 +00003987 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3988 if (!TSInfo)
3989 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990
Douglas Gregor91be6f52010-03-02 17:18:33 +00003991 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3992 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00003993 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003995 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003996 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003997 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003998 } else {
3999 CXXConstructExpr::ConstructionKind ConstructKind =
4000 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004002 if (Entity.getKind() == InitializedEntity::EK_Base) {
4003 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004005 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006 }
4007
Chandler Carruth428edaf2010-10-25 08:47:36 +00004008 // Only get the parenthesis range if it is a direct construction.
4009 SourceRange parenRange =
4010 Kind.getKind() == InitializationKind::IK_Direct ?
4011 Kind.getParenRange() : SourceRange();
4012
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004013 // If the entity allows NRVO, mark the construction as elidable
4014 // unconditionally.
4015 if (Entity.allowsNRVO())
4016 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4017 Constructor, /*Elidable=*/true,
4018 move_arg(ConstructorArgs),
4019 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004020 ConstructKind,
4021 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004022 else
4023 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004025 move_arg(ConstructorArgs),
4026 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004027 ConstructKind,
4028 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004029 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004030 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004031 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004032
4033 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004034 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004035 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004036 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004037
Douglas Gregor2f599792010-04-02 18:24:57 +00004038 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004039 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004040
Douglas Gregor51c56d62009-12-14 20:49:26 +00004041 break;
4042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor71d17402009-12-15 00:01:57 +00004044 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004045 step_iterator NextStep = Step;
4046 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004048 NextStep->Kind == SK_ConstructorInitialization) {
4049 // The need for zero-initialization is recorded directly into
4050 // the call to the object's constructor within the next step.
4051 ConstructorInitRequiresZeroInit = true;
4052 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4053 S.getLangOptions().CPlusPlus &&
4054 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004055 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4056 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004058 Kind.getRange().getBegin());
4059
4060 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4061 TSInfo->getType().getNonLValueExprType(S.Context),
4062 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004063 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004064 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004065 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004066 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004067 break;
4068 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004069
4070 case SK_CAssignment: {
4071 QualType SourceType = CurInitExpr->getType();
4072 Sema::AssignConvertType ConvTy =
4073 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00004074
4075 // If this is a call, allow conversion to a transparent union.
4076 if (ConvTy != Sema::Compatible &&
4077 Entity.getKind() == InitializedEntity::EK_Parameter &&
4078 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4079 == Sema::Compatible)
4080 ConvTy = Sema::Compatible;
4081
Douglas Gregora41a8c52010-04-22 00:20:18 +00004082 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004083 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4084 Step->Type, SourceType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004085 CurInitExpr,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004086 getAssignmentAction(Entity),
4087 &Complained)) {
4088 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004089 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004090 } else if (Complained)
4091 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004092
4093 CurInit.release();
4094 CurInit = S.Owned(CurInitExpr);
4095 break;
4096 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004097
4098 case SK_StringInit: {
4099 QualType Ty = Step->Type;
John McCallfef8b342011-02-21 07:57:55 +00004100 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty,
4101 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004102 break;
4103 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004104
4105 case SK_ObjCObjectConversion:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004106 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004107 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004108 S.CastCategory(CurInitExpr));
4109 CurInit.release();
4110 CurInit = S.Owned(CurInitExpr);
4111 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004112
4113 case SK_ArrayInit:
4114 // Okay: we checked everything before creating this step. Note that
4115 // this is a GNU extension.
4116 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
4117 << Step->Type << CurInitExpr->getType()
4118 << CurInitExpr->getSourceRange();
4119
4120 // If the destination type is an incomplete array type, update the
4121 // type accordingly.
4122 if (ResultType) {
4123 if (const IncompleteArrayType *IncompleteDest
4124 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4125 if (const ConstantArrayType *ConstantSource
4126 = S.Context.getAsConstantArrayType(CurInitExpr->getType())) {
4127 *ResultType = S.Context.getConstantArrayType(
4128 IncompleteDest->getElementType(),
4129 ConstantSource->getSize(),
4130 ArrayType::Normal, 0);
4131 }
4132 }
4133 }
4134
4135 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004136 }
4137 }
John McCall15d7d122010-11-11 03:21:53 +00004138
4139 // Diagnose non-fatal problems with the completed initialization.
4140 if (Entity.getKind() == InitializedEntity::EK_Member &&
4141 cast<FieldDecl>(Entity.getDecl())->isBitField())
4142 S.CheckBitFieldInitialization(Kind.getLocation(),
4143 cast<FieldDecl>(Entity.getDecl()),
4144 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145
Douglas Gregor20093b42009-12-09 23:02:17 +00004146 return move(CurInit);
4147}
4148
4149//===----------------------------------------------------------------------===//
4150// Diagnose initialization failures
4151//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004153 const InitializedEntity &Entity,
4154 const InitializationKind &Kind,
4155 Expr **Args, unsigned NumArgs) {
4156 if (SequenceKind != FailedSequence)
4157 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004158
Douglas Gregord6542d82009-12-22 15:35:07 +00004159 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004160 switch (Failure) {
4161 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004162 // FIXME: Customize for the initialized entity?
4163 if (NumArgs == 0)
4164 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4165 << DestType.getNonReferenceType();
4166 else // FIXME: diagnostic below could be better!
4167 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4168 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004169 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170
Douglas Gregor20093b42009-12-09 23:02:17 +00004171 case FK_ArrayNeedsInitList:
4172 case FK_ArrayNeedsInitListOrStringLiteral:
4173 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4174 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4175 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004176
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004177 case FK_ArrayTypeMismatch:
4178 case FK_NonConstantArrayInit:
4179 S.Diag(Kind.getLocation(),
4180 (Failure == FK_ArrayTypeMismatch
4181 ? diag::err_array_init_different_type
4182 : diag::err_array_init_non_constant_array))
4183 << DestType.getNonReferenceType()
4184 << Args[0]->getType()
4185 << Args[0]->getSourceRange();
4186 break;
4187
John McCall6bb80172010-03-30 21:47:33 +00004188 case FK_AddressOfOverloadFailed: {
4189 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004190 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004191 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004192 true,
4193 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004194 break;
John McCall6bb80172010-03-30 21:47:33 +00004195 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004196
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004198 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 switch (FailedOverloadResult) {
4200 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004201 if (Failure == FK_UserConversionOverloadFailed)
4202 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4203 << Args[0]->getType() << DestType
4204 << Args[0]->getSourceRange();
4205 else
4206 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4207 << DestType << Args[0]->getType()
4208 << Args[0]->getSourceRange();
4209
John McCall120d63c2010-08-24 20:38:10 +00004210 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004211 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004212
Douglas Gregor20093b42009-12-09 23:02:17 +00004213 case OR_No_Viable_Function:
4214 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4215 << Args[0]->getType() << DestType.getNonReferenceType()
4216 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004217 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, 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_Deleted: {
4221 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4222 << Args[0]->getType() << DestType.getNonReferenceType()
4223 << Args[0]->getSourceRange();
4224 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004225 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004226 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4227 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004228 if (Ovl == OR_Deleted) {
4229 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4230 << Best->Function->isDeleted();
4231 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004232 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004233 }
4234 break;
4235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236
Douglas Gregor20093b42009-12-09 23:02:17 +00004237 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004238 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004239 break;
4240 }
4241 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242
Douglas Gregor20093b42009-12-09 23:02:17 +00004243 case FK_NonConstLValueReferenceBindingToTemporary:
4244 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004245 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004246 Failure == FK_NonConstLValueReferenceBindingToTemporary
4247 ? diag::err_lvalue_reference_bind_to_temporary
4248 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004249 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004250 << DestType.getNonReferenceType()
4251 << Args[0]->getType()
4252 << Args[0]->getSourceRange();
4253 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004254
Douglas Gregor20093b42009-12-09 23:02:17 +00004255 case FK_RValueReferenceBindingToLValue:
4256 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004257 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004258 << Args[0]->getSourceRange();
4259 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260
Douglas Gregor20093b42009-12-09 23:02:17 +00004261 case FK_ReferenceInitDropsQualifiers:
4262 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4263 << DestType.getNonReferenceType()
4264 << Args[0]->getType()
4265 << Args[0]->getSourceRange();
4266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267
Douglas Gregor20093b42009-12-09 23:02:17 +00004268 case FK_ReferenceInitFailed:
4269 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4270 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004271 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004272 << Args[0]->getType()
4273 << Args[0]->getSourceRange();
4274 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004276 case FK_ConversionFailed: {
4277 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004278 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4279 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004280 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004281 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004282 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004283 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004284 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004285 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004286 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004287 SourceRange R;
4288
4289 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004290 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004291 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004293 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004294
Douglas Gregor19311e72010-09-08 21:40:08 +00004295 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4296 if (Kind.isCStyleOrFunctionalCast())
4297 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4298 << R;
4299 else
4300 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4301 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004302 break;
4303 }
4304
4305 case FK_ReferenceBindingToInitList:
4306 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4307 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4308 break;
4309
4310 case FK_InitListBadDestinationType:
4311 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4312 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4313 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
Douglas Gregor51c56d62009-12-14 20:49:26 +00004315 case FK_ConstructorOverloadFailed: {
4316 SourceRange ArgsRange;
4317 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004319 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004320
Douglas Gregor51c56d62009-12-14 20:49:26 +00004321 // FIXME: Using "DestType" for the entity we're printing is probably
4322 // bad.
4323 switch (FailedOverloadResult) {
4324 case OR_Ambiguous:
4325 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4326 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004327 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4328 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004329 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004330
Douglas Gregor51c56d62009-12-14 20:49:26 +00004331 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004332 if (Kind.getKind() == InitializationKind::IK_Default &&
4333 (Entity.getKind() == InitializedEntity::EK_Base ||
4334 Entity.getKind() == InitializedEntity::EK_Member) &&
4335 isa<CXXConstructorDecl>(S.CurContext)) {
4336 // This is implicit default initialization of a member or
4337 // base within a constructor. If no viable function was
4338 // found, notify the user that she needs to explicitly
4339 // initialize this base/member.
4340 CXXConstructorDecl *Constructor
4341 = cast<CXXConstructorDecl>(S.CurContext);
4342 if (Entity.getKind() == InitializedEntity::EK_Base) {
4343 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4344 << Constructor->isImplicit()
4345 << S.Context.getTypeDeclType(Constructor->getParent())
4346 << /*base=*/0
4347 << Entity.getType();
4348
4349 RecordDecl *BaseDecl
4350 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4351 ->getDecl();
4352 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4353 << S.Context.getTagDeclType(BaseDecl);
4354 } else {
4355 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4356 << Constructor->isImplicit()
4357 << S.Context.getTypeDeclType(Constructor->getParent())
4358 << /*member=*/1
4359 << Entity.getName();
4360 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4361
4362 if (const RecordType *Record
4363 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004364 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004365 diag::note_previous_decl)
4366 << S.Context.getTagDeclType(Record->getDecl());
4367 }
4368 break;
4369 }
4370
Douglas Gregor51c56d62009-12-14 20:49:26 +00004371 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4372 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004373 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004374 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375
Douglas Gregor51c56d62009-12-14 20:49:26 +00004376 case OR_Deleted: {
4377 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4378 << true << DestType << ArgsRange;
4379 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004380 OverloadingResult Ovl
4381 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004382 if (Ovl == OR_Deleted) {
4383 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4384 << Best->Function->isDeleted();
4385 } else {
4386 llvm_unreachable("Inconsistent overload resolution?");
4387 }
4388 break;
4389 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004390
Douglas Gregor51c56d62009-12-14 20:49:26 +00004391 case OR_Success:
4392 llvm_unreachable("Conversion did not fail!");
4393 break;
4394 }
4395 break;
4396 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004397
Douglas Gregor99a2e602009-12-16 01:38:02 +00004398 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004399 if (Entity.getKind() == InitializedEntity::EK_Member &&
4400 isa<CXXConstructorDecl>(S.CurContext)) {
4401 // This is implicit default-initialization of a const member in
4402 // a constructor. Complain that it needs to be explicitly
4403 // initialized.
4404 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4405 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4406 << Constructor->isImplicit()
4407 << S.Context.getTypeDeclType(Constructor->getParent())
4408 << /*const=*/1
4409 << Entity.getName();
4410 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4411 << Entity.getName();
4412 } else {
4413 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4414 << DestType << (bool)DestType->getAs<RecordType>();
4415 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004416 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004418 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004419 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004420 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004421 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004423
Douglas Gregora41a8c52010-04-22 00:20:18 +00004424 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004425 return true;
4426}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004427
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004428void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4429 switch (SequenceKind) {
4430 case FailedSequence: {
4431 OS << "Failed sequence: ";
4432 switch (Failure) {
4433 case FK_TooManyInitsForReference:
4434 OS << "too many initializers for reference";
4435 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004437 case FK_ArrayNeedsInitList:
4438 OS << "array requires initializer list";
4439 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004440
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004441 case FK_ArrayNeedsInitListOrStringLiteral:
4442 OS << "array requires initializer list or string literal";
4443 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004444
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004445 case FK_ArrayTypeMismatch:
4446 OS << "array type mismatch";
4447 break;
4448
4449 case FK_NonConstantArrayInit:
4450 OS << "non-constant array initializer";
4451 break;
4452
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004453 case FK_AddressOfOverloadFailed:
4454 OS << "address of overloaded function failed";
4455 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004456
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004457 case FK_ReferenceInitOverloadFailed:
4458 OS << "overload resolution for reference initialization failed";
4459 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004460
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004461 case FK_NonConstLValueReferenceBindingToTemporary:
4462 OS << "non-const lvalue reference bound to temporary";
4463 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004465 case FK_NonConstLValueReferenceBindingToUnrelated:
4466 OS << "non-const lvalue reference bound to unrelated type";
4467 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004469 case FK_RValueReferenceBindingToLValue:
4470 OS << "rvalue reference bound to an lvalue";
4471 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004472
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004473 case FK_ReferenceInitDropsQualifiers:
4474 OS << "reference initialization drops qualifiers";
4475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004477 case FK_ReferenceInitFailed:
4478 OS << "reference initialization failed";
4479 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004481 case FK_ConversionFailed:
4482 OS << "conversion failed";
4483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004485 case FK_TooManyInitsForScalar:
4486 OS << "too many initializers for scalar";
4487 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004488
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004489 case FK_ReferenceBindingToInitList:
4490 OS << "referencing binding to initializer list";
4491 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004493 case FK_InitListBadDestinationType:
4494 OS << "initializer list for non-aggregate, non-scalar type";
4495 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004497 case FK_UserConversionOverloadFailed:
4498 OS << "overloading failed for user-defined conversion";
4499 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004501 case FK_ConstructorOverloadFailed:
4502 OS << "constructor overloading failed";
4503 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004505 case FK_DefaultInitOfConst:
4506 OS << "default initialization of a const variable";
4507 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004509 case FK_Incomplete:
4510 OS << "initialization of incomplete type";
4511 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004513 OS << '\n';
4514 return;
4515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004516
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004517 case DependentSequence:
4518 OS << "Dependent sequence: ";
4519 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004521 case UserDefinedConversion:
4522 OS << "User-defined conversion sequence: ";
4523 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004525 case ConstructorInitialization:
4526 OS << "Constructor initialization sequence: ";
4527 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004528
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004529 case ReferenceBinding:
4530 OS << "Reference binding: ";
4531 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004533 case ListInitialization:
4534 OS << "List initialization: ";
4535 break;
4536
4537 case ZeroInitialization:
4538 OS << "Zero initialization\n";
4539 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004541 case NoInitialization:
4542 OS << "No initialization\n";
4543 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004544
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004545 case StandardConversion:
4546 OS << "Standard conversion: ";
4547 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004549 case CAssignment:
4550 OS << "C assignment: ";
4551 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004552
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004553 case StringInit:
4554 OS << "String initialization: ";
4555 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004556
4557 case ArrayInit:
4558 OS << "Array initialization: ";
4559 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004560 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004561
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004562 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4563 if (S != step_begin()) {
4564 OS << " -> ";
4565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004566
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004567 switch (S->Kind) {
4568 case SK_ResolveAddressOfOverloadedFunction:
4569 OS << "resolve address of overloaded function";
4570 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004571
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004572 case SK_CastDerivedToBaseRValue:
4573 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4574 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004575
Sebastian Redl906082e2010-07-20 04:20:21 +00004576 case SK_CastDerivedToBaseXValue:
4577 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4578 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004579
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004580 case SK_CastDerivedToBaseLValue:
4581 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4582 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004584 case SK_BindReference:
4585 OS << "bind reference to lvalue";
4586 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004588 case SK_BindReferenceToTemporary:
4589 OS << "bind reference to a temporary";
4590 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004591
Douglas Gregor523d46a2010-04-18 07:40:54 +00004592 case SK_ExtraneousCopyToTemporary:
4593 OS << "extraneous C++03 copy to temporary";
4594 break;
4595
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004596 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004597 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004598 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004599
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004600 case SK_QualificationConversionRValue:
4601 OS << "qualification conversion (rvalue)";
4602
Sebastian Redl906082e2010-07-20 04:20:21 +00004603 case SK_QualificationConversionXValue:
4604 OS << "qualification conversion (xvalue)";
4605
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004606 case SK_QualificationConversionLValue:
4607 OS << "qualification conversion (lvalue)";
4608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004609
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004610 case SK_ConversionSequence:
4611 OS << "implicit conversion sequence (";
4612 S->ICS->DebugPrint(); // FIXME: use OS
4613 OS << ")";
4614 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004615
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004616 case SK_ListInitialization:
4617 OS << "list initialization";
4618 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004620 case SK_ConstructorInitialization:
4621 OS << "constructor initialization";
4622 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004624 case SK_ZeroInitialization:
4625 OS << "zero initialization";
4626 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004628 case SK_CAssignment:
4629 OS << "C assignment";
4630 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004631
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004632 case SK_StringInit:
4633 OS << "string initialization";
4634 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004635
4636 case SK_ObjCObjectConversion:
4637 OS << "Objective-C object conversion";
4638 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004639
4640 case SK_ArrayInit:
4641 OS << "array initialization";
4642 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004643 }
4644 }
4645}
4646
4647void InitializationSequence::dump() const {
4648 dump(llvm::errs());
4649}
4650
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004651//===----------------------------------------------------------------------===//
4652// Initialization helper functions
4653//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004655Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4656 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004657 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004658 if (Init.isInvalid())
4659 return ExprError();
4660
John McCall15d7d122010-11-11 03:21:53 +00004661 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004662 assert(InitE && "No initialization expression?");
4663
4664 if (EqualLoc.isInvalid())
4665 EqualLoc = InitE->getLocStart();
4666
4667 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4668 EqualLoc);
4669 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4670 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004671 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004672}