blob: 835d837e4c0ae21edef984a7b00e8a652e8915c5 [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCallce6c9b72011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
John McCallce6c9b72011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCallfef8b342011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000090 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000091 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Eli Friedman8718a6a2009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000094
Eli Friedmanbc34b1d2011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Eli Friedman8718a6a2009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000126}
127
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregor9e80f722009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000159namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000236
Douglas Gregord6d37de2009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner8b419b92009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278
Douglas Gregord6d37de2009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000287
John McCall60d7b3a2010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000299 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000300 // Value-initialization requires a constructor call, so
301 // extend the initializer list to include the constructor
302 // call and make a note that we'll need to take another pass
303 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000304 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000305 RequiresSecondPass = true;
306 }
307 } else if (InitListExpr *InnerILE
308 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000309 FillInValueInitializations(MemberEntity, InnerILE,
310 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311}
312
Douglas Gregor4c678342009-01-28 21:54:33 +0000313/// Recursively replaces NULL values within the given initializer list
314/// with expressions that perform value-initialization of the
315/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000316void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000317InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
318 InitListExpr *ILE,
319 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000320 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000321 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000322 SourceLocation Loc = ILE->getSourceRange().getBegin();
323 if (ILE->getSyntacticForm())
324 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Ted Kremenek6217b802009-07-29 21:53:49 +0000326 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 if (RType->getDecl()->isUnion() &&
328 ILE->getInitializedFieldInUnion())
329 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
330 Entity, ILE, RequiresSecondPass);
331 else {
332 unsigned Init = 0;
333 for (RecordDecl::field_iterator
334 Field = RType->getDecl()->field_begin(),
335 FieldEnd = RType->getDecl()->field_end();
336 Field != FieldEnd; ++Field) {
337 if (Field->isUnnamedBitfield())
338 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000339
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000342
343 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
344 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346
Douglas Gregord6d37de2009-12-22 00:05:34 +0000347 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000348
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349 // Only look at the first initialization of a union.
350 if (RType->getDecl()->isUnion())
351 break;
352 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 }
354
355 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000356 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000357
358 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000360 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000361 unsigned NumInits = ILE->getNumInits();
362 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000363 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000364 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
366 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000368 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000369 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000371 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000373 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000374 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000379 if (hadError)
380 return;
381
Anders Carlssond3d824d2010-01-23 04:34:47 +0000382 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
383 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 ElementEntity.setElementIndex(Init);
385
Douglas Gregor87fd7032009-02-02 17:43:21 +0000386 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000387 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
388 true);
389 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
390 if (!InitSeq) {
391 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000392 hadError = true;
393 return;
394 }
395
John McCall60d7b3a2010-08-24 06:29:42 +0000396 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000397 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000399 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000400 return;
401 }
402
403 if (hadError) {
404 // Do nothing
405 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000406 // For arrays, just set the expression used for value-initialization
407 // of the "holes" in the array.
408 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
409 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
410 else
411 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000412 } else {
413 // For arrays, just set the expression used for value-initialization
414 // of the rest of elements and exit.
415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
416 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
417 return;
418 }
419
Sebastian Redl7491c492011-06-05 13:59:11 +0000420 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000421 // Value-initialization requires a constructor call, so
422 // extend the initializer list to include the constructor
423 // call and make a note that we'll need to take another pass
424 // through the initializer list.
425 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
426 RequiresSecondPass = true;
427 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000428 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000429 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000430 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
431 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000432 }
433}
434
Chris Lattner68355a52009-01-29 05:10:57 +0000435
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000436InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
437 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000438 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000439 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000440
Eli Friedmanb85f7072008-05-19 19:16:24 +0000441 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000444 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000446 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000447 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000448
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000449 if (!hadError) {
450 bool RequiresSecondPass = false;
451 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000452 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000453 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000454 RequiresSecondPass);
455 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000456}
457
458int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000459 // FIXME: use a proper constant
460 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000461 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000462 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000463 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
464 }
465 return maxElements;
466}
467
468int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000469 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000470 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000471 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000472 Field = structDecl->field_begin(),
473 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000474 Field != FieldEnd; ++Field) {
475 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
476 ++InitializableMembers;
477 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000478 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000479 return std::min(InitializableMembers, 1);
480 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000481}
482
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000483void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000484 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 QualType T, unsigned &Index,
486 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000487 unsigned &StructuredIndex,
488 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000489 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Steve Naroff0cca7492008-05-01 22:18:59 +0000491 if (T->isArrayType())
492 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000493 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000494 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000495 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000496 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000497 else
498 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000499
Eli Friedman402256f2008-05-25 13:49:22 +0000500 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000501 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000502 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000504 hadError = true;
505 return;
506 }
507
Douglas Gregor4c678342009-01-28 21:54:33 +0000508 // Build a structured initializer list corresponding to this subobject.
509 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000510 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
511 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000512 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
513 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000515
Douglas Gregor4c678342009-01-28 21:54:33 +0000516 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000517 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000518 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000519 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000521 StructuredSubobjectInitIndex,
522 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000523 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000524 StructuredSubobjectInitList->setType(T);
525
Douglas Gregored8a93d2009-03-01 17:12:46 +0000526 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000527 // range corresponds with the end of the last initializer it used.
528 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000529 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000530 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
531 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000534 // Warn about missing braces.
535 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000536 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
537 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000538 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000540 "{")
541 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000542 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000543 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000544 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000545}
546
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000547void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000548 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000549 unsigned &Index,
550 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000551 unsigned &StructuredIndex,
552 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000553 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000554 SyntacticToSemantic[IList] = StructuredList;
555 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000557 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000558 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
559 IList->setType(ExprTy);
560 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000561 if (hadError)
562 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000563
Eli Friedman638e1442008-05-25 13:22:35 +0000564 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000565 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000566 if (StructuredIndex == 1 &&
567 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000568 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000569 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000570 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000571 hadError = true;
572 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000573 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000574 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000575 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000576 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000577 // Don't complain for incomplete types, since we'll get an error
578 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000579 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000580 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000581 CurrentObjectType->isArrayType()? 0 :
582 CurrentObjectType->isVectorType()? 1 :
583 CurrentObjectType->isScalarType()? 2 :
584 CurrentObjectType->isUnionType()? 3 :
585 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000586
587 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000588 if (SemaRef.getLangOptions().CPlusPlus) {
589 DK = diag::err_excess_initializers;
590 hadError = true;
591 }
Nate Begeman08634522009-07-07 21:53:06 +0000592 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
593 DK = diag::err_excess_initializers;
594 hadError = true;
595 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000596
Chris Lattner08202542009-02-24 22:50:46 +0000597 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000598 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000599 }
600 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000601
Eli Friedman759f2522009-05-16 11:45:48 +0000602 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000603 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000604 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000605 << FixItHint::CreateRemoval(IList->getLocStart())
606 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000607}
608
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000609void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000610 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000611 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000612 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000613 unsigned &Index,
614 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000615 unsigned &StructuredIndex,
616 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000617 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000618 CheckScalarType(Entity, IList, DeclType, Index,
619 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000620 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000622 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000623 } else if (DeclType->isAggregateType()) {
624 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000625 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000626 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000627 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000628 StructuredList, StructuredIndex,
629 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000630 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000631 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000632 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000633 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000635 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000636 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000637 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000639 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
640 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000642 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000643 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000644 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000645 } else if (DeclType->isRecordType()) {
646 // C++ [dcl.init]p14:
647 // [...] If the class is an aggregate (8.5.1), and the initializer
648 // is a brace-enclosed list, see 8.5.1.
649 //
650 // Note: 8.5.1 is handled below; here, we diagnose the case where
651 // we have an initializer list and a destination type that is not
652 // an aggregate.
653 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000655 << DeclType << IList->getSourceRange();
656 hadError = true;
657 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000658 CheckReferenceType(Entity, IList, DeclType, Index,
659 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000660 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000661 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
662 << DeclType;
663 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000664 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
666 << DeclType;
667 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000668 }
669}
670
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000671void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000672 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000673 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
676 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000677 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000678 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
679 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000681 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 = getStructuredSubobjectInit(IList, Index, ElemType,
683 StructuredList, StructuredIndex,
684 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000685 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000686 newStructuredList, newStructuredIndex);
687 ++StructuredIndex;
688 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000689 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000690 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000691 return CheckScalarType(Entity, IList, ElemType, Index,
692 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000693 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000694 return CheckReferenceType(Entity, IList, ElemType, Index,
695 StructuredList, StructuredIndex);
696 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000697
John McCallfef8b342011-02-21 07:57:55 +0000698 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
699 // arrayType can be incomplete if we're initializing a flexible
700 // array member. There's nothing we can do with the completed
701 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000702
John McCallfef8b342011-02-21 07:57:55 +0000703 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
704 CheckStringInit(Str, ElemType, arrayType, SemaRef);
705 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000706 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000707 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000708 }
John McCallfef8b342011-02-21 07:57:55 +0000709
710 // Fall through for subaggregate initialization.
711
712 } else if (SemaRef.getLangOptions().CPlusPlus) {
713 // C++ [dcl.init.aggr]p12:
714 // All implicit type conversions (clause 4) are considered when
715 // initializing the aggregate member with an ini- tializer from
716 // an initializer-list. If the initializer can initialize a
717 // member, the member is initialized. [...]
718
719 // FIXME: Better EqualLoc?
720 InitializationKind Kind =
721 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
722 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
723
724 if (Seq) {
725 ExprResult Result =
726 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
727 if (Result.isInvalid())
728 hadError = true;
729
730 UpdateStructuredListElement(StructuredList, StructuredIndex,
731 Result.takeAs<Expr>());
732 ++Index;
733 return;
734 }
735
736 // Fall through for subaggregate initialization
737 } else {
738 // C99 6.7.8p13:
739 //
740 // The initializer for a structure or union object that has
741 // automatic storage duration shall be either an initializer
742 // list as described below, or a single expression that has
743 // compatible structure or union type. In the latter case, the
744 // initial value of the object, including unnamed members, is
745 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000746 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000747 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000748 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000749 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000750 if (ExprRes.isInvalid())
751 hadError = true;
752 else {
753 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
754 if (ExprRes.isInvalid())
755 hadError = true;
756 }
757 UpdateStructuredListElement(StructuredList, StructuredIndex,
758 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000759 ++Index;
760 return;
761 }
John Wiegley429bb272011-04-08 18:41:53 +0000762 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000763 // Fall through for subaggregate initialization
764 }
765
766 // C++ [dcl.init.aggr]p12:
767 //
768 // [...] Otherwise, if the member is itself a non-empty
769 // subaggregate, brace elision is assumed and the initializer is
770 // considered for the initialization of the first member of
771 // the subaggregate.
772 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
773 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
774 StructuredIndex);
775 ++StructuredIndex;
776 } else {
777 // We cannot initialize this element, so let
778 // PerformCopyInitialization produce the appropriate diagnostic.
779 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
780 SemaRef.Owned(expr));
781 hadError = true;
782 ++Index;
783 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000784 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000785}
786
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000787void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000788 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000789 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000792 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000793 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000794 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000795 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 ++Index;
797 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000798 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000799 }
John McCallb934c2d2010-11-11 00:46:36 +0000800
801 Expr *expr = IList->getInit(Index);
802 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
803 SemaRef.Diag(SubIList->getLocStart(),
804 diag::warn_many_braces_around_scalar_init)
805 << SubIList->getSourceRange();
806
807 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
808 StructuredIndex);
809 return;
810 } else if (isa<DesignatedInitExpr>(expr)) {
811 SemaRef.Diag(expr->getSourceRange().getBegin(),
812 diag::err_designator_for_scalar_init)
813 << DeclType << expr->getSourceRange();
814 hadError = true;
815 ++Index;
816 ++StructuredIndex;
817 return;
818 }
819
820 ExprResult Result =
821 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
822 SemaRef.Owned(expr));
823
824 Expr *ResultExpr = 0;
825
826 if (Result.isInvalid())
827 hadError = true; // types weren't compatible.
828 else {
829 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000830
John McCallb934c2d2010-11-11 00:46:36 +0000831 if (ResultExpr != expr) {
832 // The type was promoted, update initializer list.
833 IList->setInit(Index, ResultExpr);
834 }
835 }
836 if (hadError)
837 ++StructuredIndex;
838 else
839 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
840 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000841}
842
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000843void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
844 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000845 unsigned &Index,
846 InitListExpr *StructuredList,
847 unsigned &StructuredIndex) {
848 if (Index < IList->getNumInits()) {
849 Expr *expr = IList->getInit(Index);
850 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000851 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000852 << DeclType << IList->getSourceRange();
853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
856 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000857 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000858
John McCall60d7b3a2010-08-24 06:29:42 +0000859 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000860 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
861 SemaRef.Owned(expr));
862
863 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000864 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000865
866 expr = Result.takeAs<Expr>();
867 IList->setInit(Index, expr);
868
Douglas Gregor930d8b52009-01-30 22:09:00 +0000869 if (hadError)
870 ++StructuredIndex;
871 else
872 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
873 ++Index;
874 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000875 // FIXME: It would be wonderful if we could point at the actual member. In
876 // general, it would be useful to pass location information down the stack,
877 // so that we know the location (or decl) of the "current object" being
878 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000879 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000880 diag::err_init_reference_member_uninitialized)
881 << DeclType
882 << IList->getSourceRange();
883 hadError = true;
884 ++Index;
885 ++StructuredIndex;
886 return;
887 }
888}
889
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000890void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000891 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000892 unsigned &Index,
893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000895 if (Index >= IList->getNumInits())
896 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
John McCall20e047a2010-10-30 00:11:39 +0000898 const VectorType *VT = DeclType->getAs<VectorType>();
899 unsigned maxElements = VT->getNumElements();
900 unsigned numEltsInit = 0;
901 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000902
John McCall20e047a2010-10-30 00:11:39 +0000903 if (!SemaRef.getLangOptions().OpenCL) {
904 // If the initializing element is a vector, try to copy-initialize
905 // instead of breaking it apart (which is doomed to failure anyway).
906 Expr *Init = IList->getInit(Index);
907 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
908 ExprResult Result =
909 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
910 SemaRef.Owned(Init));
911
912 Expr *ResultExpr = 0;
913 if (Result.isInvalid())
914 hadError = true; // types weren't compatible.
915 else {
916 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (ResultExpr != Init) {
919 // The type was promoted, update initializer list.
920 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000921 }
922 }
John McCall20e047a2010-10-30 00:11:39 +0000923 if (hadError)
924 ++StructuredIndex;
925 else
926 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
927 ++Index;
928 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930
John McCall20e047a2010-10-30 00:11:39 +0000931 InitializedEntity ElementEntity =
932 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-10-30 00:11:39 +0000934 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
935 // Don't attempt to go past the end of the init list
936 if (Index >= IList->getNumInits())
937 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000938
John McCall20e047a2010-10-30 00:11:39 +0000939 ElementEntity.setElementIndex(Index);
940 CheckSubElementType(ElementEntity, IList, elementType, Index,
941 StructuredList, StructuredIndex);
942 }
943 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000944 }
John McCall20e047a2010-10-30 00:11:39 +0000945
946 InitializedEntity ElementEntity =
947 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000948
John McCall20e047a2010-10-30 00:11:39 +0000949 // OpenCL initializers allows vectors to be constructed from vectors.
950 for (unsigned i = 0; i < maxElements; ++i) {
951 // Don't attempt to go past the end of the init list
952 if (Index >= IList->getNumInits())
953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
John McCall20e047a2010-10-30 00:11:39 +0000955 ElementEntity.setElementIndex(Index);
956
957 QualType IType = IList->getInit(Index)->getType();
958 if (!IType->isVectorType()) {
959 CheckSubElementType(ElementEntity, IList, elementType, Index,
960 StructuredList, StructuredIndex);
961 ++numEltsInit;
962 } else {
963 QualType VecType;
964 const VectorType *IVT = IType->getAs<VectorType>();
965 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000966
John McCall20e047a2010-10-30 00:11:39 +0000967 if (IType->isExtVectorType())
968 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
969 else
970 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000971 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000972 CheckSubElementType(ElementEntity, IList, VecType, Index,
973 StructuredList, StructuredIndex);
974 numEltsInit += numIElts;
975 }
976 }
977
978 // OpenCL requires all elements to be initialized.
979 if (numEltsInit != maxElements)
980 if (SemaRef.getLangOptions().OpenCL)
981 SemaRef.Diag(IList->getSourceRange().getBegin(),
982 diag::err_vector_incorrect_num_initializers)
983 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000984}
985
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000986void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000987 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000988 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000989 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000990 unsigned &Index,
991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +0000993 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
994
Steve Naroff0cca7492008-05-01 22:18:59 +0000995 // Check for the special-case of initializing an array with a string.
996 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +0000997 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +0000998 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +0000999 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001000 // We place the string literal directly into the resulting
1001 // initializer list. This is the only place where the structure
1002 // of the structured initializer list doesn't match exactly,
1003 // because doing so would involve allocating one character
1004 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001005 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001006 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001007 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001008 return;
1009 }
1010 }
John McCallce6c9b72011-02-21 07:22:22 +00001011 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001012 // Check for VLAs; in standard C it would be possible to check this
1013 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1014 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001015 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001016 diag::err_variable_object_no_init)
1017 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001018 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001019 ++Index;
1020 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001021 return;
1022 }
1023
Douglas Gregor05c13a32009-01-22 00:58:24 +00001024 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001025 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1026 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001027 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001028 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001029 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001030 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001031 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001032 maxElementsKnown = true;
1033 }
1034
John McCallce6c9b72011-02-21 07:22:22 +00001035 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001036 while (Index < IList->getNumInits()) {
1037 Expr *Init = IList->getInit(Index);
1038 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001039 // If we're not the subobject that matches up with the '{' for
1040 // the designator, we shouldn't be handling the
1041 // designator. Return immediately.
1042 if (!SubobjectIsDesignatorContext)
1043 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001044
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001045 // Handle this designated initializer. elementIndex will be
1046 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001047 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001048 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001049 StructuredList, StructuredIndex, true,
1050 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001051 hadError = true;
1052 continue;
1053 }
1054
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001055 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001056 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001057 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001058 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001059 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001060
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // If the array is of incomplete type, keep track of the number of
1062 // elements in the initializer.
1063 if (!maxElementsKnown && elementIndex > maxElements)
1064 maxElements = elementIndex;
1065
Douglas Gregor05c13a32009-01-22 00:58:24 +00001066 continue;
1067 }
1068
1069 // If we know the maximum number of elements, and we've already
1070 // hit it, stop consuming elements in the initializer list.
1071 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001072 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001073
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001074 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001076 Entity);
1077 // Check this element.
1078 CheckSubElementType(ElementEntity, IList, elementType, Index,
1079 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001080 ++elementIndex;
1081
1082 // If the array is of incomplete type, keep track of the number of
1083 // elements in the initializer.
1084 if (!maxElementsKnown && elementIndex > maxElements)
1085 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001086 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001087 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001089 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001090 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001091 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001092 // Sizing an array implicitly to zero is not allowed by ISO C,
1093 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001094 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001095 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001096 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001097
Mike Stump1eb44332009-09-09 15:08:12 +00001098 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001099 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001100 }
1101}
1102
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001103void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001104 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001105 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001106 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001107 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001108 unsigned &Index,
1109 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001110 unsigned &StructuredIndex,
1111 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Eli Friedmanb85f7072008-05-19 19:16:24 +00001114 // If the record is invalid, some of it's members are invalid. To avoid
1115 // confusion, we forgo checking the intializer for the entire record.
1116 if (structDecl->isInvalidDecl()) {
1117 hadError = true;
1118 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001119 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001120
1121 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1122 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001123 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001124 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001125 Field != FieldEnd; ++Field) {
1126 if (Field->getDeclName()) {
1127 StructuredList->setInitializedFieldInUnion(*Field);
1128 break;
1129 }
1130 }
1131 return;
1132 }
1133
Douglas Gregor05c13a32009-01-22 00:58:24 +00001134 // If structDecl is a forward declaration, this loop won't do
1135 // anything except look at designated initializers; That's okay,
1136 // because an error should get printed out elsewhere. It might be
1137 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001138 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001139 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001140 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001141 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001142 while (Index < IList->getNumInits()) {
1143 Expr *Init = IList->getInit(Index);
1144
1145 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001146 // If we're not the subobject that matches up with the '{' for
1147 // the designator, we shouldn't be handling the
1148 // designator. Return immediately.
1149 if (!SubobjectIsDesignatorContext)
1150 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001151
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001152 // Handle this designated initializer. Field will be updated to
1153 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001154 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001155 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001156 StructuredList, StructuredIndex,
1157 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001158 hadError = true;
1159
Douglas Gregordfb5e592009-02-12 19:00:39 +00001160 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001161
1162 // Disable check for missing fields when designators are used.
1163 // This matches gcc behaviour.
1164 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001165 continue;
1166 }
1167
1168 if (Field == FieldEnd) {
1169 // We've run out of fields. We're done.
1170 break;
1171 }
1172
Douglas Gregordfb5e592009-02-12 19:00:39 +00001173 // We've already initialized a member of a union. We're done.
1174 if (InitializedSomething && DeclType->isUnionType())
1175 break;
1176
Douglas Gregor44b43212008-12-11 16:49:14 +00001177 // If we've hit the flexible array member at the end, we're done.
1178 if (Field->getType()->isIncompleteArrayType())
1179 break;
1180
Douglas Gregor0bb76892009-01-29 16:53:55 +00001181 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001182 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001183 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001184 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001185 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001186
Douglas Gregor54001c12011-06-29 21:51:31 +00001187 // Make sure we can use this declaration.
1188 if (SemaRef.DiagnoseUseOfDecl(*Field,
1189 IList->getInit(Index)->getLocStart())) {
1190 ++Index;
1191 ++Field;
1192 hadError = true;
1193 continue;
1194 }
1195
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001196 InitializedEntity MemberEntity =
1197 InitializedEntity::InitializeMember(*Field, &Entity);
1198 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1199 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001200 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001201
1202 if (DeclType->isUnionType()) {
1203 // Initialize the first field within the union.
1204 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001205 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001206
1207 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001208 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001209
John McCall80639de2010-03-11 19:32:38 +00001210 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001211 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001212 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1213 // It is possible we have one or more unnamed bitfields remaining.
1214 // Find first (if any) named field and emit warning.
1215 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1216 it != end; ++it) {
1217 if (!it->isUnnamedBitfield()) {
1218 SemaRef.Diag(IList->getSourceRange().getEnd(),
1219 diag::warn_missing_field_initializers) << it->getName();
1220 break;
1221 }
1222 }
1223 }
1224
Mike Stump1eb44332009-09-09 15:08:12 +00001225 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001226 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001227 return;
1228
1229 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001230 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001231 (!isa<InitListExpr>(IList->getInit(Index)) ||
1232 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001234 diag::err_flexible_array_init_nonempty)
1235 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001236 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001237 << *Field;
1238 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001239 ++Index;
1240 return;
1241 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001242 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001243 diag::ext_flexible_array_init)
1244 << IList->getInit(Index)->getSourceRange().getBegin();
1245 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1246 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001247 }
1248
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001249 InitializedEntity MemberEntity =
1250 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001251
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001252 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001254 StructuredList, StructuredIndex);
1255 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001256 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001257 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001258}
Steve Naroff0cca7492008-05-01 22:18:59 +00001259
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001260/// \brief Expand a field designator that refers to a member of an
1261/// anonymous struct or union into a series of field designators that
1262/// refers to the field within the appropriate subobject.
1263///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001264static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001265 DesignatedInitExpr *DIE,
1266 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001267 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001268 typedef DesignatedInitExpr::Designator Designator;
1269
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001270 // Build the replacement designators.
1271 llvm::SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001272 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1273 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1274 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001275 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001276 DIE->getDesignator(DesigIdx)->getDotLoc(),
1277 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1278 else
1279 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1280 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001281 assert(isa<FieldDecl>(*PI));
1282 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001283 }
1284
1285 // Expand the current designator into the set of replacement
1286 // designators, so we have a full subobject path down to where the
1287 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001288 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001289 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001290}
Mike Stump1eb44332009-09-09 15:08:12 +00001291
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001293/// corresponds to FieldName.
1294static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1295 IdentifierInfo *FieldName) {
1296 assert(AnonField->isAnonymousStructOrUnion());
1297 Decl *NextDecl = AnonField->getNextDeclInContext();
1298 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1299 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1300 return IF;
1301 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001302 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001303 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001304}
1305
Douglas Gregor05c13a32009-01-22 00:58:24 +00001306/// @brief Check the well-formedness of a C99 designated initializer.
1307///
1308/// Determines whether the designated initializer @p DIE, which
1309/// resides at the given @p Index within the initializer list @p
1310/// IList, is well-formed for a current object of type @p DeclType
1311/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001312/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001313/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001314///
1315/// @param IList The initializer list in which this designated
1316/// initializer occurs.
1317///
Douglas Gregor71199712009-04-15 04:56:10 +00001318/// @param DIE The designated initializer expression.
1319///
1320/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001321///
1322/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1323/// into which the designation in @p DIE should refer.
1324///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001325/// @param NextField If non-NULL and the first designator in @p DIE is
1326/// a field, this will be set to the field declaration corresponding
1327/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001328///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001329/// @param NextElementIndex If non-NULL and the first designator in @p
1330/// DIE is an array designator or GNU array-range designator, this
1331/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001332///
1333/// @param Index Index into @p IList where the designated initializer
1334/// @p DIE occurs.
1335///
Douglas Gregor4c678342009-01-28 21:54:33 +00001336/// @param StructuredList The initializer list expression that
1337/// describes all of the subobject initializers in the order they'll
1338/// actually be initialized.
1339///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001340/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001341bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001342InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001343 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001344 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001345 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001346 QualType &CurrentObjectType,
1347 RecordDecl::field_iterator *NextField,
1348 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 unsigned &Index,
1350 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001351 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001352 bool FinishSubobjectInit,
1353 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001354 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001355 // Check the actual initialization for the designated object type.
1356 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001357
1358 // Temporarily remove the designator expression from the
1359 // initializer list that the child calls see, so that we don't try
1360 // to re-process the designator.
1361 unsigned OldIndex = Index;
1362 IList->setInit(OldIndex, DIE->getInit());
1363
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001364 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001366
1367 // Restore the designated initializer expression in the syntactic
1368 // form of the initializer list.
1369 if (IList->getInit(OldIndex) != DIE->getInit())
1370 DIE->setInit(IList->getInit(OldIndex));
1371 IList->setInit(OldIndex, DIE);
1372
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001373 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001374 }
1375
Douglas Gregor71199712009-04-15 04:56:10 +00001376 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001377 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001378 "Need a non-designated initializer list to start from");
1379
Douglas Gregor71199712009-04-15 04:56:10 +00001380 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 // Determine the structural initializer list that corresponds to the
1382 // current subobject.
1383 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001384 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001385 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 SourceRange(D->getStartLocation(),
1387 DIE->getSourceRange().getEnd()));
1388 assert(StructuredList && "Expected a structured initializer list");
1389
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001390 if (D->isFieldDesignator()) {
1391 // C99 6.7.8p7:
1392 //
1393 // If a designator has the form
1394 //
1395 // . identifier
1396 //
1397 // then the current object (defined below) shall have
1398 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001399 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001400 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 if (!RT) {
1402 SourceLocation Loc = D->getDotLoc();
1403 if (Loc.isInvalid())
1404 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001405 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1406 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001407 ++Index;
1408 return true;
1409 }
1410
Douglas Gregor4c678342009-01-28 21:54:33 +00001411 // Note: we perform a linear search of the fields here, despite
1412 // the fact that we have a faster lookup method, because we always
1413 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001414 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001415 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001416 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001417 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001418 Field = RT->getDecl()->field_begin(),
1419 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001420 for (; Field != FieldEnd; ++Field) {
1421 if (Field->isUnnamedBitfield())
1422 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001423
Francois Picheta0e27f02010-12-22 03:46:10 +00001424 // If we find a field representing an anonymous field, look in the
1425 // IndirectFieldDecl that follow for the designated initializer.
1426 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1427 if (IndirectFieldDecl *IF =
1428 FindIndirectFieldDesignator(*Field, FieldName)) {
1429 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1430 D = DIE->getDesignator(DesigIdx);
1431 break;
1432 }
1433 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001434 if (KnownField && KnownField == *Field)
1435 break;
1436 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001437 break;
1438
1439 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001440 }
1441
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001443 // There was no normal field in the struct with the designated
1444 // name. Perform another lookup for this name, which may find
1445 // something that we can't designate (e.g., a member function),
1446 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001448 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001449 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001450 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001451 // Name lookup didn't find anything. Determine whether this
1452 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001454 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001455 TypoCorrection Corrected = SemaRef.CorrectTypo(
1456 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1457 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1458 RT->getDecl(), false, Sema::CTC_NoKeywords);
1459 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001460 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001461 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001462 std::string CorrectedStr(
1463 Corrected.getAsString(SemaRef.getLangOptions()));
1464 std::string CorrectedQuotedStr(
1465 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001467 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001468 << FieldName << CurrentObjectType << CorrectedQuotedStr
1469 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001471 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001472 } else {
1473 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1474 << FieldName << CurrentObjectType;
1475 ++Index;
1476 return true;
1477 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001478 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001479
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001480 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001481 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001482 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001483 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001484 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001485 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001486 ++Index;
1487 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001488 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001489
Francois Picheta0e27f02010-12-22 03:46:10 +00001490 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001491 // The replacement field comes from typo correction; find it
1492 // in the list of fields.
1493 FieldIndex = 0;
1494 Field = RT->getDecl()->field_begin();
1495 for (; Field != FieldEnd; ++Field) {
1496 if (Field->isUnnamedBitfield())
1497 continue;
1498
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001500 Field->getIdentifier() == ReplacementField->getIdentifier())
1501 break;
1502
1503 ++FieldIndex;
1504 }
1505 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001506 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001507
1508 // All of the fields of a union are located at the same place in
1509 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001510 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001511 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001512 StructuredList->setInitializedFieldInUnion(*Field);
1513 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001514
Douglas Gregor54001c12011-06-29 21:51:31 +00001515 // Make sure we can use this declaration.
1516 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1517 ++Index;
1518 return true;
1519 }
1520
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001521 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001522 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Douglas Gregor4c678342009-01-28 21:54:33 +00001524 // Make sure that our non-designated initializer list has space
1525 // for a subobject corresponding to this field.
1526 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001527 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001528
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001529 // This designator names a flexible array member.
1530 if (Field->getType()->isIncompleteArrayType()) {
1531 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001532 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001533 // We can't designate an object within the flexible array
1534 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001535 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001536 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001537 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001538 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001539 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001540 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001541 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001542 << *Field;
1543 Invalid = true;
1544 }
1545
Chris Lattner9046c222010-10-10 17:49:49 +00001546 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1547 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001548 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001549 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001550 diag::err_flexible_array_init_needs_braces)
1551 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001552 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001553 << *Field;
1554 Invalid = true;
1555 }
1556
1557 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001559 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001560 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001561 diag::err_flexible_array_init_nonempty)
1562 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001563 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001564 << *Field;
1565 Invalid = true;
1566 }
1567
1568 if (Invalid) {
1569 ++Index;
1570 return true;
1571 }
1572
1573 // Initialize the array.
1574 bool prevHadError = hadError;
1575 unsigned newStructuredIndex = FieldIndex;
1576 unsigned OldIndex = Index;
1577 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001578
1579 InitializedEntity MemberEntity =
1580 InitializedEntity::InitializeMember(*Field, &Entity);
1581 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001582 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001583
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001584 IList->setInit(OldIndex, DIE);
1585 if (hadError && !prevHadError) {
1586 ++Field;
1587 ++FieldIndex;
1588 if (NextField)
1589 *NextField = Field;
1590 StructuredIndex = FieldIndex;
1591 return true;
1592 }
1593 } else {
1594 // Recurse to check later designated subobjects.
1595 QualType FieldType = (*Field)->getType();
1596 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001598 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001599 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1601 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001602 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001603 true, false))
1604 return true;
1605 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606
1607 // Find the position of the next field to be initialized in this
1608 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001609 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001610 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611
1612 // If this the first designator, our caller will continue checking
1613 // the rest of this struct/class/union subobject.
1614 if (IsFirstDesignator) {
1615 if (NextField)
1616 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001617 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 return false;
1619 }
1620
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 if (!FinishSubobjectInit)
1622 return false;
1623
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001624 // We've already initialized something in the union; we're done.
1625 if (RT->getDecl()->isUnion())
1626 return hadError;
1627
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001628 // Check the remaining fields within this class/struct/union subobject.
1629 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001631 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001632 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001633 return hadError && !prevHadError;
1634 }
1635
1636 // C99 6.7.8p6:
1637 //
1638 // If a designator has the form
1639 //
1640 // [ constant-expression ]
1641 //
1642 // then the current object (defined below) shall have array
1643 // type and the expression shall be an integer constant
1644 // expression. If the array is of unknown size, any
1645 // nonnegative value is valid.
1646 //
1647 // Additionally, cope with the GNU extension that permits
1648 // designators of the form
1649 //
1650 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001651 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001653 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 << CurrentObjectType;
1655 ++Index;
1656 return true;
1657 }
1658
1659 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001660 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1661 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001662 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001663 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001664 DesignatedEndIndex = DesignatedStartIndex;
1665 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001666 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001667
Mike Stump1eb44332009-09-09 15:08:12 +00001668 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001669 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001670 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001671 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001672 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001673
Chris Lattnere0fd8322011-02-19 22:28:58 +00001674 // Codegen can't handle evaluating array range designators that have side
1675 // effects, because we replicate the AST value for each initialized element.
1676 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1677 // elements with something that has a side effect, so codegen can emit an
1678 // "error unsupported" error instead of miscompiling the app.
1679 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1680 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001681 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001682 }
1683
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001684 if (isa<ConstantArrayType>(AT)) {
1685 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001686 DesignatedStartIndex
1687 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001688 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001689 DesignatedEndIndex
1690 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001691 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1692 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001693 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001694 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001695 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001696 << IndexExpr->getSourceRange();
1697 ++Index;
1698 return true;
1699 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001700 } else {
1701 // Make sure the bit-widths and signedness match.
1702 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001703 DesignatedEndIndex
1704 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001705 else if (DesignatedStartIndex.getBitWidth() <
1706 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001707 DesignatedStartIndex
1708 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001709 DesignatedStartIndex.setIsUnsigned(true);
1710 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor4c678342009-01-28 21:54:33 +00001713 // Make sure that our non-designated initializer list has space
1714 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001715 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001716 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001717 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001718
Douglas Gregor34e79462009-01-28 23:36:17 +00001719 // Repeatedly perform subobject initializations in the range
1720 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001721
Douglas Gregor34e79462009-01-28 23:36:17 +00001722 // Move to the next designator
1723 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1724 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001725
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001726 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001727 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001728
Douglas Gregor34e79462009-01-28 23:36:17 +00001729 while (DesignatedStartIndex <= DesignatedEndIndex) {
1730 // Recurse to check later designated subobjects.
1731 QualType ElementType = AT->getElementType();
1732 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001734 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1736 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001737 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001738 (DesignatedStartIndex == DesignatedEndIndex),
1739 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001740 return true;
1741
1742 // Move to the next index in the array that we'll be initializing.
1743 ++DesignatedStartIndex;
1744 ElementIndex = DesignatedStartIndex.getZExtValue();
1745 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001746
1747 // If this the first designator, our caller will continue checking
1748 // the rest of this array subobject.
1749 if (IsFirstDesignator) {
1750 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001751 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001752 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001753 return false;
1754 }
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Douglas Gregor34e79462009-01-28 23:36:17 +00001756 if (!FinishSubobjectInit)
1757 return false;
1758
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001759 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001760 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001761 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001762 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001763 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001764 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001765}
1766
Douglas Gregor4c678342009-01-28 21:54:33 +00001767// Get the structured initializer list for a subobject of type
1768// @p CurrentObjectType.
1769InitListExpr *
1770InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1771 QualType CurrentObjectType,
1772 InitListExpr *StructuredList,
1773 unsigned StructuredIndex,
1774 SourceRange InitRange) {
1775 Expr *ExistingInit = 0;
1776 if (!StructuredList)
1777 ExistingInit = SyntacticToSemantic[IList];
1778 else if (StructuredIndex < StructuredList->getNumInits())
1779 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1782 return Result;
1783
1784 if (ExistingInit) {
1785 // We are creating an initializer list that initializes the
1786 // subobjects of the current object, but there was already an
1787 // initialization that completely initialized the current
1788 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001789 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001790 // struct X { int a, b; };
1791 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001792 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001793 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1794 // designated initializer re-initializes the whole
1795 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001796 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001797 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001798 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001799 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001800 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001801 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001802 << ExistingInit->getSourceRange();
1803 }
1804
Mike Stump1eb44332009-09-09 15:08:12 +00001805 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001806 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1807 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001808 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001809
Douglas Gregor63982352010-07-13 18:40:04 +00001810 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001811
Douglas Gregorfa219202009-03-20 23:58:33 +00001812 // Pre-allocate storage for the structured initializer list.
1813 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001814 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001815 bool GotNumInits = false;
1816 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001817 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001818 GotNumInits = true;
1819 } else if (Index < IList->getNumInits()) {
1820 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001821 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001822 GotNumInits = true;
1823 }
Douglas Gregor08457732009-03-21 18:13:52 +00001824 }
1825
Mike Stump1eb44332009-09-09 15:08:12 +00001826 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001827 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1828 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1829 NumElements = CAType->getSize().getZExtValue();
1830 // Simple heuristic so that we don't allocate a very large
1831 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001832 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001833 NumElements = 0;
1834 }
John McCall183700f2009-09-21 23:43:11 +00001835 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001836 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001837 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001838 RecordDecl *RDecl = RType->getDecl();
1839 if (RDecl->isUnion())
1840 NumElements = 1;
1841 else
Mike Stump1eb44332009-09-09 15:08:12 +00001842 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001843 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001844 }
1845
Douglas Gregor08457732009-03-21 18:13:52 +00001846 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001847 NumElements = IList->getNumInits();
1848
Ted Kremenek709210f2010-04-13 23:39:13 +00001849 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001850
Douglas Gregor4c678342009-01-28 21:54:33 +00001851 // Link this new initializer list into the structured initializer
1852 // lists.
1853 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001854 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001855 else {
1856 Result->setSyntacticForm(IList);
1857 SyntacticToSemantic[IList] = Result;
1858 }
1859
1860 return Result;
1861}
1862
1863/// Update the initializer at index @p StructuredIndex within the
1864/// structured initializer list to the value @p expr.
1865void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1866 unsigned &StructuredIndex,
1867 Expr *expr) {
1868 // No structured initializer list to update
1869 if (!StructuredList)
1870 return;
1871
Ted Kremenek709210f2010-04-13 23:39:13 +00001872 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1873 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001874 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001876 diag::warn_initializer_overrides)
1877 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001878 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001879 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001880 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001881 << PrevInit->getSourceRange();
1882 }
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Douglas Gregor4c678342009-01-28 21:54:33 +00001884 ++StructuredIndex;
1885}
1886
Douglas Gregor05c13a32009-01-22 00:58:24 +00001887/// Check that the given Index expression is a valid array designator
1888/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001889/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001890/// and produces a reasonable diagnostic if there is a
1891/// failure. Returns true if there was an error, false otherwise. If
1892/// everything went okay, Value will receive the value of the constant
1893/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001894static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001895CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001896 SourceLocation Loc = Index->getSourceRange().getBegin();
1897
1898 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001899 if (S.VerifyIntegerConstantExpression(Index, &Value))
1900 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001901
Chris Lattner3bf68932009-04-25 21:59:05 +00001902 if (Value.isSigned() && Value.isNegative())
1903 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001904 << Value.toString(10) << Index->getSourceRange();
1905
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001906 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001907 return false;
1908}
1909
John McCall60d7b3a2010-08-24 06:29:42 +00001910ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001911 SourceLocation Loc,
1912 bool GNUSyntax,
1913 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001914 typedef DesignatedInitExpr::Designator ASTDesignator;
1915
1916 bool Invalid = false;
1917 llvm::SmallVector<ASTDesignator, 32> Designators;
1918 llvm::SmallVector<Expr *, 32> InitExpressions;
1919
1920 // Build designators and check array designator expressions.
1921 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1922 const Designator &D = Desig.getDesignator(Idx);
1923 switch (D.getKind()) {
1924 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001925 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001926 D.getFieldLoc()));
1927 break;
1928
1929 case Designator::ArrayDesignator: {
1930 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1931 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001932 if (!Index->isTypeDependent() &&
1933 !Index->isValueDependent() &&
1934 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935 Invalid = true;
1936 else {
1937 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001938 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001939 D.getRBracketLoc()));
1940 InitExpressions.push_back(Index);
1941 }
1942 break;
1943 }
1944
1945 case Designator::ArrayRangeDesignator: {
1946 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1947 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1948 llvm::APSInt StartValue;
1949 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001950 bool StartDependent = StartIndex->isTypeDependent() ||
1951 StartIndex->isValueDependent();
1952 bool EndDependent = EndIndex->isTypeDependent() ||
1953 EndIndex->isValueDependent();
1954 if ((!StartDependent &&
1955 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1956 (!EndDependent &&
1957 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001958 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001959 else {
1960 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001961 if (StartDependent || EndDependent) {
1962 // Nothing to compute.
1963 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001964 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001965 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001966 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001967
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001968 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001969 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001970 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001971 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1972 Invalid = true;
1973 } else {
1974 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001975 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001976 D.getEllipsisLoc(),
1977 D.getRBracketLoc()));
1978 InitExpressions.push_back(StartIndex);
1979 InitExpressions.push_back(EndIndex);
1980 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001981 }
1982 break;
1983 }
1984 }
1985 }
1986
1987 if (Invalid || Init.isInvalid())
1988 return ExprError();
1989
1990 // Clear out the expressions within the designation.
1991 Desig.ClearExprs(*this);
1992
1993 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001994 = DesignatedInitExpr::Create(Context,
1995 Designators.data(), Designators.size(),
1996 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001997 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001998
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001999 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002000 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2001 << DIE->getSourceRange();
2002 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002003 Diag(DIE->getLocStart(), diag::ext_designated_init)
2004 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002005
Douglas Gregor05c13a32009-01-22 00:58:24 +00002006 return Owned(DIE);
2007}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002008
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002009bool Sema::CheckInitList(const InitializedEntity &Entity,
2010 InitListExpr *&InitList, QualType &DeclType) {
2011 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002012 if (!CheckInitList.HadError())
2013 InitList = CheckInitList.getFullyStructuredList();
2014
2015 return CheckInitList.HadError();
2016}
Douglas Gregor87fd7032009-02-02 17:43:21 +00002017
Douglas Gregor20093b42009-12-09 23:02:17 +00002018//===----------------------------------------------------------------------===//
2019// Initialization entity
2020//===----------------------------------------------------------------------===//
2021
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002022InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002023 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002024 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002025{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002026 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2027 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002028 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002029 } else {
2030 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002031 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002032 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002033}
2034
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002035InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002036 CXXBaseSpecifier *Base,
2037 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002038{
2039 InitializedEntity Result;
2040 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002041 Result.Base = reinterpret_cast<uintptr_t>(Base);
2042 if (IsInheritedVirtualBase)
2043 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002044
Douglas Gregord6542d82009-12-22 15:35:07 +00002045 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002046 return Result;
2047}
2048
Douglas Gregor99a2e602009-12-16 01:38:02 +00002049DeclarationName InitializedEntity::getName() const {
2050 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002051 case EK_Parameter: {
2052 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2053 return (D ? D->getDeclName() : DeclarationName());
2054 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002055
2056 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002057 case EK_Member:
2058 return VariableOrMember->getDeclName();
2059
2060 case EK_Result:
2061 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002062 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002063 case EK_Temporary:
2064 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002065 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002066 case EK_ArrayElement:
2067 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002068 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002069 return DeclarationName();
2070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002071
Douglas Gregor99a2e602009-12-16 01:38:02 +00002072 // Silence GCC warning
2073 return DeclarationName();
2074}
2075
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002076DeclaratorDecl *InitializedEntity::getDecl() const {
2077 switch (getKind()) {
2078 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002079 case EK_Member:
2080 return VariableOrMember;
2081
John McCallf85e1932011-06-15 23:02:42 +00002082 case EK_Parameter:
2083 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2084
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002085 case EK_Result:
2086 case EK_Exception:
2087 case EK_New:
2088 case EK_Temporary:
2089 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002090 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002091 case EK_ArrayElement:
2092 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002093 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002094 return 0;
2095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002096
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002097 // Silence GCC warning
2098 return 0;
2099}
2100
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002101bool InitializedEntity::allowsNRVO() const {
2102 switch (getKind()) {
2103 case EK_Result:
2104 case EK_Exception:
2105 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002106
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002107 case EK_Variable:
2108 case EK_Parameter:
2109 case EK_Member:
2110 case EK_New:
2111 case EK_Temporary:
2112 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002113 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002114 case EK_ArrayElement:
2115 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002116 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002117 break;
2118 }
2119
2120 return false;
2121}
2122
Douglas Gregor20093b42009-12-09 23:02:17 +00002123//===----------------------------------------------------------------------===//
2124// Initialization sequence
2125//===----------------------------------------------------------------------===//
2126
2127void InitializationSequence::Step::Destroy() {
2128 switch (Kind) {
2129 case SK_ResolveAddressOfOverloadedFunction:
2130 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002131 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002132 case SK_CastDerivedToBaseLValue:
2133 case SK_BindReference:
2134 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002135 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002136 case SK_UserConversion:
2137 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002138 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002139 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002140 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002141 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002142 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002143 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002144 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002145 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002146 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002147 case SK_PassByIndirectCopyRestore:
2148 case SK_PassByIndirectRestore:
2149 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002150 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151
Douglas Gregor20093b42009-12-09 23:02:17 +00002152 case SK_ConversionSequence:
2153 delete ICS;
2154 }
2155}
2156
Douglas Gregorb70cf442010-03-26 20:14:36 +00002157bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002158 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002159}
2160
2161bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002162 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002163 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002164
Douglas Gregorb70cf442010-03-26 20:14:36 +00002165 switch (getFailureKind()) {
2166 case FK_TooManyInitsForReference:
2167 case FK_ArrayNeedsInitList:
2168 case FK_ArrayNeedsInitListOrStringLiteral:
2169 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2170 case FK_NonConstLValueReferenceBindingToTemporary:
2171 case FK_NonConstLValueReferenceBindingToUnrelated:
2172 case FK_RValueReferenceBindingToLValue:
2173 case FK_ReferenceInitDropsQualifiers:
2174 case FK_ReferenceInitFailed:
2175 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002176 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002177 case FK_TooManyInitsForScalar:
2178 case FK_ReferenceBindingToInitList:
2179 case FK_InitListBadDestinationType:
2180 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002181 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002182 case FK_ArrayTypeMismatch:
2183 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002184 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185
Douglas Gregorb70cf442010-03-26 20:14:36 +00002186 case FK_ReferenceInitOverloadFailed:
2187 case FK_UserConversionOverloadFailed:
2188 case FK_ConstructorOverloadFailed:
2189 return FailedOverloadResult == OR_Ambiguous;
2190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002191
Douglas Gregorb70cf442010-03-26 20:14:36 +00002192 return false;
2193}
2194
Douglas Gregord6e44a32010-04-16 22:09:46 +00002195bool InitializationSequence::isConstructorInitialization() const {
2196 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2197}
2198
Douglas Gregor20093b42009-12-09 23:02:17 +00002199void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002200 FunctionDecl *Function,
2201 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002202 Step S;
2203 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2204 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002205 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002206 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002207 Steps.push_back(S);
2208}
2209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002211 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002212 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002213 switch (VK) {
2214 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2215 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2216 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002217 default: llvm_unreachable("No such category");
2218 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002219 S.Type = BaseType;
2220 Steps.push_back(S);
2221}
2222
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002223void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002224 bool BindingTemporary) {
2225 Step S;
2226 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2227 S.Type = T;
2228 Steps.push_back(S);
2229}
2230
Douglas Gregor523d46a2010-04-18 07:40:54 +00002231void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2232 Step S;
2233 S.Kind = SK_ExtraneousCopyToTemporary;
2234 S.Type = T;
2235 Steps.push_back(S);
2236}
2237
Eli Friedman03981012009-12-11 02:42:07 +00002238void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002239 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002240 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002241 Step S;
2242 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002243 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002244 S.Function.Function = Function;
2245 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002246 Steps.push_back(S);
2247}
2248
2249void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002250 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002251 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002252 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002253 switch (VK) {
2254 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002255 S.Kind = SK_QualificationConversionRValue;
2256 break;
John McCall5baba9d2010-08-25 10:28:54 +00002257 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002258 S.Kind = SK_QualificationConversionXValue;
2259 break;
John McCall5baba9d2010-08-25 10:28:54 +00002260 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002261 S.Kind = SK_QualificationConversionLValue;
2262 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002263 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002264 S.Type = Ty;
2265 Steps.push_back(S);
2266}
2267
2268void InitializationSequence::AddConversionSequenceStep(
2269 const ImplicitConversionSequence &ICS,
2270 QualType T) {
2271 Step S;
2272 S.Kind = SK_ConversionSequence;
2273 S.Type = T;
2274 S.ICS = new ImplicitConversionSequence(ICS);
2275 Steps.push_back(S);
2276}
2277
Douglas Gregord87b61f2009-12-10 17:56:55 +00002278void InitializationSequence::AddListInitializationStep(QualType T) {
2279 Step S;
2280 S.Kind = SK_ListInitialization;
2281 S.Type = T;
2282 Steps.push_back(S);
2283}
2284
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002285void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002286InitializationSequence::AddConstructorInitializationStep(
2287 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002288 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002289 QualType T) {
2290 Step S;
2291 S.Kind = SK_ConstructorInitialization;
2292 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002293 S.Function.Function = Constructor;
2294 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002295 Steps.push_back(S);
2296}
2297
Douglas Gregor71d17402009-12-15 00:01:57 +00002298void InitializationSequence::AddZeroInitializationStep(QualType T) {
2299 Step S;
2300 S.Kind = SK_ZeroInitialization;
2301 S.Type = T;
2302 Steps.push_back(S);
2303}
2304
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002305void InitializationSequence::AddCAssignmentStep(QualType T) {
2306 Step S;
2307 S.Kind = SK_CAssignment;
2308 S.Type = T;
2309 Steps.push_back(S);
2310}
2311
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002312void InitializationSequence::AddStringInitStep(QualType T) {
2313 Step S;
2314 S.Kind = SK_StringInit;
2315 S.Type = T;
2316 Steps.push_back(S);
2317}
2318
Douglas Gregor569c3162010-08-07 11:51:51 +00002319void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2320 Step S;
2321 S.Kind = SK_ObjCObjectConversion;
2322 S.Type = T;
2323 Steps.push_back(S);
2324}
2325
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002326void InitializationSequence::AddArrayInitStep(QualType T) {
2327 Step S;
2328 S.Kind = SK_ArrayInit;
2329 S.Type = T;
2330 Steps.push_back(S);
2331}
2332
John McCallf85e1932011-06-15 23:02:42 +00002333void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2334 bool shouldCopy) {
2335 Step s;
2336 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2337 : SK_PassByIndirectRestore);
2338 s.Type = type;
2339 Steps.push_back(s);
2340}
2341
2342void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2343 Step S;
2344 S.Kind = SK_ProduceObjCObject;
2345 S.Type = T;
2346 Steps.push_back(S);
2347}
2348
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002350 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002351 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002352 this->Failure = Failure;
2353 this->FailedOverloadResult = Result;
2354}
2355
2356//===----------------------------------------------------------------------===//
2357// Attempt initialization
2358//===----------------------------------------------------------------------===//
2359
John McCallf85e1932011-06-15 23:02:42 +00002360static void MaybeProduceObjCObject(Sema &S,
2361 InitializationSequence &Sequence,
2362 const InitializedEntity &Entity) {
2363 if (!S.getLangOptions().ObjCAutoRefCount) return;
2364
2365 /// When initializing a parameter, produce the value if it's marked
2366 /// __attribute__((ns_consumed)).
2367 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2368 if (!Entity.isParameterConsumed())
2369 return;
2370
2371 assert(Entity.getType()->isObjCRetainableType() &&
2372 "consuming an object of unretainable type?");
2373 Sequence.AddProduceObjCObjectStep(Entity.getType());
2374
2375 /// When initializing a return value, if the return type is a
2376 /// retainable type, then returns need to immediately retain the
2377 /// object. If an autorelease is required, it will be done at the
2378 /// last instant.
2379 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2380 if (!Entity.getType()->isObjCRetainableType())
2381 return;
2382
2383 Sequence.AddProduceObjCObjectStep(Entity.getType());
2384 }
2385}
2386
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002387/// \brief Attempt list initialization (C++0x [dcl.init.list])
2388static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002389 const InitializedEntity &Entity,
2390 const InitializationKind &Kind,
2391 InitListExpr *InitList,
2392 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002393 // FIXME: We only perform rudimentary checking of list
2394 // initializations at this point, then assume that any list
2395 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002396 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002397 // do all of the necessary checking. C++0x initializer lists will
2398 // force us to perform more checking here.
Douglas Gregord87b61f2009-12-10 17:56:55 +00002399
Douglas Gregord6542d82009-12-22 15:35:07 +00002400 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002401
2402 // C++ [dcl.init]p13:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002403 // If T is a scalar type, then a declaration of the form
Douglas Gregord87b61f2009-12-10 17:56:55 +00002404 //
2405 // T x = { a };
2406 //
2407 // is equivalent to
2408 //
2409 // T x = a;
2410 if (DestType->isScalarType()) {
2411 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2412 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2413 return;
2414 }
2415
2416 // Assume scalar initialization from a single value works.
2417 } else if (DestType->isAggregateType()) {
2418 // Assume aggregate initialization works.
2419 } else if (DestType->isVectorType()) {
2420 // Assume vector initialization works.
2421 } else if (DestType->isReferenceType()) {
2422 // FIXME: C++0x defines behavior for this.
2423 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2424 return;
2425 } else if (DestType->isRecordType()) {
2426 // FIXME: C++0x defines behavior for this
2427 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2428 }
2429
2430 // Add a general "list initialization" step.
2431 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002432}
2433
2434/// \brief Try a reference initialization that involves calling a conversion
2435/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002436static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2437 const InitializedEntity &Entity,
2438 const InitializationKind &Kind,
2439 Expr *Initializer,
2440 bool AllowRValues,
2441 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002442 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2444 QualType T1 = cv1T1.getUnqualifiedType();
2445 QualType cv2T2 = Initializer->getType();
2446 QualType T2 = cv2T2.getUnqualifiedType();
2447
2448 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002449 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002450 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002451 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002452 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002453 ObjCConversion,
2454 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002455 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002456 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002457 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002458 (void)ObjCLifetimeConversion;
2459
Douglas Gregor20093b42009-12-09 23:02:17 +00002460 // Build the candidate set directly in the initialization sequence
2461 // structure, so that it will persist if we fail.
2462 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2463 CandidateSet.clear();
2464
2465 // Determine whether we are allowed to call explicit constructors or
2466 // explicit conversion operators.
2467 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002468
Douglas Gregor20093b42009-12-09 23:02:17 +00002469 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002470 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2471 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 // The type we're converting to is a class type. Enumerate its constructors
2473 // to see if there is a suitable conversion.
2474 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002475
Douglas Gregor20093b42009-12-09 23:02:17 +00002476 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002477 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002478 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002479 NamedDecl *D = *Con;
2480 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2481
Douglas Gregor20093b42009-12-09 23:02:17 +00002482 // Find the constructor (which may be a template).
2483 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002484 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002485 if (ConstructorTmpl)
2486 Constructor = cast<CXXConstructorDecl>(
2487 ConstructorTmpl->getTemplatedDecl());
2488 else
John McCall9aa472c2010-03-19 07:35:19 +00002489 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002490
Douglas Gregor20093b42009-12-09 23:02:17 +00002491 if (!Constructor->isInvalidDecl() &&
2492 Constructor->isConvertingConstructor(AllowExplicit)) {
2493 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002494 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002495 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002496 &Initializer, 1, CandidateSet,
2497 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002498 else
John McCall9aa472c2010-03-19 07:35:19 +00002499 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002500 &Initializer, 1, CandidateSet,
2501 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002503 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 }
John McCall572fc622010-08-17 07:23:57 +00002505 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2506 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002507
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002508 const RecordType *T2RecordType = 0;
2509 if ((T2RecordType = T2->getAs<RecordType>()) &&
2510 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 // The type we're converting from is a class type, enumerate its conversion
2512 // functions.
2513 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2514
John McCalleec51cf2010-01-20 00:46:10 +00002515 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002516 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002517 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2518 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 NamedDecl *D = *I;
2520 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2521 if (isa<UsingShadowDecl>(D))
2522 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002523
Douglas Gregor20093b42009-12-09 23:02:17 +00002524 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2525 CXXConversionDecl *Conv;
2526 if (ConvTemplate)
2527 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2528 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002529 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002530
Douglas Gregor20093b42009-12-09 23:02:17 +00002531 // If the conversion function doesn't return a reference type,
2532 // it can't be considered for this conversion unless we're allowed to
2533 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002534 // FIXME: Do we need to make sure that we only consider conversion
2535 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 // break recursion.
2537 if ((AllowExplicit || !Conv->isExplicit()) &&
2538 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2539 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002540 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002541 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002542 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002543 else
John McCall9aa472c2010-03-19 07:35:19 +00002544 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002545 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 }
2547 }
2548 }
John McCall572fc622010-08-17 07:23:57 +00002549 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2550 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 SourceLocation DeclLoc = Initializer->getLocStart();
2553
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002555 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002556 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002557 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002559
Douglas Gregor20093b42009-12-09 23:02:17 +00002560 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002561
Chandler Carruth25ca4212011-02-25 19:41:05 +00002562 // This is the overload that will actually be used for the initialization, so
2563 // mark it as used.
2564 S.MarkDeclarationReferenced(DeclLoc, Function);
2565
Eli Friedman03981012009-12-11 02:42:07 +00002566 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002567 if (isa<CXXConversionDecl>(Function))
2568 T2 = Function->getResultType();
2569 else
2570 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002571
2572 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002573 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002574 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002575
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002576 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002577 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002578 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002579 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002580 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002581 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002582 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002583
Douglas Gregor20093b42009-12-09 23:02:17 +00002584 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002585 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002586 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002587 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002588 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002589 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002590 NewDerivedToBase, NewObjCConversion,
2591 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002592 if (NewRefRelationship == Sema::Ref_Incompatible) {
2593 // If the type we've converted to is not reference-related to the
2594 // type we're looking for, then there is another conversion step
2595 // we need to perform to produce a temporary of the right type
2596 // that we'll be binding to.
2597 ImplicitConversionSequence ICS;
2598 ICS.setStandard();
2599 ICS.Standard = Best->FinalConversion;
2600 T2 = ICS.Standard.getToType(2);
2601 Sequence.AddConversionSequenceStep(ICS, T2);
2602 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002603 Sequence.AddDerivedToBaseCastStep(
2604 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002605 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002606 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002607 else if (NewObjCConversion)
2608 Sequence.AddObjCObjectConversionStep(
2609 S.Context.getQualifiedType(T1,
2610 T2.getNonReferenceType().getQualifiers()));
2611
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002613 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002614
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2616 return OR_Success;
2617}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002618
2619/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2620static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 const InitializedEntity &Entity,
2622 const InitializationKind &Kind,
2623 Expr *Initializer,
2624 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002625 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002626 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002627 Qualifiers T1Quals;
2628 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002629 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002630 Qualifiers T2Quals;
2631 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002632 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002633
Douglas Gregor20093b42009-12-09 23:02:17 +00002634 // If the initializer is the address of an overloaded function, try
2635 // to resolve the overloaded function. If all goes well, T2 is the
2636 // type of the resulting function.
2637 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002638 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002639 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002640 T1,
2641 false,
2642 Found)) {
2643 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2644 cv2T2 = Fn->getType();
2645 T2 = cv2T2.getUnqualifiedType();
2646 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2648 return;
2649 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002650 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002651
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 // Compute some basic properties of the types and the initializer.
2653 bool isLValueRef = DestType->isLValueReferenceType();
2654 bool isRValueRef = !isLValueRef;
2655 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002656 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002657 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002658 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002659 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002660 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002661 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002662
Douglas Gregor20093b42009-12-09 23:02:17 +00002663 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002664 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002665 // "cv2 T2" as follows:
2666 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002669 // Note the analogous bullet points for rvlaue refs to functions. Because
2670 // there are no function rvalues in C++, rvalue refs to functions are treated
2671 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002672 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002673 bool T1Function = T1->isFunctionType();
2674 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002675 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002676 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002677 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002678 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002680 // reference-compatible with "cv2 T2," or
2681 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002684 // can occur. However, we do pay attention to whether it is a bit-field
2685 // to decide whether we're actually binding to a temporary created from
2686 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002687 if (DerivedToBase)
2688 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002689 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002690 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002691 else if (ObjCConversion)
2692 Sequence.AddObjCObjectConversionStep(
2693 S.Context.getQualifiedType(T1, T2Quals));
2694
Chandler Carruth5535c382010-01-12 20:32:25 +00002695 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002696 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002697 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002698 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002699 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002700 return;
2701 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702
2703 // - has a class type (i.e., T2 is a class type), where T1 is not
2704 // reference-related to T2, and can be implicitly converted to an
2705 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2706 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002707 // applicable conversion functions (13.3.1.6) and choosing the best
2708 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002709 // If we have an rvalue ref to function type here, the rhs must be
2710 // an rvalue.
2711 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2712 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002714 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002715 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002716 Sequence);
2717 if (ConvOvlResult == OR_Success)
2718 return;
John McCall1d318332010-01-12 00:44:57 +00002719 if (ConvOvlResult != OR_No_Viable_Function) {
2720 Sequence.SetOverloadFailure(
2721 InitializationSequence::FK_ReferenceInitOverloadFailed,
2722 ConvOvlResult);
2723 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002724 }
2725 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002726
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002727 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002729 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002730 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002731 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2732 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2733 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002734 Sequence.SetOverloadFailure(
2735 InitializationSequence::FK_ReferenceInitOverloadFailed,
2736 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002737 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002738 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002739 ? (RefRelationship == Sema::Ref_Related
2740 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2741 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2742 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002743
Douglas Gregor20093b42009-12-09 23:02:17 +00002744 return;
2745 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002746
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002747 // - If the initializer expression
2748 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2749 // "cv1 T1" is reference-compatible with "cv2 T2"
2750 // Note: functions are handled below.
2751 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002752 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002754 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002755 (InitCategory.isXValue() ||
2756 (InitCategory.isPRValue() && T2->isRecordType()) ||
2757 (InitCategory.isPRValue() && T2->isArrayType()))) {
2758 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2759 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002760 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2761 // compiler the freedom to perform a copy here or bind to the
2762 // object, while C++0x requires that we bind directly to the
2763 // object. Hence, we always bind to the object without making an
2764 // extra copy. However, in C++03 requires that we check for the
2765 // presence of a suitable copy constructor:
2766 //
2767 // The constructor that would be used to make the copy shall
2768 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002769 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002770 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002772
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002773 if (DerivedToBase)
2774 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2775 ValueKind);
2776 else if (ObjCConversion)
2777 Sequence.AddObjCObjectConversionStep(
2778 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002779
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002780 if (T1Quals != T2Quals)
2781 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002782 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002783 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002786
2787 // - has a class type (i.e., T2 is a class type), where T1 is not
2788 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002789 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2790 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002791 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002792 if (RefRelationship == Sema::Ref_Incompatible) {
2793 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2794 Kind, Initializer,
2795 /*AllowRValues=*/true,
2796 Sequence);
2797 if (ConvOvlResult)
2798 Sequence.SetOverloadFailure(
2799 InitializationSequence::FK_ReferenceInitOverloadFailed,
2800 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002801
Douglas Gregor20093b42009-12-09 23:02:17 +00002802 return;
2803 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002804
Douglas Gregor20093b42009-12-09 23:02:17 +00002805 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2806 return;
2807 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002808
2809 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002810 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002813
Douglas Gregor20093b42009-12-09 23:02:17 +00002814 // Determine whether we are allowed to call explicit constructors or
2815 // explicit conversion operators.
2816 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002817
2818 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2819
John McCallf85e1932011-06-15 23:02:42 +00002820 ImplicitConversionSequence ICS
2821 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00002822 /*SuppressUserConversions*/ false,
2823 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002824 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00002825 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2826 /*AllowObjCWritebackConversion=*/false);
2827
2828 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002829 // FIXME: Use the conversion function set stored in ICS to turn
2830 // this into an overloading ambiguity diagnostic. However, we need
2831 // to keep that set as an OverloadCandidateSet rather than as some
2832 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002833 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2834 Sequence.SetOverloadFailure(
2835 InitializationSequence::FK_ReferenceInitOverloadFailed,
2836 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002837 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2838 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002839 else
2840 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002841 return;
John McCallf85e1932011-06-15 23:02:42 +00002842 } else {
2843 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 }
2845
2846 // [...] If T1 is reference-related to T2, cv1 must be the
2847 // same cv-qualification as, or greater cv-qualification
2848 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002849 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2850 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002852 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002853 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2854 return;
2855 }
2856
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002858 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002860 InitCategory.isLValue()) {
2861 Sequence.SetFailed(
2862 InitializationSequence::FK_RValueReferenceBindingToLValue);
2863 return;
2864 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002865
Douglas Gregor20093b42009-12-09 23:02:17 +00002866 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2867 return;
2868}
2869
2870/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871/// (C++ [dcl.init.string], C99 6.7.8).
2872static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002873 const InitializedEntity &Entity,
2874 const InitializationKind &Kind,
2875 Expr *Initializer,
2876 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002877 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002878}
2879
Douglas Gregor20093b42009-12-09 23:02:17 +00002880/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2881/// enumerates the constructors of the initialized entity and performs overload
2882/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002884 const InitializedEntity &Entity,
2885 const InitializationKind &Kind,
2886 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002887 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002888 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002889 // Build the candidate set directly in the initialization sequence
2890 // structure, so that it will persist if we fail.
2891 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2892 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893
Douglas Gregor51c56d62009-12-14 20:49:26 +00002894 // Determine whether we are allowed to call explicit constructors or
2895 // explicit conversion operators.
2896 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2897 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002898 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002899
2900 // The type we're constructing needs to be complete.
2901 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002902 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002903 return;
2904 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002905
Douglas Gregor51c56d62009-12-14 20:49:26 +00002906 // The type we're converting to is a class type. Enumerate its constructors
2907 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002908 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00002910 CXXRecordDecl *DestRecordDecl
2911 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002912
Douglas Gregor51c56d62009-12-14 20:49:26 +00002913 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002914 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002915 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002916 NamedDecl *D = *Con;
2917 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002918 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919
Douglas Gregor51c56d62009-12-14 20:49:26 +00002920 // Find the constructor (which may be a template).
2921 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002922 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002923 if (ConstructorTmpl)
2924 Constructor = cast<CXXConstructorDecl>(
2925 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002926 else {
John McCall9aa472c2010-03-19 07:35:19 +00002927 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002928
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00002930 // suppress user-defined conversions on the arguments.
2931 // FIXME: Move constructors?
2932 if (Kind.getKind() == InitializationKind::IK_Copy &&
2933 Constructor->isCopyConstructor())
2934 SuppressUserConversions = true;
2935 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002936
Douglas Gregor51c56d62009-12-14 20:49:26 +00002937 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002938 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002939 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002940 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002941 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002942 Args, NumArgs, CandidateSet,
2943 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002944 else
John McCall9aa472c2010-03-19 07:35:19 +00002945 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002946 Args, NumArgs, CandidateSet,
2947 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002948 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949 }
2950
Douglas Gregor51c56d62009-12-14 20:49:26 +00002951 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002952
2953 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002954 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002956 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002957 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002959 Result);
2960 return;
2961 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002962
2963 // C++0x [dcl.init]p6:
2964 // If a program calls for the default initialization of an object
2965 // of a const-qualified type T, T shall be a class type with a
2966 // user-provided default constructor.
2967 if (Kind.getKind() == InitializationKind::IK_Default &&
2968 Entity.getType().isConstQualified() &&
2969 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2970 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2971 return;
2972 }
2973
Douglas Gregor51c56d62009-12-14 20:49:26 +00002974 // Add the constructor initialization step. Any cv-qualification conversion is
2975 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002976 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002978 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002979 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002980}
2981
Douglas Gregor71d17402009-12-15 00:01:57 +00002982/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002983static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00002984 const InitializedEntity &Entity,
2985 const InitializationKind &Kind,
2986 InitializationSequence &Sequence) {
2987 // C++ [dcl.init]p5:
2988 //
2989 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002990 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002991
Douglas Gregor71d17402009-12-15 00:01:57 +00002992 // -- if T is an array type, then each element is value-initialized;
2993 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2994 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002995
Douglas Gregor71d17402009-12-15 00:01:57 +00002996 if (const RecordType *RT = T->getAs<RecordType>()) {
2997 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2998 // -- if T is a class type (clause 9) with a user-declared
2999 // constructor (12.1), then the default constructor for T is
3000 // called (and the initialization is ill-formed if T has no
3001 // accessible default constructor);
3002 //
3003 // FIXME: we really want to refer to a single subobject of the array,
3004 // but Entity doesn't have a way to capture that (yet).
3005 if (ClassDecl->hasUserDeclaredConstructor())
3006 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003007
Douglas Gregor16006c92009-12-16 18:50:27 +00003008 // -- if T is a (possibly cv-qualified) non-union class type
3009 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003010 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003011 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003012 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003013 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003014 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003015 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003016 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003017 }
3018 }
3019
Douglas Gregord6542d82009-12-22 15:35:07 +00003020 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003021}
3022
Douglas Gregor99a2e602009-12-16 01:38:02 +00003023/// \brief Attempt default initialization (C++ [dcl.init]p6).
3024static void TryDefaultInitialization(Sema &S,
3025 const InitializedEntity &Entity,
3026 const InitializationKind &Kind,
3027 InitializationSequence &Sequence) {
3028 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029
Douglas Gregor99a2e602009-12-16 01:38:02 +00003030 // C++ [dcl.init]p6:
3031 // To default-initialize an object of type T means:
3032 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003033 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3034
Douglas Gregor99a2e602009-12-16 01:38:02 +00003035 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3036 // constructor for T is called (and the initialization is ill-formed if
3037 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003038 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003039 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3040 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042
Douglas Gregor99a2e602009-12-16 01:38:02 +00003043 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003044
Douglas Gregor99a2e602009-12-16 01:38:02 +00003045 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003047 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003048 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003049 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003050 return;
3051 }
3052
3053 // If the destination type has a lifetime property, zero-initialize it.
3054 if (DestType.getQualifiers().hasObjCLifetime()) {
3055 Sequence.AddZeroInitializationStep(Entity.getType());
3056 return;
3057 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003058}
3059
Douglas Gregor20093b42009-12-09 23:02:17 +00003060/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3061/// which enumerates all conversion functions and performs overload resolution
3062/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003064 const InitializedEntity &Entity,
3065 const InitializationKind &Kind,
3066 Expr *Initializer,
3067 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003068 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003069 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3070 QualType SourceType = Initializer->getType();
3071 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3072 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor4a520a22009-12-14 17:27:33 +00003074 // Build the candidate set directly in the initialization sequence
3075 // structure, so that it will persist if we fail.
3076 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3077 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078
Douglas Gregor4a520a22009-12-14 17:27:33 +00003079 // Determine whether we are allowed to call explicit constructors or
3080 // explicit conversion operators.
3081 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082
Douglas Gregor4a520a22009-12-14 17:27:33 +00003083 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3084 // The type we're converting to is a class type. Enumerate its constructors
3085 // to see if there is a suitable conversion.
3086 CXXRecordDecl *DestRecordDecl
3087 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003089 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003090 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003091 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003092 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003093 Con != ConEnd; ++Con) {
3094 NamedDecl *D = *Con;
3095 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003096
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003097 // Find the constructor (which may be a template).
3098 CXXConstructorDecl *Constructor = 0;
3099 FunctionTemplateDecl *ConstructorTmpl
3100 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003101 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003102 Constructor = cast<CXXConstructorDecl>(
3103 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003104 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003105 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003106
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003107 if (!Constructor->isInvalidDecl() &&
3108 Constructor->isConvertingConstructor(AllowExplicit)) {
3109 if (ConstructorTmpl)
3110 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3111 /*ExplicitArgs*/ 0,
3112 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003113 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003114 else
3115 S.AddOverloadCandidate(Constructor, FoundDecl,
3116 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003117 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003120 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003121 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003122
3123 SourceLocation DeclLoc = Initializer->getLocStart();
3124
Douglas Gregor4a520a22009-12-14 17:27:33 +00003125 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3126 // The type we're converting from is a class type, enumerate its conversion
3127 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003128
Eli Friedman33c2da92009-12-20 22:12:03 +00003129 // We can only enumerate the conversion functions for a complete type; if
3130 // the type isn't complete, simply skip this step.
3131 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3132 CXXRecordDecl *SourceRecordDecl
3133 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134
John McCalleec51cf2010-01-20 00:46:10 +00003135 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003136 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003137 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003139 I != E; ++I) {
3140 NamedDecl *D = *I;
3141 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3142 if (isa<UsingShadowDecl>(D))
3143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144
Eli Friedman33c2da92009-12-20 22:12:03 +00003145 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3146 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003147 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003148 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003149 else
John McCall32daa422010-03-31 01:36:47 +00003150 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151
Eli Friedman33c2da92009-12-20 22:12:03 +00003152 if (AllowExplicit || !Conv->isExplicit()) {
3153 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003154 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003155 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003156 CandidateSet);
3157 else
John McCall9aa472c2010-03-19 07:35:19 +00003158 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003159 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003160 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003161 }
3162 }
3163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164
3165 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003166 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003167 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003168 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003169 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003171 Result);
3172 return;
3173 }
John McCall1d318332010-01-12 00:44:57 +00003174
Douglas Gregor4a520a22009-12-14 17:27:33 +00003175 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003176 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177
Douglas Gregor4a520a22009-12-14 17:27:33 +00003178 if (isa<CXXConstructorDecl>(Function)) {
3179 // Add the user-defined conversion step. Any cv-qualification conversion is
3180 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003181 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003182 return;
3183 }
3184
3185 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003186 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003187 if (ConvType->getAs<RecordType>()) {
3188 // If we're converting to a class type, there may be an copy if
3189 // the resulting temporary object (possible to create an object of
3190 // a base class type). That copy is not a separate conversion, so
3191 // we just make a note of the actual destination type (possibly a
3192 // base class of the type returned by the conversion function) and
3193 // let the user-defined conversion step handle the conversion.
3194 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3195 return;
3196 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003197
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003198 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003200 // If the conversion following the call to the conversion function
3201 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003202 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3203 Best->FinalConversion.Third) {
3204 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003205 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003206 ICS.Standard = Best->FinalConversion;
3207 Sequence.AddConversionSequenceStep(ICS, DestType);
3208 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003209}
3210
John McCallf85e1932011-06-15 23:02:42 +00003211/// The non-zero enum values here are indexes into diagnostic alternatives.
3212enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3213
3214/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003215static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3216 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003217 // Skip parens.
3218 e = e->IgnoreParens();
3219
3220 // Skip address-of nodes.
3221 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3222 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003223 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003224
3225 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003226 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3227 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003228 case CK_Dependent:
3229 case CK_BitCast:
3230 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003231 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003232 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003233
3234 case CK_ArrayToPointerDecay:
3235 return IIK_nonscalar;
3236
3237 case CK_NullToPointer:
3238 return IIK_okay;
3239
3240 default:
3241 break;
3242 }
3243
3244 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003245 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3246 if (!isAddressOf) return IIK_nonlocal;
3247
3248 VarDecl *var;
3249 if (isa<DeclRefExpr>(e)) {
3250 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3251 if (!var) return IIK_nonlocal;
3252 } else {
3253 var = cast<BlockDeclRefExpr>(e)->getDecl();
3254 }
3255
3256 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003257
3258 // If we have a conditional operator, check both sides.
3259 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003260 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003261 return iik;
3262
John McCallc03fa492011-06-27 23:59:58 +00003263 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003264
3265 // These are never scalar.
3266 } else if (isa<ArraySubscriptExpr>(e)) {
3267 return IIK_nonscalar;
3268
3269 // Otherwise, it needs to be a null pointer constant.
3270 } else {
3271 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3272 ? IIK_okay : IIK_nonlocal);
3273 }
3274
3275 return IIK_nonlocal;
3276}
3277
3278/// Check whether the given expression is a valid operand for an
3279/// indirect copy/restore.
3280static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3281 assert(src->isRValue());
3282
John McCallc03fa492011-06-27 23:59:58 +00003283 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003284 if (iik == IIK_okay) return;
3285
3286 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3287 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3288 << src->getSourceRange();
3289}
3290
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003291/// \brief Determine whether we have compatible array types for the
3292/// purposes of GNU by-copy array initialization.
3293static bool hasCompatibleArrayTypes(ASTContext &Context,
3294 const ArrayType *Dest,
3295 const ArrayType *Source) {
3296 // If the source and destination array types are equivalent, we're
3297 // done.
3298 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3299 return true;
3300
3301 // Make sure that the element types are the same.
3302 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3303 return false;
3304
3305 // The only mismatch we allow is when the destination is an
3306 // incomplete array type and the source is a constant array type.
3307 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3308}
3309
John McCallf85e1932011-06-15 23:02:42 +00003310static bool tryObjCWritebackConversion(Sema &S,
3311 InitializationSequence &Sequence,
3312 const InitializedEntity &Entity,
3313 Expr *Initializer) {
3314 bool ArrayDecay = false;
3315 QualType ArgType = Initializer->getType();
3316 QualType ArgPointee;
3317 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3318 ArrayDecay = true;
3319 ArgPointee = ArgArrayType->getElementType();
3320 ArgType = S.Context.getPointerType(ArgPointee);
3321 }
3322
3323 // Handle write-back conversion.
3324 QualType ConvertedArgType;
3325 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3326 ConvertedArgType))
3327 return false;
3328
3329 // We should copy unless we're passing to an argument explicitly
3330 // marked 'out'.
3331 bool ShouldCopy = true;
3332 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3333 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3334
3335 // Do we need an lvalue conversion?
3336 if (ArrayDecay || Initializer->isGLValue()) {
3337 ImplicitConversionSequence ICS;
3338 ICS.setStandard();
3339 ICS.Standard.setAsIdentityConversion();
3340
3341 QualType ResultType;
3342 if (ArrayDecay) {
3343 ICS.Standard.First = ICK_Array_To_Pointer;
3344 ResultType = S.Context.getPointerType(ArgPointee);
3345 } else {
3346 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3347 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3348 }
3349
3350 Sequence.AddConversionSequenceStep(ICS, ResultType);
3351 }
3352
3353 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3354 return true;
3355}
3356
Douglas Gregor20093b42009-12-09 23:02:17 +00003357InitializationSequence::InitializationSequence(Sema &S,
3358 const InitializedEntity &Entity,
3359 const InitializationKind &Kind,
3360 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003361 unsigned NumArgs)
3362 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003363 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregor20093b42009-12-09 23:02:17 +00003365 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366 // The semantics of initializers are as follows. The destination type is
3367 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003368 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003371 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003372
3373 if (DestType->isDependentType() ||
3374 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3375 SequenceKind = DependentSequence;
3376 return;
3377 }
3378
Sebastian Redl7491c492011-06-05 13:59:11 +00003379 // Almost everything is a normal sequence.
3380 setSequenceKind(NormalSequence);
3381
John McCall241d5582010-12-07 22:54:16 +00003382 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003383 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3384 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3385 if (Result.isInvalid()) {
3386 SetFailed(FK_ConversionFromPropertyFailed);
3387 return;
3388 }
3389 Args[I] = Result.take();
3390 }
John McCall241d5582010-12-07 22:54:16 +00003391
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 QualType SourceType;
3393 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003394 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003395 Initializer = Args[0];
3396 if (!isa<InitListExpr>(Initializer))
3397 SourceType = Initializer->getType();
3398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399
3400 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003401 // list-initialized (8.5.4).
3402 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3403 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003404 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Douglas Gregor20093b42009-12-09 23:02:17 +00003407 // - If the destination type is a reference type, see 8.5.3.
3408 if (DestType->isReferenceType()) {
3409 // C++0x [dcl.init.ref]p1:
3410 // A variable declared to be a T& or T&&, that is, "reference to type T"
3411 // (8.3.2), shall be initialized by an object, or function, of type T or
3412 // by an object that can be converted into a T.
3413 // (Therefore, multiple arguments are not permitted.)
3414 if (NumArgs != 1)
3415 SetFailed(FK_TooManyInitsForReference);
3416 else
3417 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3418 return;
3419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003420
Douglas Gregor20093b42009-12-09 23:02:17 +00003421 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003422 if (Kind.getKind() == InitializationKind::IK_Value ||
3423 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 TryValueInitialization(S, Entity, Kind, *this);
3425 return;
3426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427
Douglas Gregor99a2e602009-12-16 01:38:02 +00003428 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003429 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003430 TryDefaultInitialization(S, Entity, Kind, *this);
3431 return;
3432 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003433
John McCallce6c9b72011-02-21 07:22:22 +00003434 // - If the destination type is an array of characters, an array of
3435 // char16_t, an array of char32_t, or an array of wchar_t, and the
3436 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003437 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003438 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003439 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3440 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCallce6c9b72011-02-21 07:22:22 +00003441 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3442 return;
3443 }
3444
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003445 // Note: as an GNU C extension, we allow initialization of an
3446 // array from a compound literal that creates an array of the same
3447 // type, so long as the initializer has no side effects.
3448 if (!S.getLangOptions().CPlusPlus && Initializer &&
3449 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3450 Initializer->getType()->isArrayType()) {
3451 const ArrayType *SourceAT
3452 = Context.getAsArrayType(Initializer->getType());
3453 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3454 SetFailed(FK_ArrayTypeMismatch);
3455 else if (Initializer->HasSideEffects(S.Context))
3456 SetFailed(FK_NonConstantArrayInit);
3457 else {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003458 AddArrayInitStep(DestType);
3459 }
3460 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor20093b42009-12-09 23:02:17 +00003461 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3462 else
3463 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
Douglas Gregor20093b42009-12-09 23:02:17 +00003465 return;
3466 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003467
John McCallf85e1932011-06-15 23:02:42 +00003468 // Determine whether we should consider writeback conversions for
3469 // Objective-C ARC.
3470 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3471 Entity.getKind() == InitializedEntity::EK_Parameter;
3472
3473 // We're at the end of the line for C: it's either a write-back conversion
3474 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003475 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003476 // If allowed, check whether this is an Objective-C writeback conversion.
3477 if (allowObjCWritebackConversion &&
3478 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
3479 return;
3480 }
3481
3482 // Handle initialization in C
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003483 AddCAssignmentStep(DestType);
John McCallf85e1932011-06-15 23:02:42 +00003484 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003485 return;
3486 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003487
John McCallf85e1932011-06-15 23:02:42 +00003488 assert(S.getLangOptions().CPlusPlus);
3489
Douglas Gregor20093b42009-12-09 23:02:17 +00003490 // - If the destination type is a (possibly cv-qualified) class type:
3491 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492 // - If the initialization is direct-initialization, or if it is
3493 // copy-initialization where the cv-unqualified version of the
3494 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 // class of the destination, constructors are considered. [...]
3496 if (Kind.getKind() == InitializationKind::IK_Direct ||
3497 (Kind.getKind() == InitializationKind::IK_Copy &&
3498 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3499 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003501 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003503 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003505 // used) to a derived class thereof are enumerated as described in
3506 // 13.3.1.4, and the best one is chosen through overload resolution
3507 // (13.3).
3508 else
3509 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3510 return;
3511 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512
Douglas Gregor99a2e602009-12-16 01:38:02 +00003513 if (NumArgs > 1) {
3514 SetFailed(FK_TooManyInitsForScalar);
3515 return;
3516 }
3517 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518
3519 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003520 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003521 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003522 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
John McCallf85e1932011-06-15 23:02:42 +00003523 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003524 return;
3525 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003528 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003530 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003532
3533 ImplicitConversionSequence ICS
3534 = S.TryImplicitConversion(Initializer, Entity.getType(),
3535 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003536 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003537 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003538 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3539 allowObjCWritebackConversion);
3540
3541 if (ICS.isStandard() &&
3542 ICS.Standard.Second == ICK_Writeback_Conversion) {
3543 // Objective-C ARC writeback conversion.
3544
3545 // We should copy unless we're passing to an argument explicitly
3546 // marked 'out'.
3547 bool ShouldCopy = true;
3548 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3549 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3550
3551 // If there was an lvalue adjustment, add it as a separate conversion.
3552 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3553 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3554 ImplicitConversionSequence LvalueICS;
3555 LvalueICS.setStandard();
3556 LvalueICS.Standard.setAsIdentityConversion();
3557 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3558 LvalueICS.Standard.First = ICS.Standard.First;
3559 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
3560 }
3561
3562 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3563 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003564 DeclAccessPair dap;
3565 if (Initializer->getType() == Context.OverloadTy &&
3566 !S.ResolveAddressOfOverloadedFunction(Initializer
3567 , DestType, false, dap))
Douglas Gregor8e960432010-11-08 03:40:48 +00003568 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3569 else
3570 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003571 } else {
3572 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003573
3574 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003575 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003576}
3577
3578InitializationSequence::~InitializationSequence() {
3579 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3580 StepEnd = Steps.end();
3581 Step != StepEnd; ++Step)
3582 Step->Destroy();
3583}
3584
3585//===----------------------------------------------------------------------===//
3586// Perform initialization
3587//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003589getAssignmentAction(const InitializedEntity &Entity) {
3590 switch(Entity.getKind()) {
3591 case InitializedEntity::EK_Variable:
3592 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003593 case InitializedEntity::EK_Exception:
3594 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003595 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003596 return Sema::AA_Initializing;
3597
3598 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003599 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003600 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3601 return Sema::AA_Sending;
3602
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003603 return Sema::AA_Passing;
3604
3605 case InitializedEntity::EK_Result:
3606 return Sema::AA_Returning;
3607
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003608 case InitializedEntity::EK_Temporary:
3609 // FIXME: Can we tell apart casting vs. converting?
3610 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003612 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003613 case InitializedEntity::EK_ArrayElement:
3614 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003615 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003616 return Sema::AA_Initializing;
3617 }
3618
3619 return Sema::AA_Converting;
3620}
3621
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003622/// \brief Whether we should binding a created object as a temporary when
3623/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003624static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003625 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003626 case InitializedEntity::EK_ArrayElement:
3627 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003628 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003629 case InitializedEntity::EK_New:
3630 case InitializedEntity::EK_Variable:
3631 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003632 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003633 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003634 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003635 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003636 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003638 case InitializedEntity::EK_Parameter:
3639 case InitializedEntity::EK_Temporary:
3640 return true;
3641 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003642
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003643 llvm_unreachable("missed an InitializedEntity kind?");
3644}
3645
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003646/// \brief Whether the given entity, when initialized with an object
3647/// created for that initialization, requires destruction.
3648static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3649 switch (Entity.getKind()) {
3650 case InitializedEntity::EK_Member:
3651 case InitializedEntity::EK_Result:
3652 case InitializedEntity::EK_New:
3653 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003654 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003655 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003656 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003657 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003659 case InitializedEntity::EK_Variable:
3660 case InitializedEntity::EK_Parameter:
3661 case InitializedEntity::EK_Temporary:
3662 case InitializedEntity::EK_ArrayElement:
3663 case InitializedEntity::EK_Exception:
3664 return true;
3665 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666
3667 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003668}
3669
Douglas Gregor523d46a2010-04-18 07:40:54 +00003670/// \brief Make a (potentially elidable) temporary copy of the object
3671/// provided by the given initializer by calling the appropriate copy
3672/// constructor.
3673///
3674/// \param S The Sema object used for type-checking.
3675///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003676/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003677/// the type of the initializer expression or a superclass thereof.
3678///
3679/// \param Enter The entity being initialized.
3680///
3681/// \param CurInit The initializer expression.
3682///
3683/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3684/// is permitted in C++03 (but not C++0x) when binding a reference to
3685/// an rvalue.
3686///
3687/// \returns An expression that copies the initializer expression into
3688/// a temporary object, or an error expression if a copy could not be
3689/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003690static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003691 QualType T,
3692 const InitializedEntity &Entity,
3693 ExprResult CurInit,
3694 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003695 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003696 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003697 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003698 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003699 Class = cast<CXXRecordDecl>(Record->getDecl());
3700 if (!Class)
3701 return move(CurInit);
3702
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003703 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003704 // When certain criteria are met, an implementation is allowed to
3705 // omit the copy/move construction of a class object, even if the
3706 // copy/move constructor and/or destructor for the object have
3707 // side effects. [...]
3708 // - when a temporary class object that has not been bound to a
3709 // reference (12.2) would be copied/moved to a class object
3710 // with the same cv-unqualified type, the copy/move operation
3711 // can be omitted by constructing the temporary object
3712 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003713 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003714 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003715 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003717 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003718 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003719 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003720 switch (Entity.getKind()) {
3721 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003722 Loc = Entity.getReturnLoc();
3723 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003724
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003725 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003726 Loc = Entity.getThrowLoc();
3727 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003729 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003730 Loc = Entity.getDecl()->getLocation();
3731 break;
3732
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003733 case InitializedEntity::EK_ArrayElement:
3734 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003735 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003736 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003737 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003738 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003739 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003740 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003741 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003742 Loc = CurInitExpr->getLocStart();
3743 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003744 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003745
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003747 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3748 return move(CurInit);
3749
Douglas Gregorcc15f012011-01-21 19:38:21 +00003750 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003751 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003752 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003753 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003754 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003755 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003756 // C++0x [dcl.init]p16, second bullet to class types, this
3757 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003758 CXXConstructorDecl *Constructor = 0;
3759
3760 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003761 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003762 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003763 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003764 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003765 continue;
3766
3767 DeclAccessPair FoundDecl
3768 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3769 S.AddOverloadCandidate(Constructor, FoundDecl,
3770 &CurInitExpr, 1, CandidateSet);
3771 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003773
3774 // Handle constructor templates.
3775 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3776 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003777 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003778
Douglas Gregor6493cc52010-11-08 17:16:59 +00003779 Constructor = cast<CXXConstructorDecl>(
3780 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003781 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003782 continue;
3783
3784 // FIXME: Do we need to limit this to copy-constructor-like
3785 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003786 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003787 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3788 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3789 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003792 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003793 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003794 case OR_Success:
3795 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003797 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003798 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3799 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3800 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003801 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003802 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003803 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003804 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003805 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003806 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003808 case OR_Ambiguous:
3809 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003810 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003811 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003812 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003813 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003815 case OR_Deleted:
3816 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003817 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003818 << CurInitExpr->getSourceRange();
3819 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00003820 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003821 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003822 }
3823
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003824 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003825 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003826 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003827
Anders Carlsson9a68a672010-04-21 18:47:17 +00003828 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003829 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003830
3831 if (IsExtraneousCopy) {
3832 // If this is a totally extraneous copy for C++03 reference
3833 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003834 // expression. We don't generate an (elided) copy operation here
3835 // because doing so would require us to pass down a flag to avoid
3836 // infinite recursion, where each step adds another extraneous,
3837 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003838
Douglas Gregor2559a702010-04-18 07:57:34 +00003839 // Instantiate the default arguments of any extra parameters in
3840 // the selected copy constructor, as if we were going to create a
3841 // proper call to the copy constructor.
3842 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3843 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3844 if (S.RequireCompleteType(Loc, Parm->getType(),
3845 S.PDiag(diag::err_call_incomplete_argument)))
3846 break;
3847
3848 // Build the default argument expression; we don't actually care
3849 // if this succeeds or not, because this routine will complain
3850 // if there was a problem.
3851 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3852 }
3853
Douglas Gregor523d46a2010-04-18 07:40:54 +00003854 return S.Owned(CurInitExpr);
3855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003856
Chandler Carruth25ca4212011-02-25 19:41:05 +00003857 S.MarkDeclarationReferenced(Loc, Constructor);
3858
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003859 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003860 // constructor call (we might have derived-to-base conversions, or
3861 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003862 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003863 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003864 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003865
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003866 // Actually perform the constructor call.
3867 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003868 move_arg(ConstructorArgs),
3869 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003870 CXXConstructExpr::CK_Complete,
3871 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003872
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003873 // If we're supposed to bind temporaries, do so.
3874 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3875 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3876 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003877}
Douglas Gregor20093b42009-12-09 23:02:17 +00003878
Douglas Gregora41a8c52010-04-22 00:20:18 +00003879void InitializationSequence::PrintInitLocationNote(Sema &S,
3880 const InitializedEntity &Entity) {
3881 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3882 if (Entity.getDecl()->getLocation().isInvalid())
3883 return;
3884
3885 if (Entity.getDecl()->getDeclName())
3886 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3887 << Entity.getDecl()->getDeclName();
3888 else
3889 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3890 }
3891}
3892
Sebastian Redl3b802322011-07-14 19:07:55 +00003893static bool isReferenceBinding(const InitializationSequence::Step &s) {
3894 return s.Kind == InitializationSequence::SK_BindReference ||
3895 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
3896}
3897
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003898ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003899InitializationSequence::Perform(Sema &S,
3900 const InitializedEntity &Entity,
3901 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003902 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003903 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00003904 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003905 unsigned NumArgs = Args.size();
3906 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003907 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003908 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003909
Sebastian Redl7491c492011-06-05 13:59:11 +00003910 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003911 // If the declaration is a non-dependent, incomplete array type
3912 // that has an initializer, then its type will be completed once
3913 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003914 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003915 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003916 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003917 if (const IncompleteArrayType *ArrayT
3918 = S.Context.getAsIncompleteArrayType(DeclType)) {
3919 // FIXME: We don't currently have the ability to accurately
3920 // compute the length of an initializer list without
3921 // performing full type-checking of the initializer list
3922 // (since we have to determine where braces are implicitly
3923 // introduced and such). So, we fall back to making the array
3924 // type a dependently-sized array type with no specified
3925 // bound.
3926 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3927 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003928
Douglas Gregord87b61f2009-12-10 17:56:55 +00003929 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003930 if (DeclaratorDecl *DD = Entity.getDecl()) {
3931 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3932 TypeLoc TL = TInfo->getTypeLoc();
3933 if (IncompleteArrayTypeLoc *ArrayLoc
3934 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3935 Brackets = ArrayLoc->getBracketsRange();
3936 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003937 }
3938
3939 *ResultType
3940 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3941 /*NumElts=*/0,
3942 ArrayT->getSizeModifier(),
3943 ArrayT->getIndexTypeCVRQualifiers(),
3944 Brackets);
3945 }
3946
3947 }
3948 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00003949 assert(Kind.getKind() == InitializationKind::IK_Copy ||
3950 Kind.isExplicitCast());
3951 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003952 }
3953
Sebastian Redl7491c492011-06-05 13:59:11 +00003954 // No steps means no initialization.
3955 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00003956 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003957
Douglas Gregord6542d82009-12-22 15:35:07 +00003958 QualType DestType = Entity.getType().getNonReferenceType();
3959 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003960 // the same as Entity.getDecl()->getType() in cases involving type merging,
3961 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003962 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003963 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003964 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003965
John McCall60d7b3a2010-08-24 06:29:42 +00003966 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003967
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00003969 // grab the only argument out the Args and place it into the "current"
3970 // initializer.
3971 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003972 case SK_ResolveAddressOfOverloadedFunction:
3973 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003974 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003975 case SK_CastDerivedToBaseLValue:
3976 case SK_BindReference:
3977 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003978 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003979 case SK_UserConversion:
3980 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003981 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003982 case SK_QualificationConversionRValue:
3983 case SK_ConversionSequence:
3984 case SK_ListInitialization:
3985 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003986 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003987 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00003988 case SK_ArrayInit:
3989 case SK_PassByIndirectCopyRestore:
3990 case SK_PassByIndirectRestore:
3991 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003992 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00003993 CurInit = Args.get()[0];
3994 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003995
3996 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00003997 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3998 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3999 if (CurInit.isInvalid())
4000 return ExprError();
4001 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004002 break;
John McCallf6a16482010-12-04 03:47:34 +00004003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004005 case SK_ConstructorInitialization:
4006 case SK_ZeroInitialization:
4007 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004008 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
4010 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004011 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004012 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004013 for (step_iterator Step = step_begin(), StepEnd = step_end();
4014 Step != StepEnd; ++Step) {
4015 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004016 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017
John Wiegley429bb272011-04-08 18:41:53 +00004018 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004019
Douglas Gregor20093b42009-12-09 23:02:17 +00004020 switch (Step->Kind) {
4021 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004023 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004024 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004025 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004026 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004027 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004028 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004029 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030
Douglas Gregor20093b42009-12-09 23:02:17 +00004031 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004032 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004033 case SK_CastDerivedToBaseLValue: {
4034 // We have a derived-to-base cast that produces either an rvalue or an
4035 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004036
John McCallf871d0c2010-08-07 06:22:56 +00004037 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004038
Douglas Gregor20093b42009-12-09 23:02:17 +00004039 // Casts to inaccessible base classes are allowed with C-style casts.
4040 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4041 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004042 CurInit.get()->getLocStart(),
4043 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004044 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004045 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004046
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004047 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4048 QualType T = SourceType;
4049 if (const PointerType *Pointer = T->getAs<PointerType>())
4050 T = Pointer->getPointeeType();
4051 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004052 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004053 cast<CXXRecordDecl>(RecordTy->getDecl()));
4054 }
4055
John McCall5baba9d2010-08-25 10:28:54 +00004056 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004057 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004058 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004059 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004060 VK_XValue :
4061 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004062 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4063 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004064 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004065 CurInit.get(),
4066 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004067 break;
4068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069
Douglas Gregor20093b42009-12-09 23:02:17 +00004070 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004071 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004072 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4073 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004074 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004075 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004076 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004078 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004079 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004080
John Wiegley429bb272011-04-08 18:41:53 +00004081 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004082 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004083 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4084 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004085 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004086 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004087 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004088 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004089
Douglas Gregor20093b42009-12-09 23:02:17 +00004090 // Reference binding does not have any corresponding ASTs.
4091
4092 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004093 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004094 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004095
Douglas Gregor20093b42009-12-09 23:02:17 +00004096 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004097
Douglas Gregor20093b42009-12-09 23:02:17 +00004098 case SK_BindReferenceToTemporary:
4099 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004100 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004101 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004102
Douglas Gregor03e80032011-06-21 17:03:29 +00004103 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004104 CurInit = new (S.Context) MaterializeTemporaryExpr(
4105 Entity.getType().getNonReferenceType(),
4106 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004107 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004108
4109 // If we're binding to an Objective-C object that has lifetime, we
4110 // need cleanups.
4111 if (S.getLangOptions().ObjCAutoRefCount &&
4112 CurInit.get()->getType()->isObjCLifetimeType())
4113 S.ExprNeedsCleanups = true;
4114
Douglas Gregor20093b42009-12-09 23:02:17 +00004115 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregor523d46a2010-04-18 07:40:54 +00004117 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004119 /*IsExtraneousCopy=*/true);
4120 break;
4121
Douglas Gregor20093b42009-12-09 23:02:17 +00004122 case SK_UserConversion: {
4123 // We have a user-defined conversion that invokes either a constructor
4124 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004125 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004126 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004127 FunctionDecl *Fn = Step->Function.Function;
4128 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004129 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004130 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004131 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004132 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004133 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004134 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004135 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004136
Douglas Gregor20093b42009-12-09 23:02:17 +00004137 // Determine the arguments required to actually perform the constructor
4138 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004139 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004140 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004141 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004142 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004143 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
Douglas Gregor20093b42009-12-09 23:02:17 +00004145 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004147 move_arg(ConstructorArgs),
4148 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004149 CXXConstructExpr::CK_Complete,
4150 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004151 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004152 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004153
Anders Carlsson9a68a672010-04-21 18:47:17 +00004154 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004155 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004156 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004157
John McCall2de56d12010-08-25 11:45:40 +00004158 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004159 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4160 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4161 S.IsDerivedFrom(SourceType, Class))
4162 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004164 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004165 } else {
4166 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004167 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004168 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004169 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004170 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004171 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172
4173 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004174 // derived-to-base conversion? I believe the answer is "no", because
4175 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004176 ExprResult CurInitExprRes =
4177 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4178 FoundFn, Conversion);
4179 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004180 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004181 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182
Douglas Gregor20093b42009-12-09 23:02:17 +00004183 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004184 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004185 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004186 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187
John McCall2de56d12010-08-25 11:45:40 +00004188 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004190 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192
Sebastian Redl3b802322011-07-14 19:07:55 +00004193 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004194 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004195 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004196 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004197 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004198 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004199 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004200 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004201 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004202 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004203 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4204 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004205 }
4206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004207
Sebastian Redl906082e2010-07-20 04:20:21 +00004208 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004209 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004210 CurInit.get()->getType(),
4211 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004212 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004213
Douglas Gregor2f599792010-04-02 18:24:57 +00004214 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004215 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4216 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004217
Douglas Gregor20093b42009-12-09 23:02:17 +00004218 break;
4219 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004220
Douglas Gregor20093b42009-12-09 23:02:17 +00004221 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004222 case SK_QualificationConversionXValue:
4223 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004224 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004225 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004226 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004227 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004228 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004229 VK_XValue :
4230 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004231 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004232 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004233 }
4234
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004235 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004236 Sema::CheckedConversionKind CCK
4237 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4238 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4239 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4240 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004241 ExprResult CurInitExprRes =
4242 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004243 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004244 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004245 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004246 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004247 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249
Douglas Gregord87b61f2009-12-10 17:56:55 +00004250 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004251 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004252 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004253 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004254 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004255
4256 CurInit.release();
4257 CurInit = S.Owned(InitList);
4258 break;
4259 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004260
4261 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004262 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004263 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004264 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265
Douglas Gregor51c56d62009-12-14 20:49:26 +00004266 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004267 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004268 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4269 ? Kind.getEqualLoc()
4270 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004271
4272 if (Kind.getKind() == InitializationKind::IK_Default) {
4273 // Force even a trivial, implicit default constructor to be
4274 // semantically checked. We do this explicitly because we don't build
4275 // the definition for completely trivial constructors.
4276 CXXRecordDecl *ClassDecl = Constructor->getParent();
4277 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004278 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004279 ClassDecl->hasTrivialDefaultConstructor() &&
4280 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004281 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4282 }
4283
Douglas Gregor51c56d62009-12-14 20:49:26 +00004284 // Determine the arguments required to actually perform the constructor
4285 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004287 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004288 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289
4290
Douglas Gregor91be6f52010-03-02 17:18:33 +00004291 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004292 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004293 (Kind.getKind() == InitializationKind::IK_Direct ||
4294 Kind.getKind() == InitializationKind::IK_Value)) {
4295 // An explicitly-constructed temporary, e.g., X(1, 2).
4296 unsigned NumExprs = ConstructorArgs.size();
4297 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004298 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004299 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300
Douglas Gregorab6677e2010-09-08 00:15:04 +00004301 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4302 if (!TSInfo)
4303 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304
Douglas Gregor91be6f52010-03-02 17:18:33 +00004305 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4306 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004307 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004309 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004310 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004311 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004312 } else {
4313 CXXConstructExpr::ConstructionKind ConstructKind =
4314 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004316 if (Entity.getKind() == InitializedEntity::EK_Base) {
4317 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004319 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004320 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004321 ConstructKind = CXXConstructExpr::CK_Delegating;
4322 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Chandler Carruth428edaf2010-10-25 08:47:36 +00004324 // Only get the parenthesis range if it is a direct construction.
4325 SourceRange parenRange =
4326 Kind.getKind() == InitializationKind::IK_Direct ?
4327 Kind.getParenRange() : SourceRange();
4328
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004329 // If the entity allows NRVO, mark the construction as elidable
4330 // unconditionally.
4331 if (Entity.allowsNRVO())
4332 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4333 Constructor, /*Elidable=*/true,
4334 move_arg(ConstructorArgs),
4335 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004336 ConstructKind,
4337 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004338 else
4339 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004340 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004341 move_arg(ConstructorArgs),
4342 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004343 ConstructKind,
4344 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004345 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004346 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004347 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004348
4349 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004350 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004351 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004352 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353
Douglas Gregor2f599792010-04-02 18:24:57 +00004354 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004355 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004356
Douglas Gregor51c56d62009-12-14 20:49:26 +00004357 break;
4358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359
Douglas Gregor71d17402009-12-15 00:01:57 +00004360 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004361 step_iterator NextStep = Step;
4362 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004364 NextStep->Kind == SK_ConstructorInitialization) {
4365 // The need for zero-initialization is recorded directly into
4366 // the call to the object's constructor within the next step.
4367 ConstructorInitRequiresZeroInit = true;
4368 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4369 S.getLangOptions().CPlusPlus &&
4370 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004371 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4372 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004373 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004374 Kind.getRange().getBegin());
4375
4376 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4377 TSInfo->getType().getNonLValueExprType(S.Context),
4378 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004379 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004380 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004381 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004382 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004383 break;
4384 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004385
4386 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004387 QualType SourceType = CurInit.get()->getType();
4388 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004389 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004390 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4391 if (Result.isInvalid())
4392 return ExprError();
4393 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004394
4395 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004396 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004397 if (ConvTy != Sema::Compatible &&
4398 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004399 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004400 == Sema::Compatible)
4401 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004402 if (CurInitExprRes.isInvalid())
4403 return ExprError();
4404 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004405
Douglas Gregora41a8c52010-04-22 00:20:18 +00004406 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004407 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4408 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004409 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004410 getAssignmentAction(Entity),
4411 &Complained)) {
4412 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004413 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004414 } else if (Complained)
4415 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004416 break;
4417 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004418
4419 case SK_StringInit: {
4420 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004421 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004422 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004423 break;
4424 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004425
4426 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004427 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004428 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004429 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004430 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004431
4432 case SK_ArrayInit:
4433 // Okay: we checked everything before creating this step. Note that
4434 // this is a GNU extension.
4435 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004436 << Step->Type << CurInit.get()->getType()
4437 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004438
4439 // If the destination type is an incomplete array type, update the
4440 // type accordingly.
4441 if (ResultType) {
4442 if (const IncompleteArrayType *IncompleteDest
4443 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4444 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004445 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004446 *ResultType = S.Context.getConstantArrayType(
4447 IncompleteDest->getElementType(),
4448 ConstantSource->getSize(),
4449 ArrayType::Normal, 0);
4450 }
4451 }
4452 }
John McCallf85e1932011-06-15 23:02:42 +00004453 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004454
John McCallf85e1932011-06-15 23:02:42 +00004455 case SK_PassByIndirectCopyRestore:
4456 case SK_PassByIndirectRestore:
4457 checkIndirectCopyRestoreSource(S, CurInit.get());
4458 CurInit = S.Owned(new (S.Context)
4459 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4460 Step->Kind == SK_PassByIndirectCopyRestore));
4461 break;
4462
4463 case SK_ProduceObjCObject:
4464 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4465 CK_ObjCProduceObject,
4466 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004467 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004468 }
4469 }
John McCall15d7d122010-11-11 03:21:53 +00004470
4471 // Diagnose non-fatal problems with the completed initialization.
4472 if (Entity.getKind() == InitializedEntity::EK_Member &&
4473 cast<FieldDecl>(Entity.getDecl())->isBitField())
4474 S.CheckBitFieldInitialization(Kind.getLocation(),
4475 cast<FieldDecl>(Entity.getDecl()),
4476 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004477
Douglas Gregor20093b42009-12-09 23:02:17 +00004478 return move(CurInit);
4479}
4480
4481//===----------------------------------------------------------------------===//
4482// Diagnose initialization failures
4483//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004485 const InitializedEntity &Entity,
4486 const InitializationKind &Kind,
4487 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004488 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004489 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004490
Douglas Gregord6542d82009-12-22 15:35:07 +00004491 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004492 switch (Failure) {
4493 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004494 // FIXME: Customize for the initialized entity?
4495 if (NumArgs == 0)
4496 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4497 << DestType.getNonReferenceType();
4498 else // FIXME: diagnostic below could be better!
4499 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4500 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004501 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004502
Douglas Gregor20093b42009-12-09 23:02:17 +00004503 case FK_ArrayNeedsInitList:
4504 case FK_ArrayNeedsInitListOrStringLiteral:
4505 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4506 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4507 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004509 case FK_ArrayTypeMismatch:
4510 case FK_NonConstantArrayInit:
4511 S.Diag(Kind.getLocation(),
4512 (Failure == FK_ArrayTypeMismatch
4513 ? diag::err_array_init_different_type
4514 : diag::err_array_init_non_constant_array))
4515 << DestType.getNonReferenceType()
4516 << Args[0]->getType()
4517 << Args[0]->getSourceRange();
4518 break;
4519
John McCall6bb80172010-03-30 21:47:33 +00004520 case FK_AddressOfOverloadFailed: {
4521 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004523 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004524 true,
4525 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004526 break;
John McCall6bb80172010-03-30 21:47:33 +00004527 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004528
Douglas Gregor20093b42009-12-09 23:02:17 +00004529 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004530 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004531 switch (FailedOverloadResult) {
4532 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004533 if (Failure == FK_UserConversionOverloadFailed)
4534 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4535 << Args[0]->getType() << DestType
4536 << Args[0]->getSourceRange();
4537 else
4538 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4539 << DestType << Args[0]->getType()
4540 << Args[0]->getSourceRange();
4541
John McCall120d63c2010-08-24 20:38:10 +00004542 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004543 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004544
Douglas Gregor20093b42009-12-09 23:02:17 +00004545 case OR_No_Viable_Function:
4546 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4547 << Args[0]->getType() << DestType.getNonReferenceType()
4548 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004549 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004550 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551
Douglas Gregor20093b42009-12-09 23:02:17 +00004552 case OR_Deleted: {
4553 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4554 << Args[0]->getType() << DestType.getNonReferenceType()
4555 << Args[0]->getSourceRange();
4556 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004557 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004558 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4559 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004560 if (Ovl == OR_Deleted) {
4561 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004562 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004563 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004564 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004565 }
4566 break;
4567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568
Douglas Gregor20093b42009-12-09 23:02:17 +00004569 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004570 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004571 break;
4572 }
4573 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004574
Douglas Gregor20093b42009-12-09 23:02:17 +00004575 case FK_NonConstLValueReferenceBindingToTemporary:
4576 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004578 Failure == FK_NonConstLValueReferenceBindingToTemporary
4579 ? diag::err_lvalue_reference_bind_to_temporary
4580 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004581 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004582 << DestType.getNonReferenceType()
4583 << Args[0]->getType()
4584 << Args[0]->getSourceRange();
4585 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004586
Douglas Gregor20093b42009-12-09 23:02:17 +00004587 case FK_RValueReferenceBindingToLValue:
4588 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004589 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004590 << Args[0]->getSourceRange();
4591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004592
Douglas Gregor20093b42009-12-09 23:02:17 +00004593 case FK_ReferenceInitDropsQualifiers:
4594 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4595 << DestType.getNonReferenceType()
4596 << Args[0]->getType()
4597 << Args[0]->getSourceRange();
4598 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599
Douglas Gregor20093b42009-12-09 23:02:17 +00004600 case FK_ReferenceInitFailed:
4601 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4602 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004603 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004604 << Args[0]->getType()
4605 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004606 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4607 Args[0]->getType()->isObjCObjectPointerType())
4608 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004609 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004610
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004611 case FK_ConversionFailed: {
4612 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004613 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4614 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004615 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004616 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004617 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004618 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004619 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4620 Args[0]->getType()->isObjCObjectPointerType())
4621 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004622 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004623 }
John Wiegley429bb272011-04-08 18:41:53 +00004624
4625 case FK_ConversionFromPropertyFailed:
4626 // No-op. This error has already been reported.
4627 break;
4628
Douglas Gregord87b61f2009-12-10 17:56:55 +00004629 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004630 SourceRange R;
4631
4632 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004633 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004634 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004635 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004636 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004637
Douglas Gregor19311e72010-09-08 21:40:08 +00004638 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4639 if (Kind.isCStyleOrFunctionalCast())
4640 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4641 << R;
4642 else
4643 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4644 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004645 break;
4646 }
4647
4648 case FK_ReferenceBindingToInitList:
4649 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4650 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4651 break;
4652
4653 case FK_InitListBadDestinationType:
4654 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4655 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004657
Douglas Gregor51c56d62009-12-14 20:49:26 +00004658 case FK_ConstructorOverloadFailed: {
4659 SourceRange ArgsRange;
4660 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004661 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004662 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004663
Douglas Gregor51c56d62009-12-14 20:49:26 +00004664 // FIXME: Using "DestType" for the entity we're printing is probably
4665 // bad.
4666 switch (FailedOverloadResult) {
4667 case OR_Ambiguous:
4668 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4669 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004670 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4671 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004672 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004673
Douglas Gregor51c56d62009-12-14 20:49:26 +00004674 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004675 if (Kind.getKind() == InitializationKind::IK_Default &&
4676 (Entity.getKind() == InitializedEntity::EK_Base ||
4677 Entity.getKind() == InitializedEntity::EK_Member) &&
4678 isa<CXXConstructorDecl>(S.CurContext)) {
4679 // This is implicit default initialization of a member or
4680 // base within a constructor. If no viable function was
4681 // found, notify the user that she needs to explicitly
4682 // initialize this base/member.
4683 CXXConstructorDecl *Constructor
4684 = cast<CXXConstructorDecl>(S.CurContext);
4685 if (Entity.getKind() == InitializedEntity::EK_Base) {
4686 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4687 << Constructor->isImplicit()
4688 << S.Context.getTypeDeclType(Constructor->getParent())
4689 << /*base=*/0
4690 << Entity.getType();
4691
4692 RecordDecl *BaseDecl
4693 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4694 ->getDecl();
4695 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4696 << S.Context.getTagDeclType(BaseDecl);
4697 } else {
4698 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4699 << Constructor->isImplicit()
4700 << S.Context.getTypeDeclType(Constructor->getParent())
4701 << /*member=*/1
4702 << Entity.getName();
4703 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4704
4705 if (const RecordType *Record
4706 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004707 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004708 diag::note_previous_decl)
4709 << S.Context.getTagDeclType(Record->getDecl());
4710 }
4711 break;
4712 }
4713
Douglas Gregor51c56d62009-12-14 20:49:26 +00004714 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4715 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004716 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004717 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004718
Douglas Gregor51c56d62009-12-14 20:49:26 +00004719 case OR_Deleted: {
4720 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4721 << true << DestType << ArgsRange;
4722 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004723 OverloadingResult Ovl
4724 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004725 if (Ovl == OR_Deleted) {
4726 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004727 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004728 } else {
4729 llvm_unreachable("Inconsistent overload resolution?");
4730 }
4731 break;
4732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733
Douglas Gregor51c56d62009-12-14 20:49:26 +00004734 case OR_Success:
4735 llvm_unreachable("Conversion did not fail!");
4736 break;
4737 }
4738 break;
4739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004740
Douglas Gregor99a2e602009-12-16 01:38:02 +00004741 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004742 if (Entity.getKind() == InitializedEntity::EK_Member &&
4743 isa<CXXConstructorDecl>(S.CurContext)) {
4744 // This is implicit default-initialization of a const member in
4745 // a constructor. Complain that it needs to be explicitly
4746 // initialized.
4747 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4748 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4749 << Constructor->isImplicit()
4750 << S.Context.getTypeDeclType(Constructor->getParent())
4751 << /*const=*/1
4752 << Entity.getName();
4753 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4754 << Entity.getName();
4755 } else {
4756 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4757 << DestType << (bool)DestType->getAs<RecordType>();
4758 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004759 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004761 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004762 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004763 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004765 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004766
Douglas Gregora41a8c52010-04-22 00:20:18 +00004767 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004768 return true;
4769}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004770
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004771void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4772 switch (SequenceKind) {
4773 case FailedSequence: {
4774 OS << "Failed sequence: ";
4775 switch (Failure) {
4776 case FK_TooManyInitsForReference:
4777 OS << "too many initializers for reference";
4778 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004779
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004780 case FK_ArrayNeedsInitList:
4781 OS << "array requires initializer list";
4782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004783
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004784 case FK_ArrayNeedsInitListOrStringLiteral:
4785 OS << "array requires initializer list or string literal";
4786 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004787
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004788 case FK_ArrayTypeMismatch:
4789 OS << "array type mismatch";
4790 break;
4791
4792 case FK_NonConstantArrayInit:
4793 OS << "non-constant array initializer";
4794 break;
4795
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004796 case FK_AddressOfOverloadFailed:
4797 OS << "address of overloaded function failed";
4798 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004799
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004800 case FK_ReferenceInitOverloadFailed:
4801 OS << "overload resolution for reference initialization failed";
4802 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004803
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004804 case FK_NonConstLValueReferenceBindingToTemporary:
4805 OS << "non-const lvalue reference bound to temporary";
4806 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004807
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004808 case FK_NonConstLValueReferenceBindingToUnrelated:
4809 OS << "non-const lvalue reference bound to unrelated type";
4810 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004811
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004812 case FK_RValueReferenceBindingToLValue:
4813 OS << "rvalue reference bound to an lvalue";
4814 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004815
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004816 case FK_ReferenceInitDropsQualifiers:
4817 OS << "reference initialization drops qualifiers";
4818 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004819
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004820 case FK_ReferenceInitFailed:
4821 OS << "reference initialization failed";
4822 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004823
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004824 case FK_ConversionFailed:
4825 OS << "conversion failed";
4826 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827
John Wiegley429bb272011-04-08 18:41:53 +00004828 case FK_ConversionFromPropertyFailed:
4829 OS << "conversion from property failed";
4830 break;
4831
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004832 case FK_TooManyInitsForScalar:
4833 OS << "too many initializers for scalar";
4834 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004835
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004836 case FK_ReferenceBindingToInitList:
4837 OS << "referencing binding to initializer list";
4838 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004839
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004840 case FK_InitListBadDestinationType:
4841 OS << "initializer list for non-aggregate, non-scalar type";
4842 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004843
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004844 case FK_UserConversionOverloadFailed:
4845 OS << "overloading failed for user-defined conversion";
4846 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004847
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004848 case FK_ConstructorOverloadFailed:
4849 OS << "constructor overloading failed";
4850 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004851
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004852 case FK_DefaultInitOfConst:
4853 OS << "default initialization of a const variable";
4854 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004855
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004856 case FK_Incomplete:
4857 OS << "initialization of incomplete type";
4858 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004860 OS << '\n';
4861 return;
4862 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004863
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004864 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00004865 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004866 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004867
Sebastian Redl7491c492011-06-05 13:59:11 +00004868 case NormalSequence:
4869 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004870 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004872
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004873 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4874 if (S != step_begin()) {
4875 OS << " -> ";
4876 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004878 switch (S->Kind) {
4879 case SK_ResolveAddressOfOverloadedFunction:
4880 OS << "resolve address of overloaded function";
4881 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004882
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004883 case SK_CastDerivedToBaseRValue:
4884 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
Sebastian Redl906082e2010-07-20 04:20:21 +00004887 case SK_CastDerivedToBaseXValue:
4888 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4889 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004890
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004891 case SK_CastDerivedToBaseLValue:
4892 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4893 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004894
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004895 case SK_BindReference:
4896 OS << "bind reference to lvalue";
4897 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004898
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004899 case SK_BindReferenceToTemporary:
4900 OS << "bind reference to a temporary";
4901 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004902
Douglas Gregor523d46a2010-04-18 07:40:54 +00004903 case SK_ExtraneousCopyToTemporary:
4904 OS << "extraneous C++03 copy to temporary";
4905 break;
4906
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004907 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004908 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004909 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004910
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004911 case SK_QualificationConversionRValue:
4912 OS << "qualification conversion (rvalue)";
4913
Sebastian Redl906082e2010-07-20 04:20:21 +00004914 case SK_QualificationConversionXValue:
4915 OS << "qualification conversion (xvalue)";
4916
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004917 case SK_QualificationConversionLValue:
4918 OS << "qualification conversion (lvalue)";
4919 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004920
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004921 case SK_ConversionSequence:
4922 OS << "implicit conversion sequence (";
4923 S->ICS->DebugPrint(); // FIXME: use OS
4924 OS << ")";
4925 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004926
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004927 case SK_ListInitialization:
4928 OS << "list initialization";
4929 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004930
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004931 case SK_ConstructorInitialization:
4932 OS << "constructor initialization";
4933 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004934
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004935 case SK_ZeroInitialization:
4936 OS << "zero initialization";
4937 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004938
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004939 case SK_CAssignment:
4940 OS << "C assignment";
4941 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004942
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004943 case SK_StringInit:
4944 OS << "string initialization";
4945 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004946
4947 case SK_ObjCObjectConversion:
4948 OS << "Objective-C object conversion";
4949 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004950
4951 case SK_ArrayInit:
4952 OS << "array initialization";
4953 break;
John McCallf85e1932011-06-15 23:02:42 +00004954
4955 case SK_PassByIndirectCopyRestore:
4956 OS << "pass by indirect copy and restore";
4957 break;
4958
4959 case SK_PassByIndirectRestore:
4960 OS << "pass by indirect restore";
4961 break;
4962
4963 case SK_ProduceObjCObject:
4964 OS << "Objective-C object retension";
4965 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004966 }
4967 }
4968}
4969
4970void InitializationSequence::dump() const {
4971 dump(llvm::errs());
4972}
4973
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004974//===----------------------------------------------------------------------===//
4975// Initialization helper functions
4976//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00004977bool
4978Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
4979 ExprResult Init) {
4980 if (Init.isInvalid())
4981 return false;
4982
4983 Expr *InitE = Init.get();
4984 assert(InitE && "No initialization expression");
4985
4986 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
4987 SourceLocation());
4988 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00004989 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00004990}
4991
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004992ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004993Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4994 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004995 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004996 if (Init.isInvalid())
4997 return ExprError();
4998
John McCall15d7d122010-11-11 03:21:53 +00004999 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005000 assert(InitE && "No initialization expression?");
5001
5002 if (EqualLoc.isInvalid())
5003 EqualLoc = InitE->getLocStart();
5004
5005 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5006 EqualLoc);
5007 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5008 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00005009 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005010}