blob: adf88c62ccdf4098b89fb8d751602f49aa224a24 [file] [log] [blame]
Steve Narofff8ecff22008-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//
Rafael Espindola699fc4d2011-07-14 22:58:04 +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.
Chris Lattner0cb78032009-02-24 22:27:37 +000013//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000052 // char array can be initialized with a narrow string.
53 // Only allow char x[] = "foo"; not char x[] = L"foo";
54 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000055 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000056
Eli Friedman42a84652009-05-31 10:54:53 +000057 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
58 // correction from DR343): "An array with element type compatible with a
59 // qualified or unqualified version of wchar_t may be initialized by a wide
60 // string literal, optionally enclosed in braces."
61 if (Context.typesAreCompatible(Context.getWCharType(),
62 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000063 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner0cb78032009-02-24 22:27:37 +000065 return 0;
66}
67
John McCall66884dd2011-02-21 07:22:22 +000068static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
69 const ArrayType *arrayType = Context.getAsArrayType(declType);
70 if (!arrayType) return 0;
71
72 return IsStringInit(init, arrayType, Context);
73}
74
John McCall5decec92011-02-21 07:57:55 +000075static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
76 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000077 // Get the length of the string as parsed.
78 uint64_t StrLength =
79 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
80
Mike Stump11289f42009-09-09 15:08:12 +000081
Chris Lattner0cb78032009-02-24 22:27:37 +000082 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000083 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000084 // being initialized to a string literal.
85 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000086 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000087 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000088 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
89 ConstVal,
90 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000091 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000092 }
Mike Stump11289f42009-09-09 15:08:12 +000093
Eli Friedman893abe42009-05-29 18:22:49 +000094 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000095
Eli Friedman554eba92011-04-11 00:23:45 +000096 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000097 // the size may be smaller or larger than the string we are initializing.
98 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000099 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000100 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
101 // For Pascal strings it's OK to strip off the terminating null character,
102 // so the example below is valid:
103 //
104 // unsigned char a[2] = "\pa";
105 if (SL->isPascal())
106 StrLength--;
107 }
108
Eli Friedman554eba92011-04-11 00:23:45 +0000109 // [dcl.init.string]p2
110 if (StrLength > CAT->getSize().getZExtValue())
111 S.Diag(Str->getSourceRange().getBegin(),
112 diag::err_initializer_string_for_char_array_too_long)
113 << Str->getSourceRange();
114 } else {
115 // C99 6.7.8p14.
116 if (StrLength-1 > CAT->getSize().getZExtValue())
117 S.Diag(Str->getSourceRange().getBegin(),
118 diag::warn_initializer_string_for_char_array_too_long)
119 << Str->getSourceRange();
120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Eli Friedman893abe42009-05-29 18:22:49 +0000122 // Set the type to the actual size that we are initializing. If we have
123 // something like:
124 // char x[1] = "foo";
125 // then this will set the string literal's type to char[1].
126 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000127}
128
Chris Lattner0cb78032009-02-24 22:27:37 +0000129//===----------------------------------------------------------------------===//
130// Semantic checking for initializer lists.
131//===----------------------------------------------------------------------===//
132
Douglas Gregorcde232f2009-01-29 01:05:33 +0000133/// @brief Semantic checking for initializer lists.
134///
135/// The InitListChecker class contains a set of routines that each
136/// handle the initialization of a certain kind of entity, e.g.,
137/// arrays, vectors, struct/union types, scalars, etc. The
138/// InitListChecker itself performs a recursive walk of the subobject
139/// structure of the type to be initialized, while stepping through
140/// the initializer list one element at a time. The IList and Index
141/// parameters to each of the Check* routines contain the active
142/// (syntactic) initializer list and the index into that initializer
143/// list that represents the current initializer. Each routine is
144/// responsible for moving that Index forward as it consumes elements.
145///
146/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000147/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000148/// initializer list and the index into that initializer list where we
149/// are copying initializers as we map them over to the semantic
150/// list. Once we have completed our recursive walk of the subobject
151/// structure, we will have constructed a full semantic initializer
152/// list.
153///
154/// C99 designators cause changes in the initializer list traversal,
155/// because they make the initialization "jump" into a specific
156/// subobject and then continue the initialization from that
157/// point. CheckDesignatedInitializer() recursively steps into the
158/// designated subobject and manages backing out the recursion to
159/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000160namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000161class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000162 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000163 bool hadError;
164 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
165 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000166
Anders Carlsson6cabf312010-01-23 23:23:01 +0000167 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000168 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000169 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000170 unsigned &StructuredIndex,
171 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000172 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000173 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000174 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000175 unsigned &StructuredIndex,
176 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000178 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000179 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000180 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000182 unsigned &StructuredIndex,
183 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000184 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000185 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000186 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000187 InitListExpr *StructuredList,
188 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000189 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000190 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000194 void CheckReferenceType(const InitializedEntity &Entity,
195 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000196 unsigned &Index,
197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000199 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000200 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000204 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000205 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000206 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000208 unsigned &StructuredIndex,
209 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000211 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000212 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000213 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000216 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000217 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000218 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000219 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 RecordDecl::field_iterator *NextField,
221 llvm::APSInt *NextElementIndex,
222 unsigned &Index,
223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000225 bool FinishSubobjectInit,
226 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
228 QualType CurrentObjectType,
229 InitListExpr *StructuredList,
230 unsigned StructuredIndex,
231 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000232 void UpdateStructuredListElement(InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 Expr *expr);
235 int numArrayElements(QualType DeclType);
236 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000237
Douglas Gregor2bb07652009-12-22 00:05:34 +0000238 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
239 const InitializedEntity &ParentEntity,
240 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000241 void FillInValueInitializations(const InitializedEntity &Entity,
242 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000244 InitListChecker(Sema &S, const InitializedEntity &Entity,
245 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000246 bool HadError() { return hadError; }
247
248 // @brief Retrieves the fully-structured initializer list used for
249 // semantic analysis and code generation.
250 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
251};
Chris Lattner9ececce2009-02-24 22:48:58 +0000252} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000257 bool &RequiresSecondPass) {
258 SourceLocation Loc = ILE->getSourceRange().getBegin();
259 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000261 = InitializedEntity::InitializeMember(Field, &ParentEntity);
262 if (Init >= NumInits || !ILE->getInit(Init)) {
263 // FIXME: We probably don't need to handle references
264 // specially here, since value-initialization of references is
265 // handled in InitializationSequence.
266 if (Field->getType()->isReferenceType()) {
267 // C++ [dcl.init.aggr]p9:
268 // If an incomplete or empty initializer-list leaves a
269 // member of reference type uninitialized, the program is
270 // ill-formed.
271 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
272 << Field->getType()
273 << ILE->getSyntacticForm()->getSourceRange();
274 SemaRef.Diag(Field->getLocation(),
275 diag::note_uninit_reference_member);
276 hadError = true;
277 return;
278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Douglas Gregor2bb07652009-12-22 00:05:34 +0000280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
283 if (!InitSeq) {
284 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
285 hadError = true;
286 return;
287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
John McCalldadc5752010-08-24 06:29:42 +0000289 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000290 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 if (MemberInit.isInvalid()) {
292 hadError = true;
293 return;
294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
Douglas Gregor2bb07652009-12-22 00:05:34 +0000296 if (hadError) {
297 // Do nothing
298 } else if (Init < NumInits) {
299 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000300 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000301 // Value-initialization requires a constructor call, so
302 // extend the initializer list to include the constructor
303 // call and make a note that we'll need to take another pass
304 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000305 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 RequiresSecondPass = true;
307 }
308 } else if (InitListExpr *InnerILE
309 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310 FillInValueInitializations(MemberEntity, InnerILE,
311 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312}
313
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000314/// Recursively replaces NULL values within the given initializer list
315/// with expressions that perform value-initialization of the
316/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317void
Douglas Gregor723796a2009-12-16 06:35:08 +0000318InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE,
320 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000321 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000322 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000323 SourceLocation Loc = ILE->getSourceRange().getBegin();
324 if (ILE->getSyntacticForm())
325 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000327 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (RType->getDecl()->isUnion() &&
329 ILE->getInitializedFieldInUnion())
330 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
331 Entity, ILE, RequiresSecondPass);
332 else {
333 unsigned Init = 0;
334 for (RecordDecl::field_iterator
335 Field = RType->getDecl()->field_begin(),
336 FieldEnd = RType->getDecl()->field_end();
337 Field != FieldEnd; ++Field) {
338 if (Field->isUnnamedBitfield())
339 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000340
Douglas Gregor2bb07652009-12-22 00:05:34 +0000341 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343
344 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
345 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000347
Douglas Gregor2bb07652009-12-22 00:05:34 +0000348 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 // Only look at the first initialization of a union.
351 if (RType->getDecl()->isUnion())
352 break;
353 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 }
355
356 return;
Mike Stump11289f42009-09-09 15:08:12 +0000357 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000358
359 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregor723796a2009-12-16 06:35:08 +0000361 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 unsigned NumInits = ILE->getNumInits();
363 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000364 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000365 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
367 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000369 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000370 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000371 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000374 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000375 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000376 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000377
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 if (hadError)
381 return;
382
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000383 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
384 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 ElementEntity.setElementIndex(Init);
386
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
John McCalldadc5752010-08-24 06:29:42 +0000397 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000398 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000400 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 return;
402 }
403
404 if (hadError) {
405 // Do nothing
406 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000407 // For arrays, just set the expression used for value-initialization
408 // of the "holes" in the array.
409 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
410 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
411 else
412 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000413 } else {
414 // For arrays, just set the expression used for value-initialization
415 // of the rest of elements and exit.
416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
417 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
418 return;
419 }
420
Sebastian Redld201edf2011-06-05 13:59:11 +0000421 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000422 // Value-initialization requires a constructor call, so
423 // extend the initializer list to include the constructor
424 // call and make a note that we'll need to take another pass
425 // through the initializer list.
426 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
427 RequiresSecondPass = true;
428 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000429 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000430 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000431 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
432 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000433 }
434}
435
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000436
Douglas Gregor723796a2009-12-16 06:35:08 +0000437InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
438 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000439 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000440 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000441
Eli Friedman23a9e312008-05-19 19:16:24 +0000442 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000443 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000444 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000445 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000446 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000447 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000448 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000449
Douglas Gregor723796a2009-12-16 06:35:08 +0000450 if (!hadError) {
451 bool RequiresSecondPass = false;
452 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000453 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000455 RequiresSecondPass);
456 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000457}
458
459int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000460 // FIXME: use a proper constant
461 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000462 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000463 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
465 }
466 return maxElements;
467}
468
469int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000470 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000472 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000473 Field = structDecl->field_begin(),
474 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000475 Field != FieldEnd; ++Field) {
476 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
477 ++InitializableMembers;
478 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000479 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000480 return std::min(InitializableMembers, 1);
481 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000482}
483
Anders Carlsson6cabf312010-01-23 23:23:01 +0000484void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000485 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000486 QualType T, unsigned &Index,
487 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000488 unsigned &StructuredIndex,
489 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000490 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Steve Narofff8ecff22008-05-01 22:18:59 +0000492 if (T->isArrayType())
493 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000494 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000495 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000496 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000497 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000498 else
499 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000500
Eli Friedmane0f832b2008-05-25 13:49:22 +0000501 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000502 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000503 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000505 hadError = true;
506 return;
507 }
508
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 // Build a structured initializer list corresponding to this subobject.
510 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000511 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
512 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000513 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
514 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000515 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000516
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000517 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000518 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000520 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000521 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000522 StructuredSubobjectInitIndex,
523 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000524 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000525 StructuredSubobjectInitList->setType(T);
526
Douglas Gregor5741efb2009-03-01 17:12:46 +0000527 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000528 // range corresponds with the end of the last initializer it used.
529 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000530 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000531 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
532 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Tanya Lattner5029d562010-03-07 04:17:15 +0000535 // Warn about missing braces.
536 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000537 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
538 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000539 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000541 "{")
542 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000544 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000545 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000546}
547
Anders Carlsson6cabf312010-01-23 23:23:01 +0000548void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000549 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550 unsigned &Index,
551 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 unsigned &StructuredIndex,
553 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000554 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000555 SyntacticToSemantic[IList] = StructuredList;
556 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000558 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000559 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
560 IList->setType(ExprTy);
561 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000562 if (hadError)
563 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000564
Eli Friedman85f54972008-05-25 13:22:35 +0000565 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000566 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000567 if (StructuredIndex == 1 &&
568 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000569 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000570 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000571 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000572 hadError = true;
573 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000574 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000575 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000576 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000577 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000578 // Don't complain for incomplete types, since we'll get an error
579 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000580 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000581 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 CurrentObjectType->isArrayType()? 0 :
583 CurrentObjectType->isVectorType()? 1 :
584 CurrentObjectType->isScalarType()? 2 :
585 CurrentObjectType->isUnionType()? 3 :
586 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000587
588 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000589 if (SemaRef.getLangOptions().CPlusPlus) {
590 DK = diag::err_excess_initializers;
591 hadError = true;
592 }
Nate Begeman425038c2009-07-07 21:53:06 +0000593 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
594 DK = diag::err_excess_initializers;
595 hadError = true;
596 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000597
Chris Lattnerb0912a52009-02-24 22:50:46 +0000598 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000599 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000600 }
601 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000602
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000603 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000604 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000605 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000606 << FixItHint::CreateRemoval(IList->getLocStart())
607 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000608}
609
Anders Carlsson6cabf312010-01-23 23:23:01 +0000610void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000611 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000612 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000613 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000614 unsigned &Index,
615 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000616 unsigned &StructuredIndex,
617 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000618 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000619 CheckScalarType(Entity, IList, DeclType, Index,
620 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000621 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000623 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000624 } else if (DeclType->isAggregateType()) {
625 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000626 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000627 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000628 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000629 StructuredList, StructuredIndex,
630 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000631 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000632 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000634 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000635 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000636 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000637 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000639 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000640 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
641 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000643 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000644 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000645 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000646 } else if (DeclType->isRecordType()) {
647 // C++ [dcl.init]p14:
648 // [...] If the class is an aggregate (8.5.1), and the initializer
649 // is a brace-enclosed list, see 8.5.1.
650 //
651 // Note: 8.5.1 is handled below; here, we diagnose the case where
652 // we have an initializer list and a destination type that is not
653 // an aggregate.
654 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000655 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000656 << DeclType << IList->getSourceRange();
657 hadError = true;
658 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000659 CheckReferenceType(Entity, IList, DeclType, Index,
660 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000661 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000662 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
663 << DeclType;
664 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000665 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000666 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
667 << DeclType;
668 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000669 }
670}
671
Anders Carlsson6cabf312010-01-23 23:23:01 +0000672void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000673 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000674 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000675 unsigned &Index,
676 InitListExpr *StructuredList,
677 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000678 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000679 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
680 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000681 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000682 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000683 = getStructuredSubobjectInit(IList, Index, ElemType,
684 StructuredList, StructuredIndex,
685 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000686 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000687 newStructuredList, newStructuredIndex);
688 ++StructuredIndex;
689 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000690 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000691 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000692 return CheckScalarType(Entity, IList, ElemType, Index,
693 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000695 return CheckReferenceType(Entity, IList, ElemType, Index,
696 StructuredList, StructuredIndex);
697 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000698
John McCall5decec92011-02-21 07:57:55 +0000699 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
700 // arrayType can be incomplete if we're initializing a flexible
701 // array member. There's nothing we can do with the completed
702 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000703
John McCall5decec92011-02-21 07:57:55 +0000704 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
705 CheckStringInit(Str, ElemType, arrayType, SemaRef);
706 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000707 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000708 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 }
John McCall5decec92011-02-21 07:57:55 +0000710
711 // Fall through for subaggregate initialization.
712
713 } else if (SemaRef.getLangOptions().CPlusPlus) {
714 // C++ [dcl.init.aggr]p12:
715 // All implicit type conversions (clause 4) are considered when
Rafael Espindola699fc4d2011-07-14 22:58:04 +0000716 // initializing the aggregate member with an ini- tializer from
John McCall5decec92011-02-21 07:57:55 +0000717 // an initializer-list. If the initializer can initialize a
718 // member, the member is initialized. [...]
719
720 // FIXME: Better EqualLoc?
721 InitializationKind Kind =
722 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
723 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
724
725 if (Seq) {
726 ExprResult Result =
727 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
728 if (Result.isInvalid())
729 hadError = true;
730
731 UpdateStructuredListElement(StructuredList, StructuredIndex,
732 Result.takeAs<Expr>());
733 ++Index;
734 return;
735 }
736
737 // Fall through for subaggregate initialization
738 } else {
739 // C99 6.7.8p13:
740 //
741 // The initializer for a structure or union object that has
742 // automatic storage duration shall be either an initializer
743 // list as described below, or a single expression that has
744 // compatible structure or union type. In the latter case, the
745 // initial value of the object, including unnamed members, is
746 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000747 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000748 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000749 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000750 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000751 if (ExprRes.isInvalid())
752 hadError = true;
753 else {
754 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
755 if (ExprRes.isInvalid())
756 hadError = true;
757 }
758 UpdateStructuredListElement(StructuredList, StructuredIndex,
759 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000760 ++Index;
761 return;
762 }
John Wiegley01296292011-04-08 18:41:53 +0000763 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000764 // Fall through for subaggregate initialization
765 }
766
767 // C++ [dcl.init.aggr]p12:
768 //
769 // [...] Otherwise, if the member is itself a non-empty
770 // subaggregate, brace elision is assumed and the initializer is
771 // considered for the initialization of the first member of
772 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000773 if (!SemaRef.getLangOptions().OpenCL &&
774 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000775 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
776 StructuredIndex);
777 ++StructuredIndex;
778 } else {
779 // We cannot initialize this element, so let
780 // PerformCopyInitialization produce the appropriate diagnostic.
781 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000782 SemaRef.Owned(expr),
783 /*TopLevelOfInitList=*/true);
John McCall5decec92011-02-21 07:57:55 +0000784 hadError = true;
785 ++Index;
786 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000787 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000788}
789
Anders Carlsson6cabf312010-01-23 23:23:01 +0000790void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000791 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000792 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000793 InitListExpr *StructuredList,
794 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000795 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000797 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000798 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000799 ++Index;
800 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000801 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000802 }
John McCall643169b2010-11-11 00:46:36 +0000803
804 Expr *expr = IList->getInit(Index);
805 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
806 SemaRef.Diag(SubIList->getLocStart(),
807 diag::warn_many_braces_around_scalar_init)
808 << SubIList->getSourceRange();
809
810 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
811 StructuredIndex);
812 return;
813 } else if (isa<DesignatedInitExpr>(expr)) {
814 SemaRef.Diag(expr->getSourceRange().getBegin(),
815 diag::err_designator_for_scalar_init)
816 << DeclType << expr->getSourceRange();
817 hadError = true;
818 ++Index;
819 ++StructuredIndex;
820 return;
821 }
822
823 ExprResult Result =
824 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000825 SemaRef.Owned(expr),
826 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000827
828 Expr *ResultExpr = 0;
829
830 if (Result.isInvalid())
831 hadError = true; // types weren't compatible.
832 else {
833 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
John McCall643169b2010-11-11 00:46:36 +0000835 if (ResultExpr != expr) {
836 // The type was promoted, update initializer list.
837 IList->setInit(Index, ResultExpr);
838 }
839 }
840 if (hadError)
841 ++StructuredIndex;
842 else
843 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
844 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000845}
846
Anders Carlsson6cabf312010-01-23 23:23:01 +0000847void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
848 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000849 unsigned &Index,
850 InitListExpr *StructuredList,
851 unsigned &StructuredIndex) {
852 if (Index < IList->getNumInits()) {
853 Expr *expr = IList->getInit(Index);
854 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000855 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000856 << DeclType << IList->getSourceRange();
857 hadError = true;
858 ++Index;
859 ++StructuredIndex;
860 return;
Mike Stump11289f42009-09-09 15:08:12 +0000861 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000862
John McCalldadc5752010-08-24 06:29:42 +0000863 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000864 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000865 SemaRef.Owned(expr),
866 /*TopLevelOfInitList=*/true);
Anders Carlssona91be642010-01-29 02:47:33 +0000867
868 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000869 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000870
871 expr = Result.takeAs<Expr>();
872 IList->setInit(Index, expr);
873
Douglas Gregord14247a2009-01-30 22:09:00 +0000874 if (hadError)
875 ++StructuredIndex;
876 else
877 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
878 ++Index;
879 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000880 // FIXME: It would be wonderful if we could point at the actual member. In
881 // general, it would be useful to pass location information down the stack,
882 // so that we know the location (or decl) of the "current object" being
883 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000884 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000885 diag::err_init_reference_member_uninitialized)
886 << DeclType
887 << IList->getSourceRange();
888 hadError = true;
889 ++Index;
890 ++StructuredIndex;
891 return;
892 }
893}
894
Anders Carlsson6cabf312010-01-23 23:23:01 +0000895void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000896 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000897 unsigned &Index,
898 InitListExpr *StructuredList,
899 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000900 if (Index >= IList->getNumInits())
901 return;
Mike Stump11289f42009-09-09 15:08:12 +0000902
John McCall6a16b2f2010-10-30 00:11:39 +0000903 const VectorType *VT = DeclType->getAs<VectorType>();
904 unsigned maxElements = VT->getNumElements();
905 unsigned numEltsInit = 0;
906 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000907
John McCall6a16b2f2010-10-30 00:11:39 +0000908 if (!SemaRef.getLangOptions().OpenCL) {
909 // If the initializing element is a vector, try to copy-initialize
910 // instead of breaking it apart (which is doomed to failure anyway).
911 Expr *Init = IList->getInit(Index);
912 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
913 ExprResult Result =
914 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000915 SemaRef.Owned(Init),
916 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +0000917
918 Expr *ResultExpr = 0;
919 if (Result.isInvalid())
920 hadError = true; // types weren't compatible.
921 else {
922 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
John McCall6a16b2f2010-10-30 00:11:39 +0000924 if (ResultExpr != Init) {
925 // The type was promoted, update initializer list.
926 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000927 }
928 }
John McCall6a16b2f2010-10-30 00:11:39 +0000929 if (hadError)
930 ++StructuredIndex;
931 else
932 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
933 ++Index;
934 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
John McCall6a16b2f2010-10-30 00:11:39 +0000937 InitializedEntity ElementEntity =
938 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
John McCall6a16b2f2010-10-30 00:11:39 +0000940 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
941 // Don't attempt to go past the end of the init list
942 if (Index >= IList->getNumInits())
943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944
John McCall6a16b2f2010-10-30 00:11:39 +0000945 ElementEntity.setElementIndex(Index);
946 CheckSubElementType(ElementEntity, IList, elementType, Index,
947 StructuredList, StructuredIndex);
948 }
949 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000950 }
John McCall6a16b2f2010-10-30 00:11:39 +0000951
952 InitializedEntity ElementEntity =
953 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954
John McCall6a16b2f2010-10-30 00:11:39 +0000955 // OpenCL initializers allows vectors to be constructed from vectors.
956 for (unsigned i = 0; i < maxElements; ++i) {
957 // Don't attempt to go past the end of the init list
958 if (Index >= IList->getNumInits())
959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
John McCall6a16b2f2010-10-30 00:11:39 +0000961 ElementEntity.setElementIndex(Index);
962
963 QualType IType = IList->getInit(Index)->getType();
964 if (!IType->isVectorType()) {
965 CheckSubElementType(ElementEntity, IList, elementType, Index,
966 StructuredList, StructuredIndex);
967 ++numEltsInit;
968 } else {
969 QualType VecType;
970 const VectorType *IVT = IType->getAs<VectorType>();
971 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
John McCall6a16b2f2010-10-30 00:11:39 +0000973 if (IType->isExtVectorType())
974 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
975 else
976 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000977 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000978 CheckSubElementType(ElementEntity, IList, VecType, Index,
979 StructuredList, StructuredIndex);
980 numEltsInit += numIElts;
981 }
982 }
983
984 // OpenCL requires all elements to be initialized.
985 if (numEltsInit != maxElements)
986 if (SemaRef.getLangOptions().OpenCL)
987 SemaRef.Diag(IList->getSourceRange().getBegin(),
988 diag::err_vector_incorrect_num_initializers)
989 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000990}
991
Anders Carlsson6cabf312010-01-23 23:23:01 +0000992void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000993 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000994 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000995 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000996 unsigned &Index,
997 InitListExpr *StructuredList,
998 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000999 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1000
Steve Narofff8ecff22008-05-01 22:18:59 +00001001 // Check for the special-case of initializing an array with a string.
1002 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001003 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001004 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +00001005 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001006 // We place the string literal directly into the resulting
1007 // initializer list. This is the only place where the structure
1008 // of the structured initializer list doesn't match exactly,
1009 // because doing so would involve allocating one character
1010 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001011 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001012 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001013 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001014 return;
1015 }
1016 }
John McCall66884dd2011-02-21 07:22:22 +00001017 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001018 // Check for VLAs; in standard C it would be possible to check this
1019 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1020 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001021 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001022 diag::err_variable_object_no_init)
1023 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001024 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001025 ++Index;
1026 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001027 return;
1028 }
1029
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001030 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1032 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001033 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001034 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001035 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001036 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001037 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001038 maxElementsKnown = true;
1039 }
1040
John McCall66884dd2011-02-21 07:22:22 +00001041 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001042 while (Index < IList->getNumInits()) {
1043 Expr *Init = IList->getInit(Index);
1044 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001045 // If we're not the subobject that matches up with the '{' for
1046 // the designator, we shouldn't be handling the
1047 // designator. Return immediately.
1048 if (!SubobjectIsDesignatorContext)
1049 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001050
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001051 // Handle this designated initializer. elementIndex will be
1052 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001053 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001054 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001055 StructuredList, StructuredIndex, true,
1056 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001057 hadError = true;
1058 continue;
1059 }
1060
Douglas Gregor033d1252009-01-23 16:54:12 +00001061 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001062 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001063 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001064 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001065 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001066
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001067 // If the array is of incomplete type, keep track of the number of
1068 // elements in the initializer.
1069 if (!maxElementsKnown && elementIndex > maxElements)
1070 maxElements = elementIndex;
1071
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001072 continue;
1073 }
1074
1075 // If we know the maximum number of elements, and we've already
1076 // hit it, stop consuming elements in the initializer list.
1077 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001078 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001079
Anders Carlsson6cabf312010-01-23 23:23:01 +00001080 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001082 Entity);
1083 // Check this element.
1084 CheckSubElementType(ElementEntity, IList, elementType, Index,
1085 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001086 ++elementIndex;
1087
1088 // If the array is of incomplete type, keep track of the number of
1089 // elements in the initializer.
1090 if (!maxElementsKnown && elementIndex > maxElements)
1091 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001092 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001093 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001094 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001095 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001096 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001097 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001098 // Sizing an array implicitly to zero is not allowed by ISO C,
1099 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001100 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001101 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001102 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001103
Mike Stump11289f42009-09-09 15:08:12 +00001104 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001105 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001106 }
1107}
1108
Anders Carlsson6cabf312010-01-23 23:23:01 +00001109void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001110 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001111 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001112 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001113 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001114 unsigned &Index,
1115 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001116 unsigned &StructuredIndex,
1117 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001118 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001119
Eli Friedman23a9e312008-05-19 19:16:24 +00001120 // If the record is invalid, some of it's members are invalid. To avoid
1121 // confusion, we forgo checking the intializer for the entire record.
1122 if (structDecl->isInvalidDecl()) {
1123 hadError = true;
1124 return;
Mike Stump11289f42009-09-09 15:08:12 +00001125 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001126
1127 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1128 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001129 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001130 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001131 Field != FieldEnd; ++Field) {
1132 if (Field->getDeclName()) {
1133 StructuredList->setInitializedFieldInUnion(*Field);
1134 break;
1135 }
1136 }
1137 return;
1138 }
1139
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001140 // If structDecl is a forward declaration, this loop won't do
1141 // anything except look at designated initializers; That's okay,
1142 // because an error should get printed out elsewhere. It might be
1143 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001144 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001145 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001146 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001147 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001148 while (Index < IList->getNumInits()) {
1149 Expr *Init = IList->getInit(Index);
1150
1151 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001152 // If we're not the subobject that matches up with the '{' for
1153 // the designator, we shouldn't be handling the
1154 // designator. Return immediately.
1155 if (!SubobjectIsDesignatorContext)
1156 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001157
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001158 // Handle this designated initializer. Field will be updated to
1159 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001160 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001161 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001162 StructuredList, StructuredIndex,
1163 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001164 hadError = true;
1165
Douglas Gregora9add4e2009-02-12 19:00:39 +00001166 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001167
1168 // Disable check for missing fields when designators are used.
1169 // This matches gcc behaviour.
1170 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001171 continue;
1172 }
1173
1174 if (Field == FieldEnd) {
1175 // We've run out of fields. We're done.
1176 break;
1177 }
1178
Douglas Gregora9add4e2009-02-12 19:00:39 +00001179 // We've already initialized a member of a union. We're done.
1180 if (InitializedSomething && DeclType->isUnionType())
1181 break;
1182
Douglas Gregor91f84212008-12-11 16:49:14 +00001183 // If we've hit the flexible array member at the end, we're done.
1184 if (Field->getType()->isIncompleteArrayType())
1185 break;
1186
Douglas Gregor51695702009-01-29 16:53:55 +00001187 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001188 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001189 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001190 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001191 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001192
Douglas Gregora82064c2011-06-29 21:51:31 +00001193 // Make sure we can use this declaration.
1194 if (SemaRef.DiagnoseUseOfDecl(*Field,
1195 IList->getInit(Index)->getLocStart())) {
1196 ++Index;
1197 ++Field;
1198 hadError = true;
1199 continue;
1200 }
1201
Anders Carlsson6cabf312010-01-23 23:23:01 +00001202 InitializedEntity MemberEntity =
1203 InitializedEntity::InitializeMember(*Field, &Entity);
1204 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1205 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001206 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001207
1208 if (DeclType->isUnionType()) {
1209 // Initialize the first field within the union.
1210 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001211 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001212
1213 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001214 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001215
John McCalle40b58e2010-03-11 19:32:38 +00001216 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001218 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1219 // It is possible we have one or more unnamed bitfields remaining.
1220 // Find first (if any) named field and emit warning.
1221 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1222 it != end; ++it) {
1223 if (!it->isUnnamedBitfield()) {
1224 SemaRef.Diag(IList->getSourceRange().getEnd(),
1225 diag::warn_missing_field_initializers) << it->getName();
1226 break;
1227 }
1228 }
1229 }
1230
Mike Stump11289f42009-09-09 15:08:12 +00001231 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001232 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001233 return;
1234
1235 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001236 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001237 (!isa<InitListExpr>(IList->getInit(Index)) ||
1238 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001239 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001240 diag::err_flexible_array_init_nonempty)
1241 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001242 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001243 << *Field;
1244 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001245 ++Index;
1246 return;
1247 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001248 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001249 diag::ext_flexible_array_init)
1250 << IList->getInit(Index)->getSourceRange().getBegin();
1251 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1252 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001253 }
1254
Anders Carlsson6cabf312010-01-23 23:23:01 +00001255 InitializedEntity MemberEntity =
1256 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257
Anders Carlsson6cabf312010-01-23 23:23:01 +00001258 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001260 StructuredList, StructuredIndex);
1261 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001263 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001264}
Steve Narofff8ecff22008-05-01 22:18:59 +00001265
Douglas Gregord5846a12009-04-15 06:41:24 +00001266/// \brief Expand a field designator that refers to a member of an
1267/// anonymous struct or union into a series of field designators that
1268/// refers to the field within the appropriate subobject.
1269///
Douglas Gregord5846a12009-04-15 06:41:24 +00001270static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001271 DesignatedInitExpr *DIE,
1272 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001273 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001274 typedef DesignatedInitExpr::Designator Designator;
1275
Douglas Gregord5846a12009-04-15 06:41:24 +00001276 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001277 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001278 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1279 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1280 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001281 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001282 DIE->getDesignator(DesigIdx)->getDotLoc(),
1283 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1284 else
1285 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1286 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001287 assert(isa<FieldDecl>(*PI));
1288 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001289 }
1290
1291 // Expand the current designator into the set of replacement
1292 // designators, so we have a full subobject path down to where the
1293 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001294 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001295 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001296}
Mike Stump11289f42009-09-09 15:08:12 +00001297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001299/// corresponds to FieldName.
1300static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1301 IdentifierInfo *FieldName) {
1302 assert(AnonField->isAnonymousStructOrUnion());
1303 Decl *NextDecl = AnonField->getNextDeclInContext();
1304 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1305 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1306 return IF;
1307 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001308 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001309 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001310}
1311
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001312/// @brief Check the well-formedness of a C99 designated initializer.
1313///
1314/// Determines whether the designated initializer @p DIE, which
1315/// resides at the given @p Index within the initializer list @p
1316/// IList, is well-formed for a current object of type @p DeclType
1317/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001318/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001319/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001320///
1321/// @param IList The initializer list in which this designated
1322/// initializer occurs.
1323///
Douglas Gregora5324162009-04-15 04:56:10 +00001324/// @param DIE The designated initializer expression.
1325///
1326/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001327///
1328/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1329/// into which the designation in @p DIE should refer.
1330///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001331/// @param NextField If non-NULL and the first designator in @p DIE is
1332/// a field, this will be set to the field declaration corresponding
1333/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001334///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001335/// @param NextElementIndex If non-NULL and the first designator in @p
1336/// DIE is an array designator or GNU array-range designator, this
1337/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001338///
1339/// @param Index Index into @p IList where the designated initializer
1340/// @p DIE occurs.
1341///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001342/// @param StructuredList The initializer list expression that
1343/// describes all of the subobject initializers in the order they'll
1344/// actually be initialized.
1345///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001347bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001348InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001349 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001350 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001351 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001352 QualType &CurrentObjectType,
1353 RecordDecl::field_iterator *NextField,
1354 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001355 unsigned &Index,
1356 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001357 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001358 bool FinishSubobjectInit,
1359 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001360 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001361 // Check the actual initialization for the designated object type.
1362 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001363
1364 // Temporarily remove the designator expression from the
1365 // initializer list that the child calls see, so that we don't try
1366 // to re-process the designator.
1367 unsigned OldIndex = Index;
1368 IList->setInit(OldIndex, DIE->getInit());
1369
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001370 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001371 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001372
1373 // Restore the designated initializer expression in the syntactic
1374 // form of the initializer list.
1375 if (IList->getInit(OldIndex) != DIE->getInit())
1376 DIE->setInit(IList->getInit(OldIndex));
1377 IList->setInit(OldIndex, DIE);
1378
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001379 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001380 }
1381
Douglas Gregora5324162009-04-15 04:56:10 +00001382 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001383 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 "Need a non-designated initializer list to start from");
1385
Douglas Gregora5324162009-04-15 04:56:10 +00001386 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 // Determine the structural initializer list that corresponds to the
1388 // current subobject.
1389 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001390 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001391 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 SourceRange(D->getStartLocation(),
1393 DIE->getSourceRange().getEnd()));
1394 assert(StructuredList && "Expected a structured initializer list");
1395
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001396 if (D->isFieldDesignator()) {
1397 // C99 6.7.8p7:
1398 //
1399 // If a designator has the form
1400 //
1401 // . identifier
1402 //
1403 // then the current object (defined below) shall have
1404 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001405 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001406 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001407 if (!RT) {
1408 SourceLocation Loc = D->getDotLoc();
1409 if (Loc.isInvalid())
1410 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001411 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1412 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001413 ++Index;
1414 return true;
1415 }
1416
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001417 // Note: we perform a linear search of the fields here, despite
1418 // the fact that we have a faster lookup method, because we always
1419 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001420 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001421 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001422 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001423 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001424 Field = RT->getDecl()->field_begin(),
1425 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001426 for (; Field != FieldEnd; ++Field) {
1427 if (Field->isUnnamedBitfield())
1428 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001429
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001430 // If we find a field representing an anonymous field, look in the
1431 // IndirectFieldDecl that follow for the designated initializer.
1432 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1433 if (IndirectFieldDecl *IF =
1434 FindIndirectFieldDesignator(*Field, FieldName)) {
1435 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1436 D = DIE->getDesignator(DesigIdx);
1437 break;
1438 }
1439 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001440 if (KnownField && KnownField == *Field)
1441 break;
1442 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001443 break;
1444
1445 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001446 }
1447
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001448 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001449 // There was no normal field in the struct with the designated
1450 // name. Perform another lookup for this name, which may find
1451 // something that we can't designate (e.g., a member function),
1452 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001453 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001454 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001455 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001456 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001457 // Name lookup didn't find anything. Determine whether this
1458 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001460 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001461 TypoCorrection Corrected = SemaRef.CorrectTypo(
1462 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1463 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1464 RT->getDecl(), false, Sema::CTC_NoKeywords);
1465 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001466 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001467 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001468 std::string CorrectedStr(
1469 Corrected.getAsString(SemaRef.getLangOptions()));
1470 std::string CorrectedQuotedStr(
1471 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001473 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001474 << FieldName << CurrentObjectType << CorrectedQuotedStr
1475 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001477 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001478 } else {
1479 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1480 << FieldName << CurrentObjectType;
1481 ++Index;
1482 return true;
1483 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001486 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001487 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001488 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001489 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001490 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001491 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001492 ++Index;
1493 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001494 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001495
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001496 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001497 // The replacement field comes from typo correction; find it
1498 // in the list of fields.
1499 FieldIndex = 0;
1500 Field = RT->getDecl()->field_begin();
1501 for (; Field != FieldEnd; ++Field) {
1502 if (Field->isUnnamedBitfield())
1503 continue;
1504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001506 Field->getIdentifier() == ReplacementField->getIdentifier())
1507 break;
1508
1509 ++FieldIndex;
1510 }
1511 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001512 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001513
1514 // All of the fields of a union are located at the same place in
1515 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001516 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001517 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001518 StructuredList->setInitializedFieldInUnion(*Field);
1519 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001520
Douglas Gregora82064c2011-06-29 21:51:31 +00001521 // Make sure we can use this declaration.
1522 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1523 ++Index;
1524 return true;
1525 }
1526
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001528 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001529
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001530 // Make sure that our non-designated initializer list has space
1531 // for a subobject corresponding to this field.
1532 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001533 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001534
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001535 // This designator names a flexible array member.
1536 if (Field->getType()->isIncompleteArrayType()) {
1537 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001538 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001539 // We can't designate an object within the flexible array
1540 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001541 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001542 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001543 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001544 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001545 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001546 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001547 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001548 << *Field;
1549 Invalid = true;
1550 }
1551
Chris Lattner001b29c2010-10-10 17:49:49 +00001552 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1553 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001554 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001555 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001556 diag::err_flexible_array_init_needs_braces)
1557 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001558 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001559 << *Field;
1560 Invalid = true;
1561 }
1562
1563 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001564 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001565 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001566 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001567 diag::err_flexible_array_init_nonempty)
1568 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001569 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001570 << *Field;
1571 Invalid = true;
1572 }
1573
1574 if (Invalid) {
1575 ++Index;
1576 return true;
1577 }
1578
1579 // Initialize the array.
1580 bool prevHadError = hadError;
1581 unsigned newStructuredIndex = FieldIndex;
1582 unsigned OldIndex = Index;
1583 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001584
1585 InitializedEntity MemberEntity =
1586 InitializedEntity::InitializeMember(*Field, &Entity);
1587 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001588 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001589
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001590 IList->setInit(OldIndex, DIE);
1591 if (hadError && !prevHadError) {
1592 ++Field;
1593 ++FieldIndex;
1594 if (NextField)
1595 *NextField = Field;
1596 StructuredIndex = FieldIndex;
1597 return true;
1598 }
1599 } else {
1600 // Recurse to check later designated subobjects.
1601 QualType FieldType = (*Field)->getType();
1602 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001604 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001605 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1607 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001608 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001609 true, false))
1610 return true;
1611 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612
1613 // Find the position of the next field to be initialized in this
1614 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001615 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617
1618 // If this the first designator, our caller will continue checking
1619 // the rest of this struct/class/union subobject.
1620 if (IsFirstDesignator) {
1621 if (NextField)
1622 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001624 return false;
1625 }
1626
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627 if (!FinishSubobjectInit)
1628 return false;
1629
Douglas Gregord5846a12009-04-15 06:41:24 +00001630 // We've already initialized something in the union; we're done.
1631 if (RT->getDecl()->isUnion())
1632 return hadError;
1633
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001634 // Check the remaining fields within this class/struct/union subobject.
1635 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636
Anders Carlsson6cabf312010-01-23 23:23:01 +00001637 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001638 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001639 return hadError && !prevHadError;
1640 }
1641
1642 // C99 6.7.8p6:
1643 //
1644 // If a designator has the form
1645 //
1646 // [ constant-expression ]
1647 //
1648 // then the current object (defined below) shall have array
1649 // type and the expression shall be an integer constant
1650 // expression. If the array is of unknown size, any
1651 // nonnegative value is valid.
1652 //
1653 // Additionally, cope with the GNU extension that permits
1654 // designators of the form
1655 //
1656 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001657 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001659 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001660 << CurrentObjectType;
1661 ++Index;
1662 return true;
1663 }
1664
1665 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1667 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001668 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001669 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001670 DesignatedEndIndex = DesignatedStartIndex;
1671 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673
Mike Stump11289f42009-09-09 15:08:12 +00001674 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001675 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001676 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001677 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001678 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001679
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001680 // Codegen can't handle evaluating array range designators that have side
1681 // effects, because we replicate the AST value for each initialized element.
1682 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1683 // elements with something that has a side effect, so codegen can emit an
1684 // "error unsupported" error instead of miscompiling the app.
1685 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1686 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001687 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001688 }
1689
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001690 if (isa<ConstantArrayType>(AT)) {
1691 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001692 DesignatedStartIndex
1693 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001694 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001695 DesignatedEndIndex
1696 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001697 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1698 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001699 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001700 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001701 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001702 << IndexExpr->getSourceRange();
1703 ++Index;
1704 return true;
1705 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001706 } else {
1707 // Make sure the bit-widths and signedness match.
1708 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001709 DesignatedEndIndex
1710 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001711 else if (DesignatedStartIndex.getBitWidth() <
1712 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001713 DesignatedStartIndex
1714 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001715 DesignatedStartIndex.setIsUnsigned(true);
1716 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719 // Make sure that our non-designated initializer list has space
1720 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001721 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001722 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001723 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001724
Douglas Gregor17bd0942009-01-28 23:36:17 +00001725 // Repeatedly perform subobject initializations in the range
1726 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001727
Douglas Gregor17bd0942009-01-28 23:36:17 +00001728 // Move to the next designator
1729 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1730 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001732 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001733 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001734
Douglas Gregor17bd0942009-01-28 23:36:17 +00001735 while (DesignatedStartIndex <= DesignatedEndIndex) {
1736 // Recurse to check later designated subobjects.
1737 QualType ElementType = AT->getElementType();
1738 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001740 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1742 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001743 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001744 (DesignatedStartIndex == DesignatedEndIndex),
1745 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001746 return true;
1747
1748 // Move to the next index in the array that we'll be initializing.
1749 ++DesignatedStartIndex;
1750 ElementIndex = DesignatedStartIndex.getZExtValue();
1751 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001752
1753 // If this the first designator, our caller will continue checking
1754 // the rest of this array subobject.
1755 if (IsFirstDesignator) {
1756 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001757 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001758 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001759 return false;
1760 }
Mike Stump11289f42009-09-09 15:08:12 +00001761
Douglas Gregor17bd0942009-01-28 23:36:17 +00001762 if (!FinishSubobjectInit)
1763 return false;
1764
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001765 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001766 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001768 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001770 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771}
1772
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773// Get the structured initializer list for a subobject of type
1774// @p CurrentObjectType.
1775InitListExpr *
1776InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1777 QualType CurrentObjectType,
1778 InitListExpr *StructuredList,
1779 unsigned StructuredIndex,
1780 SourceRange InitRange) {
1781 Expr *ExistingInit = 0;
1782 if (!StructuredList)
1783 ExistingInit = SyntacticToSemantic[IList];
1784 else if (StructuredIndex < StructuredList->getNumInits())
1785 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001787 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1788 return Result;
1789
1790 if (ExistingInit) {
1791 // We are creating an initializer list that initializes the
1792 // subobjects of the current object, but there was already an
1793 // initialization that completely initialized the current
1794 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001795 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001796 // struct X { int a, b; };
1797 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001798 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001799 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1800 // designated initializer re-initializes the whole
1801 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001802 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001803 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001804 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001805 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001806 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001807 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001808 << ExistingInit->getSourceRange();
1809 }
1810
Mike Stump11289f42009-09-09 15:08:12 +00001811 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001812 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1813 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001814 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001815
Douglas Gregora8a089b2010-07-13 18:40:04 +00001816 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001817
Douglas Gregor6d00c992009-03-20 23:58:33 +00001818 // Pre-allocate storage for the structured initializer list.
1819 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001820 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001821 bool GotNumInits = false;
1822 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001823 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001824 GotNumInits = true;
1825 } else if (Index < IList->getNumInits()) {
1826 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001827 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001828 GotNumInits = true;
1829 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001830 }
1831
Mike Stump11289f42009-09-09 15:08:12 +00001832 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001833 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1834 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1835 NumElements = CAType->getSize().getZExtValue();
1836 // Simple heuristic so that we don't allocate a very large
1837 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001838 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001839 NumElements = 0;
1840 }
John McCall9dd450b2009-09-21 23:43:11 +00001841 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001842 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001844 RecordDecl *RDecl = RType->getDecl();
1845 if (RDecl->isUnion())
1846 NumElements = 1;
1847 else
Mike Stump11289f42009-09-09 15:08:12 +00001848 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001849 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001850 }
1851
Douglas Gregor221c9a52009-03-21 18:13:52 +00001852 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001853 NumElements = IList->getNumInits();
1854
Ted Kremenekac034612010-04-13 23:39:13 +00001855 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001856
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001857 // Link this new initializer list into the structured initializer
1858 // lists.
1859 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001860 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001861 else {
1862 Result->setSyntacticForm(IList);
1863 SyntacticToSemantic[IList] = Result;
1864 }
1865
1866 return Result;
1867}
1868
1869/// Update the initializer at index @p StructuredIndex within the
1870/// structured initializer list to the value @p expr.
1871void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1872 unsigned &StructuredIndex,
1873 Expr *expr) {
1874 // No structured initializer list to update
1875 if (!StructuredList)
1876 return;
1877
Ted Kremenekac034612010-04-13 23:39:13 +00001878 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1879 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001880 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001881 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001882 diag::warn_initializer_overrides)
1883 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001884 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001885 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001886 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001887 << PrevInit->getSourceRange();
1888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001890 ++StructuredIndex;
1891}
1892
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001893/// Check that the given Index expression is a valid array designator
1894/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001895/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001896/// and produces a reasonable diagnostic if there is a
1897/// failure. Returns true if there was an error, false otherwise. If
1898/// everything went okay, Value will receive the value of the constant
1899/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001900static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001901CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001902 SourceLocation Loc = Index->getSourceRange().getBegin();
1903
1904 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001905 if (S.VerifyIntegerConstantExpression(Index, &Value))
1906 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001907
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001908 if (Value.isSigned() && Value.isNegative())
1909 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001910 << Value.toString(10) << Index->getSourceRange();
1911
Douglas Gregor51650d32009-01-23 21:04:18 +00001912 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001913 return false;
1914}
1915
John McCalldadc5752010-08-24 06:29:42 +00001916ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001917 SourceLocation Loc,
1918 bool GNUSyntax,
1919 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001920 typedef DesignatedInitExpr::Designator ASTDesignator;
1921
1922 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001923 SmallVector<ASTDesignator, 32> Designators;
1924 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001925
1926 // Build designators and check array designator expressions.
1927 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1928 const Designator &D = Desig.getDesignator(Idx);
1929 switch (D.getKind()) {
1930 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001931 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001932 D.getFieldLoc()));
1933 break;
1934
1935 case Designator::ArrayDesignator: {
1936 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1937 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001938 if (!Index->isTypeDependent() &&
1939 !Index->isValueDependent() &&
1940 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001941 Invalid = true;
1942 else {
1943 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001944 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001945 D.getRBracketLoc()));
1946 InitExpressions.push_back(Index);
1947 }
1948 break;
1949 }
1950
1951 case Designator::ArrayRangeDesignator: {
1952 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1953 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1954 llvm::APSInt StartValue;
1955 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001956 bool StartDependent = StartIndex->isTypeDependent() ||
1957 StartIndex->isValueDependent();
1958 bool EndDependent = EndIndex->isTypeDependent() ||
1959 EndIndex->isValueDependent();
1960 if ((!StartDependent &&
1961 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1962 (!EndDependent &&
1963 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001964 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001965 else {
1966 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001967 if (StartDependent || EndDependent) {
1968 // Nothing to compute.
1969 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001970 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001971 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001972 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001973
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001974 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001975 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001976 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001977 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1978 Invalid = true;
1979 } else {
1980 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001981 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001982 D.getEllipsisLoc(),
1983 D.getRBracketLoc()));
1984 InitExpressions.push_back(StartIndex);
1985 InitExpressions.push_back(EndIndex);
1986 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001987 }
1988 break;
1989 }
1990 }
1991 }
1992
1993 if (Invalid || Init.isInvalid())
1994 return ExprError();
1995
1996 // Clear out the expressions within the designation.
1997 Desig.ClearExprs(*this);
1998
1999 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002000 = DesignatedInitExpr::Create(Context,
2001 Designators.data(), Designators.size(),
2002 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002003 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Douglas Gregorc124e592011-01-16 16:13:16 +00002005 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002006 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2007 << DIE->getSourceRange();
2008 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002009 Diag(DIE->getLocStart(), diag::ext_designated_init)
2010 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002012 return Owned(DIE);
2013}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002014
Douglas Gregor723796a2009-12-16 06:35:08 +00002015bool Sema::CheckInitList(const InitializedEntity &Entity,
2016 InitListExpr *&InitList, QualType &DeclType) {
2017 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002018 if (!CheckInitList.HadError())
2019 InitList = CheckInitList.getFullyStructuredList();
2020
2021 return CheckInitList.HadError();
2022}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002023
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002024//===----------------------------------------------------------------------===//
2025// Initialization entity
2026//===----------------------------------------------------------------------===//
2027
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002029 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002031{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002032 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2033 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002034 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002035 } else {
2036 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002037 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002038 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002039}
2040
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002041InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002042 CXXBaseSpecifier *Base,
2043 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002044{
2045 InitializedEntity Result;
2046 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002047 Result.Base = reinterpret_cast<uintptr_t>(Base);
2048 if (IsInheritedVirtualBase)
2049 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050
Douglas Gregor1b303932009-12-22 15:35:07 +00002051 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002052 return Result;
2053}
2054
Douglas Gregor85dabae2009-12-16 01:38:02 +00002055DeclarationName InitializedEntity::getName() const {
2056 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002057 case EK_Parameter: {
2058 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2059 return (D ? D->getDeclName() : DeclarationName());
2060 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002061
2062 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002063 case EK_Member:
2064 return VariableOrMember->getDeclName();
2065
2066 case EK_Result:
2067 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002068 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002069 case EK_Temporary:
2070 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002071 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002072 case EK_ArrayElement:
2073 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002074 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002075 return DeclarationName();
2076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Douglas Gregor85dabae2009-12-16 01:38:02 +00002078 // Silence GCC warning
2079 return DeclarationName();
2080}
2081
Douglas Gregora4b592a2009-12-19 03:01:41 +00002082DeclaratorDecl *InitializedEntity::getDecl() const {
2083 switch (getKind()) {
2084 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002085 case EK_Member:
2086 return VariableOrMember;
2087
John McCall31168b02011-06-15 23:02:42 +00002088 case EK_Parameter:
2089 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2090
Douglas Gregora4b592a2009-12-19 03:01:41 +00002091 case EK_Result:
2092 case EK_Exception:
2093 case EK_New:
2094 case EK_Temporary:
2095 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002096 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002097 case EK_ArrayElement:
2098 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002099 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002100 return 0;
2101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
Douglas Gregora4b592a2009-12-19 03:01:41 +00002103 // Silence GCC warning
2104 return 0;
2105}
2106
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002107bool InitializedEntity::allowsNRVO() const {
2108 switch (getKind()) {
2109 case EK_Result:
2110 case EK_Exception:
2111 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002113 case EK_Variable:
2114 case EK_Parameter:
2115 case EK_Member:
2116 case EK_New:
2117 case EK_Temporary:
2118 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002119 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002120 case EK_ArrayElement:
2121 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002122 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002123 break;
2124 }
2125
2126 return false;
2127}
2128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129//===----------------------------------------------------------------------===//
2130// Initialization sequence
2131//===----------------------------------------------------------------------===//
2132
2133void InitializationSequence::Step::Destroy() {
2134 switch (Kind) {
2135 case SK_ResolveAddressOfOverloadedFunction:
2136 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002137 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 case SK_CastDerivedToBaseLValue:
2139 case SK_BindReference:
2140 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002141 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002142 case SK_UserConversion:
2143 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002144 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002146 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002147 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002148 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002149 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002150 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002151 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002152 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002153 case SK_PassByIndirectCopyRestore:
2154 case SK_PassByIndirectRestore:
2155 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002156 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002158 case SK_ConversionSequence:
2159 delete ICS;
2160 }
2161}
2162
Douglas Gregor838fcc32010-03-26 20:14:36 +00002163bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002164 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002165}
2166
2167bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002168 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002169 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Douglas Gregor838fcc32010-03-26 20:14:36 +00002171 switch (getFailureKind()) {
2172 case FK_TooManyInitsForReference:
2173 case FK_ArrayNeedsInitList:
2174 case FK_ArrayNeedsInitListOrStringLiteral:
2175 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2176 case FK_NonConstLValueReferenceBindingToTemporary:
2177 case FK_NonConstLValueReferenceBindingToUnrelated:
2178 case FK_RValueReferenceBindingToLValue:
2179 case FK_ReferenceInitDropsQualifiers:
2180 case FK_ReferenceInitFailed:
2181 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002182 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002183 case FK_TooManyInitsForScalar:
2184 case FK_ReferenceBindingToInitList:
2185 case FK_InitListBadDestinationType:
2186 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002187 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002188 case FK_ArrayTypeMismatch:
2189 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002190 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002191
Douglas Gregor838fcc32010-03-26 20:14:36 +00002192 case FK_ReferenceInitOverloadFailed:
2193 case FK_UserConversionOverloadFailed:
2194 case FK_ConstructorOverloadFailed:
2195 return FailedOverloadResult == OR_Ambiguous;
2196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Douglas Gregor838fcc32010-03-26 20:14:36 +00002198 return false;
2199}
2200
Douglas Gregorb33eed02010-04-16 22:09:46 +00002201bool InitializationSequence::isConstructorInitialization() const {
2202 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2203}
2204
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002205bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2206 const Expr *Initializer,
2207 bool *isInitializerConstant,
2208 APValue *ConstantValue) const {
2209 if (Steps.empty() || Initializer->isValueDependent())
2210 return false;
2211
2212 const Step &LastStep = Steps.back();
2213 if (LastStep.Kind != SK_ConversionSequence)
2214 return false;
2215
2216 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2217 const StandardConversionSequence *SCS = NULL;
2218 switch (ICS.getKind()) {
2219 case ImplicitConversionSequence::StandardConversion:
2220 SCS = &ICS.Standard;
2221 break;
2222 case ImplicitConversionSequence::UserDefinedConversion:
2223 SCS = &ICS.UserDefined.After;
2224 break;
2225 case ImplicitConversionSequence::AmbiguousConversion:
2226 case ImplicitConversionSequence::EllipsisConversion:
2227 case ImplicitConversionSequence::BadConversion:
2228 return false;
2229 }
2230
2231 // Check if SCS represents a narrowing conversion, according to C++0x
2232 // [dcl.init.list]p7:
2233 //
2234 // A narrowing conversion is an implicit conversion ...
2235 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2236 QualType FromType = SCS->getToType(0);
2237 QualType ToType = SCS->getToType(1);
2238 switch (PossibleNarrowing) {
2239 // * from a floating-point type to an integer type, or
2240 //
2241 // * from an integer type or unscoped enumeration type to a floating-point
2242 // type, except where the source is a constant expression and the actual
2243 // value after conversion will fit into the target type and will produce
2244 // the original value when converted back to the original type, or
2245 case ICK_Floating_Integral:
2246 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2247 *isInitializerConstant = false;
2248 return true;
2249 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2250 llvm::APSInt IntConstantValue;
2251 if (Initializer &&
2252 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2253 // Convert the integer to the floating type.
2254 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2255 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2256 llvm::APFloat::rmNearestTiesToEven);
2257 // And back.
2258 llvm::APSInt ConvertedValue = IntConstantValue;
2259 bool ignored;
2260 Result.convertToInteger(ConvertedValue,
2261 llvm::APFloat::rmTowardZero, &ignored);
2262 // If the resulting value is different, this was a narrowing conversion.
2263 if (IntConstantValue != ConvertedValue) {
2264 *isInitializerConstant = true;
2265 *ConstantValue = APValue(IntConstantValue);
2266 return true;
2267 }
2268 } else {
2269 // Variables are always narrowings.
2270 *isInitializerConstant = false;
2271 return true;
2272 }
2273 }
2274 return false;
2275
2276 // * from long double to double or float, or from double to float, except
2277 // where the source is a constant expression and the actual value after
2278 // conversion is within the range of values that can be represented (even
2279 // if it cannot be represented exactly), or
2280 case ICK_Floating_Conversion:
2281 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2282 // FromType is larger than ToType.
2283 Expr::EvalResult InitializerValue;
2284 // FIXME: Check whether Initializer is a constant expression according
2285 // to C++0x [expr.const], rather than just whether it can be folded.
2286 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2287 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2288 // Constant! (Except for FIXME above.)
2289 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2290 // Convert the source value into the target type.
2291 bool ignored;
2292 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2293 Ctx.getFloatTypeSemantics(ToType),
2294 llvm::APFloat::rmNearestTiesToEven, &ignored);
2295 // If there was no overflow, the source value is within the range of
2296 // values that can be represented.
2297 if (ConvertStatus & llvm::APFloat::opOverflow) {
2298 *isInitializerConstant = true;
2299 *ConstantValue = InitializerValue.Val;
2300 return true;
2301 }
2302 } else {
2303 *isInitializerConstant = false;
2304 return true;
2305 }
2306 }
2307 return false;
2308
2309 // * from an integer type or unscoped enumeration type to an integer type
2310 // that cannot represent all the values of the original type, except where
2311 // the source is a constant expression and the actual value after
2312 // conversion will fit into the target type and will produce the original
2313 // value when converted back to the original type.
2314 case ICK_Integral_Conversion: {
2315 assert(FromType->isIntegralOrUnscopedEnumerationType());
2316 assert(ToType->isIntegralOrUnscopedEnumerationType());
2317 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2318 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2319 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2320 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2321
2322 if (FromWidth > ToWidth ||
2323 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2324 // Not all values of FromType can be represented in ToType.
2325 llvm::APSInt InitializerValue;
2326 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2327 *isInitializerConstant = true;
2328 *ConstantValue = APValue(InitializerValue);
2329
2330 // Add a bit to the InitializerValue so we don't have to worry about
2331 // signed vs. unsigned comparisons.
2332 InitializerValue = InitializerValue.extend(
2333 InitializerValue.getBitWidth() + 1);
2334 // Convert the initializer to and from the target width and signed-ness.
2335 llvm::APSInt ConvertedValue = InitializerValue;
2336 ConvertedValue = ConvertedValue.trunc(ToWidth);
2337 ConvertedValue.setIsSigned(ToSigned);
2338 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2339 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2340 // If the result is different, this was a narrowing conversion.
2341 return ConvertedValue != InitializerValue;
2342 } else {
2343 // Variables are always narrowings.
2344 *isInitializerConstant = false;
2345 return true;
2346 }
2347 }
2348 return false;
2349 }
2350
2351 default:
2352 // Other kinds of conversions are not narrowings.
2353 return false;
2354 }
2355}
2356
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002357void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002358 FunctionDecl *Function,
2359 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002360 Step S;
2361 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2362 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002363 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002364 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365 Steps.push_back(S);
2366}
2367
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002369 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002370 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002371 switch (VK) {
2372 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2373 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2374 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002375 default: llvm_unreachable("No such category");
2376 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002377 S.Type = BaseType;
2378 Steps.push_back(S);
2379}
2380
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002381void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002382 bool BindingTemporary) {
2383 Step S;
2384 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2385 S.Type = T;
2386 Steps.push_back(S);
2387}
2388
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002389void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2390 Step S;
2391 S.Kind = SK_ExtraneousCopyToTemporary;
2392 S.Type = T;
2393 Steps.push_back(S);
2394}
2395
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002396void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002397 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002398 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 Step S;
2400 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002401 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002402 S.Function.Function = Function;
2403 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002404 Steps.push_back(S);
2405}
2406
2407void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002408 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002409 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002410 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002411 switch (VK) {
2412 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002413 S.Kind = SK_QualificationConversionRValue;
2414 break;
John McCall2536c6d2010-08-25 10:28:54 +00002415 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002416 S.Kind = SK_QualificationConversionXValue;
2417 break;
John McCall2536c6d2010-08-25 10:28:54 +00002418 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002419 S.Kind = SK_QualificationConversionLValue;
2420 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002421 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002422 S.Type = Ty;
2423 Steps.push_back(S);
2424}
2425
2426void InitializationSequence::AddConversionSequenceStep(
2427 const ImplicitConversionSequence &ICS,
2428 QualType T) {
2429 Step S;
2430 S.Kind = SK_ConversionSequence;
2431 S.Type = T;
2432 S.ICS = new ImplicitConversionSequence(ICS);
2433 Steps.push_back(S);
2434}
2435
Douglas Gregor51e77d52009-12-10 17:56:55 +00002436void InitializationSequence::AddListInitializationStep(QualType T) {
2437 Step S;
2438 S.Kind = SK_ListInitialization;
2439 S.Type = T;
2440 Steps.push_back(S);
2441}
2442
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002444InitializationSequence::AddConstructorInitializationStep(
2445 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002446 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002447 QualType T) {
2448 Step S;
2449 S.Kind = SK_ConstructorInitialization;
2450 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002451 S.Function.Function = Constructor;
2452 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002453 Steps.push_back(S);
2454}
2455
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002456void InitializationSequence::AddZeroInitializationStep(QualType T) {
2457 Step S;
2458 S.Kind = SK_ZeroInitialization;
2459 S.Type = T;
2460 Steps.push_back(S);
2461}
2462
Douglas Gregore1314a62009-12-18 05:02:21 +00002463void InitializationSequence::AddCAssignmentStep(QualType T) {
2464 Step S;
2465 S.Kind = SK_CAssignment;
2466 S.Type = T;
2467 Steps.push_back(S);
2468}
2469
Eli Friedman78275202009-12-19 08:11:05 +00002470void InitializationSequence::AddStringInitStep(QualType T) {
2471 Step S;
2472 S.Kind = SK_StringInit;
2473 S.Type = T;
2474 Steps.push_back(S);
2475}
2476
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002477void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2478 Step S;
2479 S.Kind = SK_ObjCObjectConversion;
2480 S.Type = T;
2481 Steps.push_back(S);
2482}
2483
Douglas Gregore2f943b2011-02-22 18:29:51 +00002484void InitializationSequence::AddArrayInitStep(QualType T) {
2485 Step S;
2486 S.Kind = SK_ArrayInit;
2487 S.Type = T;
2488 Steps.push_back(S);
2489}
2490
John McCall31168b02011-06-15 23:02:42 +00002491void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2492 bool shouldCopy) {
2493 Step s;
2494 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2495 : SK_PassByIndirectRestore);
2496 s.Type = type;
2497 Steps.push_back(s);
2498}
2499
2500void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2501 Step S;
2502 S.Kind = SK_ProduceObjCObject;
2503 S.Type = T;
2504 Steps.push_back(S);
2505}
2506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002508 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002509 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 this->Failure = Failure;
2511 this->FailedOverloadResult = Result;
2512}
2513
2514//===----------------------------------------------------------------------===//
2515// Attempt initialization
2516//===----------------------------------------------------------------------===//
2517
John McCall31168b02011-06-15 23:02:42 +00002518static void MaybeProduceObjCObject(Sema &S,
2519 InitializationSequence &Sequence,
2520 const InitializedEntity &Entity) {
2521 if (!S.getLangOptions().ObjCAutoRefCount) return;
2522
2523 /// When initializing a parameter, produce the value if it's marked
2524 /// __attribute__((ns_consumed)).
2525 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2526 if (!Entity.isParameterConsumed())
2527 return;
2528
2529 assert(Entity.getType()->isObjCRetainableType() &&
2530 "consuming an object of unretainable type?");
2531 Sequence.AddProduceObjCObjectStep(Entity.getType());
2532
2533 /// When initializing a return value, if the return type is a
2534 /// retainable type, then returns need to immediately retain the
2535 /// object. If an autorelease is required, it will be done at the
2536 /// last instant.
2537 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2538 if (!Entity.getType()->isObjCRetainableType())
2539 return;
2540
2541 Sequence.AddProduceObjCObjectStep(Entity.getType());
2542 }
2543}
2544
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002545/// \brief Attempt list initialization (C++0x [dcl.init.list])
2546static void TryListInitialization(Sema &S,
2547 const InitializedEntity &Entity,
2548 const InitializationKind &Kind,
2549 InitListExpr *InitList,
2550 InitializationSequence &Sequence) {
2551 // FIXME: We only perform rudimentary checking of list
2552 // initializations at this point, then assume that any list
2553 // initialization of an array, aggregate, or scalar will be
2554 // well-formed. When we actually "perform" list initialization, we'll
2555 // do all of the necessary checking. C++0x initializer lists will
2556 // force us to perform more checking here.
2557
2558 QualType DestType = Entity.getType();
2559
2560 // C++ [dcl.init]p13:
2561 // If T is a scalar type, then a declaration of the form
2562 //
2563 // T x = { a };
2564 //
2565 // is equivalent to
2566 //
2567 // T x = a;
2568 if (DestType->isScalarType()) {
2569 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2570 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2571 return;
2572 }
2573
2574 // Assume scalar initialization from a single value works.
2575 } else if (DestType->isAggregateType()) {
2576 // Assume aggregate initialization works.
2577 } else if (DestType->isVectorType()) {
2578 // Assume vector initialization works.
2579 } else if (DestType->isReferenceType()) {
2580 // FIXME: C++0x defines behavior for this.
2581 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2582 return;
2583 } else if (DestType->isRecordType()) {
2584 // FIXME: C++0x defines behavior for this
2585 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2586 }
2587
2588 // Add a general "list initialization" step.
2589 Sequence.AddListInitializationStep(DestType);
2590}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002591
2592/// \brief Try a reference initialization that involves calling a conversion
2593/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002594static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2595 const InitializedEntity &Entity,
2596 const InitializationKind &Kind,
2597 Expr *Initializer,
2598 bool AllowRValues,
2599 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002600 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2602 QualType T1 = cv1T1.getUnqualifiedType();
2603 QualType cv2T2 = Initializer->getType();
2604 QualType T2 = cv2T2.getUnqualifiedType();
2605
2606 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002607 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002608 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002610 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002611 ObjCConversion,
2612 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002613 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002614 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002615 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002616 (void)ObjCLifetimeConversion;
2617
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618 // Build the candidate set directly in the initialization sequence
2619 // structure, so that it will persist if we fail.
2620 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2621 CandidateSet.clear();
2622
2623 // Determine whether we are allowed to call explicit constructors or
2624 // explicit conversion operators.
2625 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002626
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002628 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2629 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002630 // The type we're converting to is a class type. Enumerate its constructors
2631 // to see if there is a suitable conversion.
2632 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002633
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002635 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002636 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002637 NamedDecl *D = *Con;
2638 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2639
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002640 // Find the constructor (which may be a template).
2641 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002642 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002643 if (ConstructorTmpl)
2644 Constructor = cast<CXXConstructorDecl>(
2645 ConstructorTmpl->getTemplatedDecl());
2646 else
John McCalla0296f72010-03-19 07:35:19 +00002647 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002649 if (!Constructor->isInvalidDecl() &&
2650 Constructor->isConvertingConstructor(AllowExplicit)) {
2651 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002652 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002653 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002654 &Initializer, 1, CandidateSet,
2655 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002656 else
John McCalla0296f72010-03-19 07:35:19 +00002657 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002658 &Initializer, 1, CandidateSet,
2659 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002660 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002662 }
John McCall3696dcb2010-08-17 07:23:57 +00002663 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2664 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Douglas Gregor496e8b342010-05-07 19:42:26 +00002666 const RecordType *T2RecordType = 0;
2667 if ((T2RecordType = T2->getAs<RecordType>()) &&
2668 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669 // The type we're converting from is a class type, enumerate its conversion
2670 // functions.
2671 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2672
John McCallad371252010-01-20 00:46:10 +00002673 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002674 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002675 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2676 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 NamedDecl *D = *I;
2678 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2679 if (isa<UsingShadowDecl>(D))
2680 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2683 CXXConversionDecl *Conv;
2684 if (ConvTemplate)
2685 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2686 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002687 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002689 // If the conversion function doesn't return a reference type,
2690 // it can't be considered for this conversion unless we're allowed to
2691 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692 // FIXME: Do we need to make sure that we only consider conversion
2693 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002694 // break recursion.
2695 if ((AllowExplicit || !Conv->isExplicit()) &&
2696 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2697 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002698 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002699 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002700 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002701 else
John McCalla0296f72010-03-19 07:35:19 +00002702 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002703 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002704 }
2705 }
2706 }
John McCall3696dcb2010-08-17 07:23:57 +00002707 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2708 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002710 SourceLocation DeclLoc = Initializer->getLocStart();
2711
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002712 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002713 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002715 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002717
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002718 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002719
Chandler Carruth30141632011-02-25 19:41:05 +00002720 // This is the overload that will actually be used for the initialization, so
2721 // mark it as used.
2722 S.MarkDeclarationReferenced(DeclLoc, Function);
2723
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002724 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725 if (isa<CXXConversionDecl>(Function))
2726 T2 = Function->getResultType();
2727 else
2728 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002729
2730 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002731 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002732 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002733
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002734 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002735 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002736 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002737 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002738 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002739 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002740 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002741
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002742 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002743 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002744 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002745 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002747 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002748 NewDerivedToBase, NewObjCConversion,
2749 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002750 if (NewRefRelationship == Sema::Ref_Incompatible) {
2751 // If the type we've converted to is not reference-related to the
2752 // type we're looking for, then there is another conversion step
2753 // we need to perform to produce a temporary of the right type
2754 // that we'll be binding to.
2755 ImplicitConversionSequence ICS;
2756 ICS.setStandard();
2757 ICS.Standard = Best->FinalConversion;
2758 T2 = ICS.Standard.getToType(2);
2759 Sequence.AddConversionSequenceStep(ICS, T2);
2760 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002761 Sequence.AddDerivedToBaseCastStep(
2762 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002763 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002764 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002765 else if (NewObjCConversion)
2766 Sequence.AddObjCObjectConversionStep(
2767 S.Context.getQualifiedType(T1,
2768 T2.getNonReferenceType().getQualifiers()));
2769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002770 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002771 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002772
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002773 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2774 return OR_Success;
2775}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002776
2777/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2778static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002779 const InitializedEntity &Entity,
2780 const InitializationKind &Kind,
2781 Expr *Initializer,
2782 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002783 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002784 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002785 Qualifiers T1Quals;
2786 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002787 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002788 Qualifiers T2Quals;
2789 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002790 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002792 // If the initializer is the address of an overloaded function, try
2793 // to resolve the overloaded function. If all goes well, T2 is the
2794 // type of the resulting function.
2795 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002796 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002798 T1,
2799 false,
2800 Found)) {
2801 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2802 cv2T2 = Fn->getType();
2803 T2 = cv2T2.getUnqualifiedType();
2804 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002805 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2806 return;
2807 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002808 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002810 // Compute some basic properties of the types and the initializer.
2811 bool isLValueRef = DestType->isLValueReferenceType();
2812 bool isRValueRef = !isLValueRef;
2813 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002814 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002815 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002816 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002817 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002818 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002819 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002820
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002821 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002823 // "cv2 T2" as follows:
2824 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002826 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002827 // Note the analogous bullet points for rvlaue refs to functions. Because
2828 // there are no function rvalues in C++, rvalue refs to functions are treated
2829 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002830 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002831 bool T1Function = T1->isFunctionType();
2832 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002833 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002834 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002836 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002837 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002838 // reference-compatible with "cv2 T2," or
2839 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002841 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002842 // can occur. However, we do pay attention to whether it is a bit-field
2843 // to decide whether we're actually binding to a temporary created from
2844 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002845 if (DerivedToBase)
2846 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002847 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002848 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002849 else if (ObjCConversion)
2850 Sequence.AddObjCObjectConversionStep(
2851 S.Context.getQualifiedType(T1, T2Quals));
2852
Chandler Carruth04bdce62010-01-12 20:32:25 +00002853 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002854 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002855 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002856 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002857 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002858 return;
2859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002860
2861 // - has a class type (i.e., T2 is a class type), where T1 is not
2862 // reference-related to T2, and can be implicitly converted to an
2863 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2864 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865 // applicable conversion functions (13.3.1.6) and choosing the best
2866 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002867 // If we have an rvalue ref to function type here, the rhs must be
2868 // an rvalue.
2869 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2870 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002871 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002872 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002873 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002874 Sequence);
2875 if (ConvOvlResult == OR_Success)
2876 return;
John McCall0d1da222010-01-12 00:44:57 +00002877 if (ConvOvlResult != OR_No_Viable_Function) {
2878 Sequence.SetOverloadFailure(
2879 InitializationSequence::FK_ReferenceInitOverloadFailed,
2880 ConvOvlResult);
2881 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 }
2883 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002887 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002888 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002889 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2890 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2891 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002892 Sequence.SetOverloadFailure(
2893 InitializationSequence::FK_ReferenceInitOverloadFailed,
2894 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002895 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002896 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897 ? (RefRelationship == Sema::Ref_Related
2898 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2899 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2900 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902 return;
2903 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002904
Douglas Gregor92e460e2011-01-20 16:44:54 +00002905 // - If the initializer expression
2906 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2907 // "cv1 T1" is reference-compatible with "cv2 T2"
2908 // Note: functions are handled below.
2909 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002910 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002912 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002913 (InitCategory.isXValue() ||
2914 (InitCategory.isPRValue() && T2->isRecordType()) ||
2915 (InitCategory.isPRValue() && T2->isArrayType()))) {
2916 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2917 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002918 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2919 // compiler the freedom to perform a copy here or bind to the
2920 // object, while C++0x requires that we bind directly to the
2921 // object. Hence, we always bind to the object without making an
2922 // extra copy. However, in C++03 requires that we check for the
2923 // presence of a suitable copy constructor:
2924 //
2925 // The constructor that would be used to make the copy shall
2926 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002927 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002928 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930
Douglas Gregor92e460e2011-01-20 16:44:54 +00002931 if (DerivedToBase)
2932 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2933 ValueKind);
2934 else if (ObjCConversion)
2935 Sequence.AddObjCObjectConversionStep(
2936 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002937
Douglas Gregor92e460e2011-01-20 16:44:54 +00002938 if (T1Quals != T2Quals)
2939 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002941 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
2945 // - has a class type (i.e., T2 is a class type), where T1 is not
2946 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002947 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2948 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002949 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002950 if (RefRelationship == Sema::Ref_Incompatible) {
2951 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2952 Kind, Initializer,
2953 /*AllowRValues=*/true,
2954 Sequence);
2955 if (ConvOvlResult)
2956 Sequence.SetOverloadFailure(
2957 InitializationSequence::FK_ReferenceInitOverloadFailed,
2958 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002960 return;
2961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002963 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2964 return;
2965 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002966
2967 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002971
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002972 // Determine whether we are allowed to call explicit constructors or
2973 // explicit conversion operators.
2974 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002975
2976 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2977
John McCall31168b02011-06-15 23:02:42 +00002978 ImplicitConversionSequence ICS
2979 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00002980 /*SuppressUserConversions*/ false,
2981 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002982 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00002983 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2984 /*AllowObjCWritebackConversion=*/false);
2985
2986 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002987 // FIXME: Use the conversion function set stored in ICS to turn
2988 // this into an overloading ambiguity diagnostic. However, we need
2989 // to keep that set as an OverloadCandidateSet rather than as some
2990 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002991 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2992 Sequence.SetOverloadFailure(
2993 InitializationSequence::FK_ReferenceInitOverloadFailed,
2994 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002995 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2996 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002997 else
2998 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002999 return;
John McCall31168b02011-06-15 23:02:42 +00003000 } else {
3001 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003002 }
3003
3004 // [...] If T1 is reference-related to T2, cv1 must be the
3005 // same cv-qualification as, or greater cv-qualification
3006 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003007 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3008 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003010 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003011 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3012 return;
3013 }
3014
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003015 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003016 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003018 InitCategory.isLValue()) {
3019 Sequence.SetFailed(
3020 InitializationSequence::FK_RValueReferenceBindingToLValue);
3021 return;
3022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003024 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3025 return;
3026}
3027
3028/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029/// (C++ [dcl.init.string], C99 6.7.8).
3030static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003031 const InitializedEntity &Entity,
3032 const InitializationKind &Kind,
3033 Expr *Initializer,
3034 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003035 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003036}
3037
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003038/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3039/// enumerates the constructors of the initialized entity and performs overload
3040/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003041static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003042 const InitializedEntity &Entity,
3043 const InitializationKind &Kind,
3044 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003045 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046 InitializationSequence &Sequence) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003047 // Build the candidate set directly in the initialization sequence
3048 // structure, so that it will persist if we fail.
3049 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3050 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003052 // Determine whether we are allowed to call explicit constructors or
3053 // explicit conversion operators.
3054 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3055 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003056 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003057
3058 // The type we're constructing needs to be complete.
3059 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003060 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003061 return;
3062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003064 // The type we're converting to is a class type. Enumerate its constructors
3065 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003066 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003068 CXXRecordDecl *DestRecordDecl
3069 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003071 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003072 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003073 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003074 NamedDecl *D = *Con;
3075 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003076 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003078 // Find the constructor (which may be a template).
3079 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003080 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003081 if (ConstructorTmpl)
3082 Constructor = cast<CXXConstructorDecl>(
3083 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003084 else {
John McCalla0296f72010-03-19 07:35:19 +00003085 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003086
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003088 // suppress user-defined conversions on the arguments.
3089 // FIXME: Move constructors?
3090 if (Kind.getKind() == InitializationKind::IK_Copy &&
3091 Constructor->isCopyConstructor())
3092 SuppressUserConversions = true;
3093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003095 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003096 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003097 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003098 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003099 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003100 Args, NumArgs, CandidateSet,
3101 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003102 else
John McCalla0296f72010-03-19 07:35:19 +00003103 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003104 Args, NumArgs, CandidateSet,
3105 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107 }
3108
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003109 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110
3111 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003112 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003114 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003115 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003117 Result);
3118 return;
3119 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003120
3121 // C++0x [dcl.init]p6:
3122 // If a program calls for the default initialization of an object
3123 // of a const-qualified type T, T shall be a class type with a
3124 // user-provided default constructor.
3125 if (Kind.getKind() == InitializationKind::IK_Default &&
3126 Entity.getType().isConstQualified() &&
3127 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3128 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3129 return;
3130 }
3131
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003132 // Add the constructor initialization step. Any cv-qualification conversion is
3133 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003134 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003136 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003137 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138}
3139
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003140/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003142 const InitializedEntity &Entity,
3143 const InitializationKind &Kind,
3144 InitializationSequence &Sequence) {
3145 // C++ [dcl.init]p5:
3146 //
3147 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003148 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003150 // -- if T is an array type, then each element is value-initialized;
3151 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3152 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003154 if (const RecordType *RT = T->getAs<RecordType>()) {
3155 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3156 // -- if T is a class type (clause 9) with a user-declared
3157 // constructor (12.1), then the default constructor for T is
3158 // called (and the initialization is ill-formed if T has no
3159 // accessible default constructor);
3160 //
3161 // FIXME: we really want to refer to a single subobject of the array,
3162 // but Entity doesn't have a way to capture that (yet).
3163 if (ClassDecl->hasUserDeclaredConstructor())
3164 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003166 // -- if T is a (possibly cv-qualified) non-union class type
3167 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003168 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003169 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003170 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003171 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003172 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003174 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003175 }
3176 }
3177
Douglas Gregor1b303932009-12-22 15:35:07 +00003178 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003179}
3180
Douglas Gregor85dabae2009-12-16 01:38:02 +00003181/// \brief Attempt default initialization (C++ [dcl.init]p6).
3182static void TryDefaultInitialization(Sema &S,
3183 const InitializedEntity &Entity,
3184 const InitializationKind &Kind,
3185 InitializationSequence &Sequence) {
3186 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor85dabae2009-12-16 01:38:02 +00003188 // C++ [dcl.init]p6:
3189 // To default-initialize an object of type T means:
3190 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003191 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3192
Douglas Gregor85dabae2009-12-16 01:38:02 +00003193 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3194 // constructor for T is called (and the initialization is ill-formed if
3195 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003196 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003197 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3198 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Douglas Gregor85dabae2009-12-16 01:38:02 +00003201 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202
Douglas Gregor85dabae2009-12-16 01:38:02 +00003203 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003205 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003206 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003207 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003208 return;
3209 }
3210
3211 // If the destination type has a lifetime property, zero-initialize it.
3212 if (DestType.getQualifiers().hasObjCLifetime()) {
3213 Sequence.AddZeroInitializationStep(Entity.getType());
3214 return;
3215 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003216}
3217
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003218/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3219/// which enumerates all conversion functions and performs overload resolution
3220/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003222 const InitializedEntity &Entity,
3223 const InitializationKind &Kind,
3224 Expr *Initializer,
3225 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003226 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003227 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3228 QualType SourceType = Initializer->getType();
3229 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3230 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
Douglas Gregor540c3b02009-12-14 17:27:33 +00003232 // Build the candidate set directly in the initialization sequence
3233 // structure, so that it will persist if we fail.
3234 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3235 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
Douglas Gregor540c3b02009-12-14 17:27:33 +00003237 // Determine whether we are allowed to call explicit constructors or
3238 // explicit conversion operators.
3239 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240
Douglas Gregor540c3b02009-12-14 17:27:33 +00003241 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3242 // The type we're converting to is a class type. Enumerate its constructors
3243 // to see if there is a suitable conversion.
3244 CXXRecordDecl *DestRecordDecl
3245 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246
Douglas Gregord9848152010-04-26 14:36:57 +00003247 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003249 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003250 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003251 Con != ConEnd; ++Con) {
3252 NamedDecl *D = *Con;
3253 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregord9848152010-04-26 14:36:57 +00003255 // Find the constructor (which may be a template).
3256 CXXConstructorDecl *Constructor = 0;
3257 FunctionTemplateDecl *ConstructorTmpl
3258 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003259 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003260 Constructor = cast<CXXConstructorDecl>(
3261 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003262 else
Douglas Gregord9848152010-04-26 14:36:57 +00003263 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264
Douglas Gregord9848152010-04-26 14:36:57 +00003265 if (!Constructor->isInvalidDecl() &&
3266 Constructor->isConvertingConstructor(AllowExplicit)) {
3267 if (ConstructorTmpl)
3268 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3269 /*ExplicitArgs*/ 0,
3270 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003271 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003272 else
3273 S.AddOverloadCandidate(Constructor, FoundDecl,
3274 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003275 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277 }
Douglas Gregord9848152010-04-26 14:36:57 +00003278 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003279 }
Eli Friedman78275202009-12-19 08:11:05 +00003280
3281 SourceLocation DeclLoc = Initializer->getLocStart();
3282
Douglas Gregor540c3b02009-12-14 17:27:33 +00003283 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3284 // The type we're converting from is a class type, enumerate its conversion
3285 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003286
Eli Friedman4afe9a32009-12-20 22:12:03 +00003287 // We can only enumerate the conversion functions for a complete type; if
3288 // the type isn't complete, simply skip this step.
3289 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3290 CXXRecordDecl *SourceRecordDecl
3291 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292
John McCallad371252010-01-20 00:46:10 +00003293 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003294 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003295 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003297 I != E; ++I) {
3298 NamedDecl *D = *I;
3299 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3300 if (isa<UsingShadowDecl>(D))
3301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
Eli Friedman4afe9a32009-12-20 22:12:03 +00003303 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3304 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003305 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003307 else
John McCallda4458e2010-03-31 01:36:47 +00003308 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003309
Eli Friedman4afe9a32009-12-20 22:12:03 +00003310 if (AllowExplicit || !Conv->isExplicit()) {
3311 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003312 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003313 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003314 CandidateSet);
3315 else
John McCalla0296f72010-03-19 07:35:19 +00003316 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003317 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003318 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003319 }
3320 }
3321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
3323 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003324 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003325 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003326 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003327 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003329 Result);
3330 return;
3331 }
John McCall0d1da222010-01-12 00:44:57 +00003332
Douglas Gregor540c3b02009-12-14 17:27:33 +00003333 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003334 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335
Douglas Gregor540c3b02009-12-14 17:27:33 +00003336 if (isa<CXXConstructorDecl>(Function)) {
3337 // Add the user-defined conversion step. Any cv-qualification conversion is
3338 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003339 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003340 return;
3341 }
3342
3343 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003344 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003345 if (ConvType->getAs<RecordType>()) {
3346 // If we're converting to a class type, there may be an copy if
3347 // the resulting temporary object (possible to create an object of
3348 // a base class type). That copy is not a separate conversion, so
3349 // we just make a note of the actual destination type (possibly a
3350 // base class of the type returned by the conversion function) and
3351 // let the user-defined conversion step handle the conversion.
3352 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3353 return;
3354 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003355
Douglas Gregor5ab11652010-04-17 22:01:05 +00003356 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregor5ab11652010-04-17 22:01:05 +00003358 // If the conversion following the call to the conversion function
3359 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003360 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3361 Best->FinalConversion.Third) {
3362 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003363 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003364 ICS.Standard = Best->FinalConversion;
3365 Sequence.AddConversionSequenceStep(ICS, DestType);
3366 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003367}
3368
John McCall31168b02011-06-15 23:02:42 +00003369/// The non-zero enum values here are indexes into diagnostic alternatives.
3370enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3371
3372/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003373static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3374 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003375 // Skip parens.
3376 e = e->IgnoreParens();
3377
3378 // Skip address-of nodes.
3379 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3380 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003381 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003382
3383 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003384 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3385 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003386 case CK_Dependent:
3387 case CK_BitCast:
3388 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003389 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003390 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003391
3392 case CK_ArrayToPointerDecay:
3393 return IIK_nonscalar;
3394
3395 case CK_NullToPointer:
3396 return IIK_okay;
3397
3398 default:
3399 break;
3400 }
3401
3402 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003403 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3404 if (!isAddressOf) return IIK_nonlocal;
3405
3406 VarDecl *var;
3407 if (isa<DeclRefExpr>(e)) {
3408 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3409 if (!var) return IIK_nonlocal;
3410 } else {
3411 var = cast<BlockDeclRefExpr>(e)->getDecl();
3412 }
3413
3414 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003415
3416 // If we have a conditional operator, check both sides.
3417 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003418 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003419 return iik;
3420
John McCall63f84442011-06-27 23:59:58 +00003421 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003422
3423 // These are never scalar.
3424 } else if (isa<ArraySubscriptExpr>(e)) {
3425 return IIK_nonscalar;
3426
3427 // Otherwise, it needs to be a null pointer constant.
3428 } else {
3429 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3430 ? IIK_okay : IIK_nonlocal);
3431 }
3432
3433 return IIK_nonlocal;
3434}
3435
3436/// Check whether the given expression is a valid operand for an
3437/// indirect copy/restore.
3438static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3439 assert(src->isRValue());
3440
John McCall63f84442011-06-27 23:59:58 +00003441 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003442 if (iik == IIK_okay) return;
3443
3444 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3445 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3446 << src->getSourceRange();
3447}
3448
Douglas Gregore2f943b2011-02-22 18:29:51 +00003449/// \brief Determine whether we have compatible array types for the
3450/// purposes of GNU by-copy array initialization.
3451static bool hasCompatibleArrayTypes(ASTContext &Context,
3452 const ArrayType *Dest,
3453 const ArrayType *Source) {
3454 // If the source and destination array types are equivalent, we're
3455 // done.
3456 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3457 return true;
3458
3459 // Make sure that the element types are the same.
3460 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3461 return false;
3462
3463 // The only mismatch we allow is when the destination is an
3464 // incomplete array type and the source is a constant array type.
3465 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3466}
3467
John McCall31168b02011-06-15 23:02:42 +00003468static bool tryObjCWritebackConversion(Sema &S,
3469 InitializationSequence &Sequence,
3470 const InitializedEntity &Entity,
3471 Expr *Initializer) {
3472 bool ArrayDecay = false;
3473 QualType ArgType = Initializer->getType();
3474 QualType ArgPointee;
3475 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3476 ArrayDecay = true;
3477 ArgPointee = ArgArrayType->getElementType();
3478 ArgType = S.Context.getPointerType(ArgPointee);
3479 }
3480
3481 // Handle write-back conversion.
3482 QualType ConvertedArgType;
3483 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3484 ConvertedArgType))
3485 return false;
3486
3487 // We should copy unless we're passing to an argument explicitly
3488 // marked 'out'.
3489 bool ShouldCopy = true;
3490 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3491 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3492
3493 // Do we need an lvalue conversion?
3494 if (ArrayDecay || Initializer->isGLValue()) {
3495 ImplicitConversionSequence ICS;
3496 ICS.setStandard();
3497 ICS.Standard.setAsIdentityConversion();
3498
3499 QualType ResultType;
3500 if (ArrayDecay) {
3501 ICS.Standard.First = ICK_Array_To_Pointer;
3502 ResultType = S.Context.getPointerType(ArgPointee);
3503 } else {
3504 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3505 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3506 }
3507
3508 Sequence.AddConversionSequenceStep(ICS, ResultType);
3509 }
3510
3511 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3512 return true;
3513}
3514
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003515InitializationSequence::InitializationSequence(Sema &S,
3516 const InitializedEntity &Entity,
3517 const InitializationKind &Kind,
3518 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003519 unsigned NumArgs)
3520 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003521 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003523 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524 // The semantics of initializers are as follows. The destination type is
3525 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003526 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003528 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003529 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003530
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003531 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3533 SequenceKind = DependentSequence;
3534 return;
3535 }
3536
Sebastian Redld201edf2011-06-05 13:59:11 +00003537 // Almost everything is a normal sequence.
3538 setSequenceKind(NormalSequence);
3539
John McCalled75c092010-12-07 22:54:16 +00003540 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003541 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3542 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3543 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003544 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003545 return;
3546 }
3547 Args[I] = Result.take();
3548 }
John McCalled75c092010-12-07 22:54:16 +00003549
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550 QualType SourceType;
3551 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003552 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003553 Initializer = Args[0];
3554 if (!isa<InitListExpr>(Initializer))
3555 SourceType = Initializer->getType();
3556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
3558 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003559 // list-initialized (8.5.4).
3560 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003561 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003562 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003565 // - If the destination type is a reference type, see 8.5.3.
3566 if (DestType->isReferenceType()) {
3567 // C++0x [dcl.init.ref]p1:
3568 // A variable declared to be a T& or T&&, that is, "reference to type T"
3569 // (8.3.2), shall be initialized by an object, or function, of type T or
3570 // by an object that can be converted into a T.
3571 // (Therefore, multiple arguments are not permitted.)
3572 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003573 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003575 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003576 return;
3577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003579 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003580 if (Kind.getKind() == InitializationKind::IK_Value ||
3581 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003582 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003583 return;
3584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585
Douglas Gregor85dabae2009-12-16 01:38:02 +00003586 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003587 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003588 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003589 return;
3590 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003591
John McCall66884dd2011-02-21 07:22:22 +00003592 // - If the destination type is an array of characters, an array of
3593 // char16_t, an array of char32_t, or an array of wchar_t, and the
3594 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003596 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003597 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3598 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003599 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003600 return;
3601 }
3602
Douglas Gregore2f943b2011-02-22 18:29:51 +00003603 // Note: as an GNU C extension, we allow initialization of an
3604 // array from a compound literal that creates an array of the same
3605 // type, so long as the initializer has no side effects.
3606 if (!S.getLangOptions().CPlusPlus && Initializer &&
3607 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3608 Initializer->getType()->isArrayType()) {
3609 const ArrayType *SourceAT
3610 = Context.getAsArrayType(Initializer->getType());
3611 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003612 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003613 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003614 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003615 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003616 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003617 }
3618 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003619 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003621 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 return;
3624 }
Eli Friedman78275202009-12-19 08:11:05 +00003625
John McCall31168b02011-06-15 23:02:42 +00003626 // Determine whether we should consider writeback conversions for
3627 // Objective-C ARC.
3628 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3629 Entity.getKind() == InitializedEntity::EK_Parameter;
3630
3631 // We're at the end of the line for C: it's either a write-back conversion
3632 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003633 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003634 // If allowed, check whether this is an Objective-C writeback conversion.
3635 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003636 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003637 return;
3638 }
3639
3640 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003641 AddCAssignmentStep(DestType);
3642 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003643 return;
3644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
John McCall31168b02011-06-15 23:02:42 +00003646 assert(S.getLangOptions().CPlusPlus);
3647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // - If the destination type is a (possibly cv-qualified) class type:
3649 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650 // - If the initialization is direct-initialization, or if it is
3651 // copy-initialization where the cv-unqualified version of the
3652 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003653 // class of the destination, constructors are considered. [...]
3654 if (Kind.getKind() == InitializationKind::IK_Direct ||
3655 (Kind.getKind() == InitializationKind::IK_Copy &&
3656 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3657 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003659 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663 // used) to a derived class thereof are enumerated as described in
3664 // 13.3.1.4, and the best one is chosen through overload resolution
3665 // (13.3).
3666 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003667 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003668 return;
3669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670
Douglas Gregor85dabae2009-12-16 01:38:02 +00003671 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003672 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003673 return;
3674 }
3675 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
3677 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003679 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003680 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3681 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 return;
3683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003686 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003687 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003689 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003690
3691 ImplicitConversionSequence ICS
3692 = S.TryImplicitConversion(Initializer, Entity.getType(),
3693 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003694 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003695 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003696 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3697 allowObjCWritebackConversion);
3698
3699 if (ICS.isStandard() &&
3700 ICS.Standard.Second == ICK_Writeback_Conversion) {
3701 // Objective-C ARC writeback conversion.
3702
3703 // We should copy unless we're passing to an argument explicitly
3704 // marked 'out'.
3705 bool ShouldCopy = true;
3706 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3707 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3708
3709 // If there was an lvalue adjustment, add it as a separate conversion.
3710 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3711 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3712 ImplicitConversionSequence LvalueICS;
3713 LvalueICS.setStandard();
3714 LvalueICS.Standard.setAsIdentityConversion();
3715 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3716 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003717 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003718 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003719
3720 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003721 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003722 DeclAccessPair dap;
3723 if (Initializer->getType() == Context.OverloadTy &&
3724 !S.ResolveAddressOfOverloadedFunction(Initializer
3725 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003726 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003727 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003728 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003729 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003730 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003731
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003732 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003733 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734}
3735
3736InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003737 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003738 StepEnd = Steps.end();
3739 Step != StepEnd; ++Step)
3740 Step->Destroy();
3741}
3742
3743//===----------------------------------------------------------------------===//
3744// Perform initialization
3745//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003747getAssignmentAction(const InitializedEntity &Entity) {
3748 switch(Entity.getKind()) {
3749 case InitializedEntity::EK_Variable:
3750 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003751 case InitializedEntity::EK_Exception:
3752 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003753 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003754 return Sema::AA_Initializing;
3755
3756 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003758 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3759 return Sema::AA_Sending;
3760
Douglas Gregore1314a62009-12-18 05:02:21 +00003761 return Sema::AA_Passing;
3762
3763 case InitializedEntity::EK_Result:
3764 return Sema::AA_Returning;
3765
Douglas Gregore1314a62009-12-18 05:02:21 +00003766 case InitializedEntity::EK_Temporary:
3767 // FIXME: Can we tell apart casting vs. converting?
3768 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Douglas Gregore1314a62009-12-18 05:02:21 +00003770 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003771 case InitializedEntity::EK_ArrayElement:
3772 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003773 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003774 return Sema::AA_Initializing;
3775 }
3776
3777 return Sema::AA_Converting;
3778}
3779
Douglas Gregor95562572010-04-24 23:45:46 +00003780/// \brief Whether we should binding a created object as a temporary when
3781/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003782static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003783 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003784 case InitializedEntity::EK_ArrayElement:
3785 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003786 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003787 case InitializedEntity::EK_New:
3788 case InitializedEntity::EK_Variable:
3789 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003790 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003791 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003792 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003793 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003794 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregore1314a62009-12-18 05:02:21 +00003796 case InitializedEntity::EK_Parameter:
3797 case InitializedEntity::EK_Temporary:
3798 return true;
3799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregore1314a62009-12-18 05:02:21 +00003801 llvm_unreachable("missed an InitializedEntity kind?");
3802}
3803
Douglas Gregor95562572010-04-24 23:45:46 +00003804/// \brief Whether the given entity, when initialized with an object
3805/// created for that initialization, requires destruction.
3806static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3807 switch (Entity.getKind()) {
3808 case InitializedEntity::EK_Member:
3809 case InitializedEntity::EK_Result:
3810 case InitializedEntity::EK_New:
3811 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003812 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003813 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003814 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003815 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Douglas Gregor95562572010-04-24 23:45:46 +00003817 case InitializedEntity::EK_Variable:
3818 case InitializedEntity::EK_Parameter:
3819 case InitializedEntity::EK_Temporary:
3820 case InitializedEntity::EK_ArrayElement:
3821 case InitializedEntity::EK_Exception:
3822 return true;
3823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824
3825 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003826}
3827
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003828/// \brief Make a (potentially elidable) temporary copy of the object
3829/// provided by the given initializer by calling the appropriate copy
3830/// constructor.
3831///
3832/// \param S The Sema object used for type-checking.
3833///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003834/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003835/// the type of the initializer expression or a superclass thereof.
3836///
3837/// \param Enter The entity being initialized.
3838///
3839/// \param CurInit The initializer expression.
3840///
3841/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3842/// is permitted in C++03 (but not C++0x) when binding a reference to
3843/// an rvalue.
3844///
3845/// \returns An expression that copies the initializer expression into
3846/// a temporary object, or an error expression if a copy could not be
3847/// created.
John McCalldadc5752010-08-24 06:29:42 +00003848static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003849 QualType T,
3850 const InitializedEntity &Entity,
3851 ExprResult CurInit,
3852 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003853 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003854 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003856 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003857 Class = cast<CXXRecordDecl>(Record->getDecl());
3858 if (!Class)
3859 return move(CurInit);
3860
Douglas Gregor5d369002011-01-21 18:05:27 +00003861 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003862 // When certain criteria are met, an implementation is allowed to
3863 // omit the copy/move construction of a class object, even if the
3864 // copy/move constructor and/or destructor for the object have
3865 // side effects. [...]
3866 // - when a temporary class object that has not been bound to a
3867 // reference (12.2) would be copied/moved to a class object
3868 // with the same cv-unqualified type, the copy/move operation
3869 // can be omitted by constructing the temporary object
3870 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003872 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003873 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003875 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003876 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003877 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003878 switch (Entity.getKind()) {
3879 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003880 Loc = Entity.getReturnLoc();
3881 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
Douglas Gregore1314a62009-12-18 05:02:21 +00003883 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003884 Loc = Entity.getThrowLoc();
3885 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Douglas Gregore1314a62009-12-18 05:02:21 +00003887 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003888 Loc = Entity.getDecl()->getLocation();
3889 break;
3890
Anders Carlsson0bd52402010-01-24 00:19:41 +00003891 case InitializedEntity::EK_ArrayElement:
3892 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003893 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003894 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003895 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003896 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003897 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003898 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003899 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003900 Loc = CurInitExpr->getLocStart();
3901 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003902 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003903
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003905 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3906 return move(CurInit);
3907
Douglas Gregorf282a762011-01-21 19:38:21 +00003908 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003909 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003910 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003911 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003912 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003913 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003914 // C++0x [dcl.init]p16, second bullet to class types, this
3915 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003916 CXXConstructorDecl *Constructor = 0;
3917
3918 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003919 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003920 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003921 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003922 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003923 continue;
3924
3925 DeclAccessPair FoundDecl
3926 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3927 S.AddOverloadCandidate(Constructor, FoundDecl,
3928 &CurInitExpr, 1, CandidateSet);
3929 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003931
3932 // Handle constructor templates.
3933 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3934 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003935 continue;
John McCalla0296f72010-03-19 07:35:19 +00003936
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003937 Constructor = cast<CXXConstructorDecl>(
3938 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003939 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003940 continue;
3941
3942 // FIXME: Do we need to limit this to copy-constructor-like
3943 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003944 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003945 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3946 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3947 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949
Douglas Gregore1314a62009-12-18 05:02:21 +00003950 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003951 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003952 case OR_Success:
3953 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954
Douglas Gregore1314a62009-12-18 05:02:21 +00003955 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003956 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3957 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3958 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003959 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003960 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003961 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003962 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003963 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003964 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregore1314a62009-12-18 05:02:21 +00003966 case OR_Ambiguous:
3967 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003968 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003969 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003970 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003971 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972
Douglas Gregore1314a62009-12-18 05:02:21 +00003973 case OR_Deleted:
3974 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003975 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 << CurInitExpr->getSourceRange();
3977 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00003978 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003979 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003980 }
3981
Douglas Gregor5ab11652010-04-17 22:01:05 +00003982 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003983 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003984 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003985
Anders Carlssona01874b2010-04-21 18:47:17 +00003986 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003987 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003988
3989 if (IsExtraneousCopy) {
3990 // If this is a totally extraneous copy for C++03 reference
3991 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003992 // expression. We don't generate an (elided) copy operation here
3993 // because doing so would require us to pass down a flag to avoid
3994 // infinite recursion, where each step adds another extraneous,
3995 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003996
Douglas Gregor30b52772010-04-18 07:57:34 +00003997 // Instantiate the default arguments of any extra parameters in
3998 // the selected copy constructor, as if we were going to create a
3999 // proper call to the copy constructor.
4000 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4001 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4002 if (S.RequireCompleteType(Loc, Parm->getType(),
4003 S.PDiag(diag::err_call_incomplete_argument)))
4004 break;
4005
4006 // Build the default argument expression; we don't actually care
4007 // if this succeeds or not, because this routine will complain
4008 // if there was a problem.
4009 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4010 }
4011
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004012 return S.Owned(CurInitExpr);
4013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Chandler Carruth30141632011-02-25 19:41:05 +00004015 S.MarkDeclarationReferenced(Loc, Constructor);
4016
Douglas Gregor5ab11652010-04-17 22:01:05 +00004017 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004018 // constructor call (we might have derived-to-base conversions, or
4019 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004020 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004021 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004022 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004023
Douglas Gregord0ace022010-04-25 00:55:24 +00004024 // Actually perform the constructor call.
4025 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004026 move_arg(ConstructorArgs),
4027 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004028 CXXConstructExpr::CK_Complete,
4029 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Douglas Gregord0ace022010-04-25 00:55:24 +00004031 // If we're supposed to bind temporaries, do so.
4032 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4033 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4034 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004035}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004037void InitializationSequence::PrintInitLocationNote(Sema &S,
4038 const InitializedEntity &Entity) {
4039 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4040 if (Entity.getDecl()->getLocation().isInvalid())
4041 return;
4042
4043 if (Entity.getDecl()->getDeclName())
4044 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4045 << Entity.getDecl()->getDeclName();
4046 else
4047 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4048 }
4049}
4050
Sebastian Redl112aa822011-07-14 19:07:55 +00004051static bool isReferenceBinding(const InitializationSequence::Step &s) {
4052 return s.Kind == InitializationSequence::SK_BindReference ||
4053 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4054}
4055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057InitializationSequence::Perform(Sema &S,
4058 const InitializedEntity &Entity,
4059 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004060 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004061 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004062 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004063 unsigned NumArgs = Args.size();
4064 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004065 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Sebastian Redld201edf2011-06-05 13:59:11 +00004068 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004069 // If the declaration is a non-dependent, incomplete array type
4070 // that has an initializer, then its type will be completed once
4071 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004072 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004073 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004074 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004075 if (const IncompleteArrayType *ArrayT
4076 = S.Context.getAsIncompleteArrayType(DeclType)) {
4077 // FIXME: We don't currently have the ability to accurately
4078 // compute the length of an initializer list without
4079 // performing full type-checking of the initializer list
4080 // (since we have to determine where braces are implicitly
4081 // introduced and such). So, we fall back to making the array
4082 // type a dependently-sized array type with no specified
4083 // bound.
4084 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4085 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004086
Douglas Gregor51e77d52009-12-10 17:56:55 +00004087 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004088 if (DeclaratorDecl *DD = Entity.getDecl()) {
4089 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4090 TypeLoc TL = TInfo->getTypeLoc();
4091 if (IncompleteArrayTypeLoc *ArrayLoc
4092 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4093 Brackets = ArrayLoc->getBracketsRange();
4094 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004095 }
4096
4097 *ResultType
4098 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4099 /*NumElts=*/0,
4100 ArrayT->getSizeModifier(),
4101 ArrayT->getIndexTypeCVRQualifiers(),
4102 Brackets);
4103 }
4104
4105 }
4106 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004107 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4108 Kind.isExplicitCast());
4109 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004110 }
4111
Sebastian Redld201edf2011-06-05 13:59:11 +00004112 // No steps means no initialization.
4113 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004114 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115
Douglas Gregor1b303932009-12-22 15:35:07 +00004116 QualType DestType = Entity.getType().getNonReferenceType();
4117 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004118 // the same as Entity.getDecl()->getType() in cases involving type merging,
4119 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004120 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004121 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004122 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004123
John McCalldadc5752010-08-24 06:29:42 +00004124 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004127 // grab the only argument out the Args and place it into the "current"
4128 // initializer.
4129 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004130 case SK_ResolveAddressOfOverloadedFunction:
4131 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004132 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004133 case SK_CastDerivedToBaseLValue:
4134 case SK_BindReference:
4135 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004136 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004137 case SK_UserConversion:
4138 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004139 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004140 case SK_QualificationConversionRValue:
4141 case SK_ConversionSequence:
4142 case SK_ListInitialization:
4143 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004144 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004145 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004146 case SK_ArrayInit:
4147 case SK_PassByIndirectCopyRestore:
4148 case SK_PassByIndirectRestore:
4149 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004150 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004151 CurInit = Args.get()[0];
4152 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004153
4154 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004155 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4156 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4157 if (CurInit.isInvalid())
4158 return ExprError();
4159 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004160 break;
John McCall34376a62010-12-04 03:47:34 +00004161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
Douglas Gregore1314a62009-12-18 05:02:21 +00004163 case SK_ConstructorInitialization:
4164 case SK_ZeroInitialization:
4165 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167
4168 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004169 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004170 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004171 for (step_iterator Step = step_begin(), StepEnd = step_end();
4172 Step != StepEnd; ++Step) {
4173 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004174 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
John Wiegley01296292011-04-08 18:41:53 +00004176 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004178 switch (Step->Kind) {
4179 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004182 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004183 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004184 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004185 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004186 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004187 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004189 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004190 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004191 case SK_CastDerivedToBaseLValue: {
4192 // We have a derived-to-base cast that produces either an rvalue or an
4193 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
John McCallcf142162010-08-07 06:22:56 +00004195 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004197 // Casts to inaccessible base classes are allowed with C-style casts.
4198 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4199 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004200 CurInit.get()->getLocStart(),
4201 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004202 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004203 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Douglas Gregor88d292c2010-05-13 16:44:06 +00004205 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4206 QualType T = SourceType;
4207 if (const PointerType *Pointer = T->getAs<PointerType>())
4208 T = Pointer->getPointeeType();
4209 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004210 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004211 cast<CXXRecordDecl>(RecordTy->getDecl()));
4212 }
4213
John McCall2536c6d2010-08-25 10:28:54 +00004214 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004215 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004216 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004217 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004218 VK_XValue :
4219 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004220 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4221 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004222 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004223 CurInit.get(),
4224 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004225 break;
4226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004228 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004229 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4231 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004232 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004234 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004235 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004236 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004237 }
Anders Carlssona91be642010-01-29 02:47:33 +00004238
John Wiegley01296292011-04-08 18:41:53 +00004239 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004240 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004241 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4242 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004243 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004244 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004245 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 // Reference binding does not have any corresponding ASTs.
4249
4250 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004251 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004252 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004253
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004256 case SK_BindReferenceToTemporary:
4257 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004258 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004259 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004260
Douglas Gregorfe314812011-06-21 17:03:29 +00004261 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004262 CurInit = new (S.Context) MaterializeTemporaryExpr(
4263 Entity.getType().getNonReferenceType(),
4264 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004265 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004266
4267 // If we're binding to an Objective-C object that has lifetime, we
4268 // need cleanups.
4269 if (S.getLangOptions().ObjCAutoRefCount &&
4270 CurInit.get()->getType()->isObjCLifetimeType())
4271 S.ExprNeedsCleanups = true;
4272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004275 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004277 /*IsExtraneousCopy=*/true);
4278 break;
4279
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 case SK_UserConversion: {
4281 // We have a user-defined conversion that invokes either a constructor
4282 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004283 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004284 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004285 FunctionDecl *Fn = Step->Function.Function;
4286 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004287 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004288 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004291 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004292 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004294
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004295 // Determine the arguments required to actually perform the constructor
4296 // call.
John Wiegley01296292011-04-08 18:41:53 +00004297 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004299 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004300 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004301 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004303 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004305 move_arg(ConstructorArgs),
4306 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004307 CXXConstructExpr::CK_Complete,
4308 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004310 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004311
Anders Carlssona01874b2010-04-21 18:47:17 +00004312 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004313 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004314 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
John McCalle3027922010-08-25 11:45:40 +00004316 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004317 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4318 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4319 S.IsDerivedFrom(SourceType, Class))
4320 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
Douglas Gregor95562572010-04-24 23:45:46 +00004322 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004323 } else {
4324 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004325 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004326 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004327 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004328 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004329 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
4331 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004332 // derived-to-base conversion? I believe the answer is "no", because
4333 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004334 ExprResult CurInitExprRes =
4335 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4336 FoundFn, Conversion);
4337 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004338 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004339 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004341 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004342 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004343 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004344 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
John McCalle3027922010-08-25 11:45:40 +00004346 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregor95562572010-04-24 23:45:46 +00004348 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Sebastian Redl112aa822011-07-14 19:07:55 +00004351 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004352 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004353 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004354 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004355 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004356 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004358 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004359 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004360 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004361 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4362 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004363 }
4364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004366 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004367 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004368 CurInit.get()->getType(),
4369 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004370 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004372 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004373 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4374 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004376 break;
4377 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004378
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004379 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004380 case SK_QualificationConversionXValue:
4381 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004382 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004383 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004384 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004385 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004386 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004387 VK_XValue :
4388 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004389 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004390 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004391 }
4392
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004393 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004394 Sema::CheckedConversionKind CCK
4395 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4396 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4397 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4398 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004399 ExprResult CurInitExprRes =
4400 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004401 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004402 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004403 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004404 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004405 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407
Douglas Gregor51e77d52009-12-10 17:56:55 +00004408 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004409 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004410 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004411 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004412 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004413
4414 CurInit.release();
4415 CurInit = S.Owned(InitList);
4416 break;
4417 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004418
4419 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004420 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004421 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004422 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004424 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004425 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004426 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4427 ? Kind.getEqualLoc()
4428 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004429
4430 if (Kind.getKind() == InitializationKind::IK_Default) {
4431 // Force even a trivial, implicit default constructor to be
4432 // semantically checked. We do this explicitly because we don't build
4433 // the definition for completely trivial constructors.
4434 CXXRecordDecl *ClassDecl = Constructor->getParent();
4435 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004436 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004437 ClassDecl->hasTrivialDefaultConstructor() &&
4438 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004439 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4440 }
4441
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004442 // Determine the arguments required to actually perform the constructor
4443 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004445 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004446 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447
4448
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004449 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004450 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004451 (Kind.getKind() == InitializationKind::IK_Direct ||
4452 Kind.getKind() == InitializationKind::IK_Value)) {
4453 // An explicitly-constructed temporary, e.g., X(1, 2).
4454 unsigned NumExprs = ConstructorArgs.size();
4455 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004456 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004457 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Douglas Gregor2b88c112010-09-08 00:15:04 +00004459 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4460 if (!TSInfo)
4461 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004463 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4464 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004465 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004467 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004468 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004469 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004470 } else {
4471 CXXConstructExpr::ConstructionKind ConstructKind =
4472 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004474 if (Entity.getKind() == InitializedEntity::EK_Base) {
4475 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004477 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004478 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004479 ConstructKind = CXXConstructExpr::CK_Delegating;
4480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Chandler Carruth01718152010-10-25 08:47:36 +00004482 // Only get the parenthesis range if it is a direct construction.
4483 SourceRange parenRange =
4484 Kind.getKind() == InitializationKind::IK_Direct ?
4485 Kind.getParenRange() : SourceRange();
4486
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004487 // If the entity allows NRVO, mark the construction as elidable
4488 // unconditionally.
4489 if (Entity.allowsNRVO())
4490 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4491 Constructor, /*Elidable=*/true,
4492 move_arg(ConstructorArgs),
4493 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004494 ConstructKind,
4495 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004496 else
4497 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004499 move_arg(ConstructorArgs),
4500 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004501 ConstructKind,
4502 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004503 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004504 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004505 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004506
4507 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004508 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004509 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004510 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004512 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004513 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004514
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004515 break;
4516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004518 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004519 step_iterator NextStep = Step;
4520 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004522 NextStep->Kind == SK_ConstructorInitialization) {
4523 // The need for zero-initialization is recorded directly into
4524 // the call to the object's constructor within the next step.
4525 ConstructorInitRequiresZeroInit = true;
4526 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4527 S.getLangOptions().CPlusPlus &&
4528 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004529 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4530 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004532 Kind.getRange().getBegin());
4533
4534 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4535 TSInfo->getType().getNonLValueExprType(S.Context),
4536 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004537 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004538 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004539 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004540 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004541 break;
4542 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004543
4544 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004545 QualType SourceType = CurInit.get()->getType();
4546 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004547 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004548 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4549 if (Result.isInvalid())
4550 return ExprError();
4551 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004552
4553 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004554 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004555 if (ConvTy != Sema::Compatible &&
4556 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004557 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004558 == Sema::Compatible)
4559 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004560 if (CurInitExprRes.isInvalid())
4561 return ExprError();
4562 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004563
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004564 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004565 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4566 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004567 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004568 getAssignmentAction(Entity),
4569 &Complained)) {
4570 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004571 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004572 } else if (Complained)
4573 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004574 break;
4575 }
Eli Friedman78275202009-12-19 08:11:05 +00004576
4577 case SK_StringInit: {
4578 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004579 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004580 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004581 break;
4582 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004583
4584 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004585 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004586 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004587 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004588 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004589
4590 case SK_ArrayInit:
4591 // Okay: we checked everything before creating this step. Note that
4592 // this is a GNU extension.
4593 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004594 << Step->Type << CurInit.get()->getType()
4595 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004596
4597 // If the destination type is an incomplete array type, update the
4598 // type accordingly.
4599 if (ResultType) {
4600 if (const IncompleteArrayType *IncompleteDest
4601 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4602 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004603 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004604 *ResultType = S.Context.getConstantArrayType(
4605 IncompleteDest->getElementType(),
4606 ConstantSource->getSize(),
4607 ArrayType::Normal, 0);
4608 }
4609 }
4610 }
John McCall31168b02011-06-15 23:02:42 +00004611 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004612
John McCall31168b02011-06-15 23:02:42 +00004613 case SK_PassByIndirectCopyRestore:
4614 case SK_PassByIndirectRestore:
4615 checkIndirectCopyRestoreSource(S, CurInit.get());
4616 CurInit = S.Owned(new (S.Context)
4617 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4618 Step->Kind == SK_PassByIndirectCopyRestore));
4619 break;
4620
4621 case SK_ProduceObjCObject:
4622 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4623 CK_ObjCProduceObject,
4624 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004625 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004626 }
4627 }
John McCall1f425642010-11-11 03:21:53 +00004628
4629 // Diagnose non-fatal problems with the completed initialization.
4630 if (Entity.getKind() == InitializedEntity::EK_Member &&
4631 cast<FieldDecl>(Entity.getDecl())->isBitField())
4632 S.CheckBitFieldInitialization(Kind.getLocation(),
4633 cast<FieldDecl>(Entity.getDecl()),
4634 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 return move(CurInit);
4637}
4638
4639//===----------------------------------------------------------------------===//
4640// Diagnose initialization failures
4641//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004643 const InitializedEntity &Entity,
4644 const InitializationKind &Kind,
4645 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004646 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004647 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Douglas Gregor1b303932009-12-22 15:35:07 +00004649 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004650 switch (Failure) {
4651 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004652 // FIXME: Customize for the initialized entity?
4653 if (NumArgs == 0)
4654 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4655 << DestType.getNonReferenceType();
4656 else // FIXME: diagnostic below could be better!
4657 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4658 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004659 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004661 case FK_ArrayNeedsInitList:
4662 case FK_ArrayNeedsInitListOrStringLiteral:
4663 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4664 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666
Douglas Gregore2f943b2011-02-22 18:29:51 +00004667 case FK_ArrayTypeMismatch:
4668 case FK_NonConstantArrayInit:
4669 S.Diag(Kind.getLocation(),
4670 (Failure == FK_ArrayTypeMismatch
4671 ? diag::err_array_init_different_type
4672 : diag::err_array_init_non_constant_array))
4673 << DestType.getNonReferenceType()
4674 << Args[0]->getType()
4675 << Args[0]->getSourceRange();
4676 break;
4677
John McCall16df1e52010-03-30 21:47:33 +00004678 case FK_AddressOfOverloadFailed: {
4679 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004681 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004682 true,
4683 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004684 break;
John McCall16df1e52010-03-30 21:47:33 +00004685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004687 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004688 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004689 switch (FailedOverloadResult) {
4690 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004691 if (Failure == FK_UserConversionOverloadFailed)
4692 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4693 << Args[0]->getType() << DestType
4694 << Args[0]->getSourceRange();
4695 else
4696 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4697 << DestType << Args[0]->getType()
4698 << Args[0]->getSourceRange();
4699
John McCall5c32be02010-08-24 20:38:10 +00004700 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004703 case OR_No_Viable_Function:
4704 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4705 << Args[0]->getType() << DestType.getNonReferenceType()
4706 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004707 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004708 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004710 case OR_Deleted: {
4711 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4712 << Args[0]->getType() << DestType.getNonReferenceType()
4713 << Args[0]->getSourceRange();
4714 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004715 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004716 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4717 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004718 if (Ovl == OR_Deleted) {
4719 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004720 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004721 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004722 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004723 }
4724 break;
4725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004727 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004728 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004729 break;
4730 }
4731 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004733 case FK_NonConstLValueReferenceBindingToTemporary:
4734 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004736 Failure == FK_NonConstLValueReferenceBindingToTemporary
4737 ? diag::err_lvalue_reference_bind_to_temporary
4738 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004739 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004740 << DestType.getNonReferenceType()
4741 << Args[0]->getType()
4742 << Args[0]->getSourceRange();
4743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004745 case FK_RValueReferenceBindingToLValue:
4746 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004747 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004748 << Args[0]->getSourceRange();
4749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004751 case FK_ReferenceInitDropsQualifiers:
4752 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4753 << DestType.getNonReferenceType()
4754 << Args[0]->getType()
4755 << Args[0]->getSourceRange();
4756 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004758 case FK_ReferenceInitFailed:
4759 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4760 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004761 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004762 << Args[0]->getType()
4763 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004764 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4765 Args[0]->getType()->isObjCObjectPointerType())
4766 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004767 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Douglas Gregorb491ed32011-02-19 21:32:49 +00004769 case FK_ConversionFailed: {
4770 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004771 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4772 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004773 << DestType
John McCall086a4642010-11-24 05:12:34 +00004774 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004775 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004776 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004777 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4778 Args[0]->getType()->isObjCObjectPointerType())
4779 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004780 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004781 }
John Wiegley01296292011-04-08 18:41:53 +00004782
4783 case FK_ConversionFromPropertyFailed:
4784 // No-op. This error has already been reported.
4785 break;
4786
Douglas Gregor51e77d52009-12-10 17:56:55 +00004787 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004788 SourceRange R;
4789
4790 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004791 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004792 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004793 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004794 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004795
Douglas Gregor8ec51732010-09-08 21:40:08 +00004796 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4797 if (Kind.isCStyleOrFunctionalCast())
4798 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4799 << R;
4800 else
4801 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4802 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004803 break;
4804 }
4805
4806 case FK_ReferenceBindingToInitList:
4807 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4808 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4809 break;
4810
4811 case FK_InitListBadDestinationType:
4812 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4813 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4814 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004816 case FK_ConstructorOverloadFailed: {
4817 SourceRange ArgsRange;
4818 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004820 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004822 // FIXME: Using "DestType" for the entity we're printing is probably
4823 // bad.
4824 switch (FailedOverloadResult) {
4825 case OR_Ambiguous:
4826 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4827 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004828 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4829 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004830 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004832 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004833 if (Kind.getKind() == InitializationKind::IK_Default &&
4834 (Entity.getKind() == InitializedEntity::EK_Base ||
4835 Entity.getKind() == InitializedEntity::EK_Member) &&
4836 isa<CXXConstructorDecl>(S.CurContext)) {
4837 // This is implicit default initialization of a member or
4838 // base within a constructor. If no viable function was
4839 // found, notify the user that she needs to explicitly
4840 // initialize this base/member.
4841 CXXConstructorDecl *Constructor
4842 = cast<CXXConstructorDecl>(S.CurContext);
4843 if (Entity.getKind() == InitializedEntity::EK_Base) {
4844 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4845 << Constructor->isImplicit()
4846 << S.Context.getTypeDeclType(Constructor->getParent())
4847 << /*base=*/0
4848 << Entity.getType();
4849
4850 RecordDecl *BaseDecl
4851 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4852 ->getDecl();
4853 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4854 << S.Context.getTagDeclType(BaseDecl);
4855 } else {
4856 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4857 << Constructor->isImplicit()
4858 << S.Context.getTypeDeclType(Constructor->getParent())
4859 << /*member=*/1
4860 << Entity.getName();
4861 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4862
4863 if (const RecordType *Record
4864 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004866 diag::note_previous_decl)
4867 << S.Context.getTagDeclType(Record->getDecl());
4868 }
4869 break;
4870 }
4871
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004872 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4873 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004874 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004875 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004877 case OR_Deleted: {
4878 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4879 << true << DestType << ArgsRange;
4880 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004881 OverloadingResult Ovl
4882 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004883 if (Ovl == OR_Deleted) {
4884 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004885 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004886 } else {
4887 llvm_unreachable("Inconsistent overload resolution?");
4888 }
4889 break;
4890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004892 case OR_Success:
4893 llvm_unreachable("Conversion did not fail!");
4894 break;
4895 }
4896 break;
4897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor85dabae2009-12-16 01:38:02 +00004899 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004900 if (Entity.getKind() == InitializedEntity::EK_Member &&
4901 isa<CXXConstructorDecl>(S.CurContext)) {
4902 // This is implicit default-initialization of a const member in
4903 // a constructor. Complain that it needs to be explicitly
4904 // initialized.
4905 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4906 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4907 << Constructor->isImplicit()
4908 << S.Context.getTypeDeclType(Constructor->getParent())
4909 << /*const=*/1
4910 << Entity.getName();
4911 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4912 << Entity.getName();
4913 } else {
4914 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4915 << DestType << (bool)DestType->getAs<RecordType>();
4916 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004917 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004919 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004921 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004925 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004926 return true;
4927}
Douglas Gregore1314a62009-12-18 05:02:21 +00004928
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004929void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004930 switch (SequenceKind) {
4931 case FailedSequence: {
4932 OS << "Failed sequence: ";
4933 switch (Failure) {
4934 case FK_TooManyInitsForReference:
4935 OS << "too many initializers for reference";
4936 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004938 case FK_ArrayNeedsInitList:
4939 OS << "array requires initializer list";
4940 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004942 case FK_ArrayNeedsInitListOrStringLiteral:
4943 OS << "array requires initializer list or string literal";
4944 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
Douglas Gregore2f943b2011-02-22 18:29:51 +00004946 case FK_ArrayTypeMismatch:
4947 OS << "array type mismatch";
4948 break;
4949
4950 case FK_NonConstantArrayInit:
4951 OS << "non-constant array initializer";
4952 break;
4953
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004954 case FK_AddressOfOverloadFailed:
4955 OS << "address of overloaded function failed";
4956 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004958 case FK_ReferenceInitOverloadFailed:
4959 OS << "overload resolution for reference initialization failed";
4960 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004962 case FK_NonConstLValueReferenceBindingToTemporary:
4963 OS << "non-const lvalue reference bound to temporary";
4964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004966 case FK_NonConstLValueReferenceBindingToUnrelated:
4967 OS << "non-const lvalue reference bound to unrelated type";
4968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004970 case FK_RValueReferenceBindingToLValue:
4971 OS << "rvalue reference bound to an lvalue";
4972 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004974 case FK_ReferenceInitDropsQualifiers:
4975 OS << "reference initialization drops qualifiers";
4976 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004978 case FK_ReferenceInitFailed:
4979 OS << "reference initialization failed";
4980 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004982 case FK_ConversionFailed:
4983 OS << "conversion failed";
4984 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
John Wiegley01296292011-04-08 18:41:53 +00004986 case FK_ConversionFromPropertyFailed:
4987 OS << "conversion from property failed";
4988 break;
4989
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004990 case FK_TooManyInitsForScalar:
4991 OS << "too many initializers for scalar";
4992 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004994 case FK_ReferenceBindingToInitList:
4995 OS << "referencing binding to initializer list";
4996 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004998 case FK_InitListBadDestinationType:
4999 OS << "initializer list for non-aggregate, non-scalar type";
5000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005002 case FK_UserConversionOverloadFailed:
5003 OS << "overloading failed for user-defined conversion";
5004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005006 case FK_ConstructorOverloadFailed:
5007 OS << "constructor overloading failed";
5008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005010 case FK_DefaultInitOfConst:
5011 OS << "default initialization of a const variable";
5012 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005014 case FK_Incomplete:
5015 OS << "initialization of incomplete type";
5016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005018 OS << '\n';
5019 return;
5020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005022 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005023 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005024 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
Sebastian Redld201edf2011-06-05 13:59:11 +00005026 case NormalSequence:
5027 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005028 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005031 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5032 if (S != step_begin()) {
5033 OS << " -> ";
5034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005036 switch (S->Kind) {
5037 case SK_ResolveAddressOfOverloadedFunction:
5038 OS << "resolve address of overloaded function";
5039 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005041 case SK_CastDerivedToBaseRValue:
5042 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5043 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005045 case SK_CastDerivedToBaseXValue:
5046 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5047 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005049 case SK_CastDerivedToBaseLValue:
5050 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005053 case SK_BindReference:
5054 OS << "bind reference to lvalue";
5055 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005057 case SK_BindReferenceToTemporary:
5058 OS << "bind reference to a temporary";
5059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005061 case SK_ExtraneousCopyToTemporary:
5062 OS << "extraneous C++03 copy to temporary";
5063 break;
5064
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005065 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005066 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005067 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005068
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005069 case SK_QualificationConversionRValue:
5070 OS << "qualification conversion (rvalue)";
5071
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005072 case SK_QualificationConversionXValue:
5073 OS << "qualification conversion (xvalue)";
5074
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005075 case SK_QualificationConversionLValue:
5076 OS << "qualification conversion (lvalue)";
5077 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005079 case SK_ConversionSequence:
5080 OS << "implicit conversion sequence (";
5081 S->ICS->DebugPrint(); // FIXME: use OS
5082 OS << ")";
5083 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005085 case SK_ListInitialization:
5086 OS << "list initialization";
5087 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005089 case SK_ConstructorInitialization:
5090 OS << "constructor initialization";
5091 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005093 case SK_ZeroInitialization:
5094 OS << "zero initialization";
5095 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005097 case SK_CAssignment:
5098 OS << "C assignment";
5099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005101 case SK_StringInit:
5102 OS << "string initialization";
5103 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005104
5105 case SK_ObjCObjectConversion:
5106 OS << "Objective-C object conversion";
5107 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005108
5109 case SK_ArrayInit:
5110 OS << "array initialization";
5111 break;
John McCall31168b02011-06-15 23:02:42 +00005112
5113 case SK_PassByIndirectCopyRestore:
5114 OS << "pass by indirect copy and restore";
5115 break;
5116
5117 case SK_PassByIndirectRestore:
5118 OS << "pass by indirect restore";
5119 break;
5120
5121 case SK_ProduceObjCObject:
5122 OS << "Objective-C object retension";
5123 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005124 }
5125 }
5126}
5127
5128void InitializationSequence::dump() const {
5129 dump(llvm::errs());
5130}
5131
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005132static void DiagnoseNarrowingInInitList(
5133 Sema& S, QualType EntityType, const Expr *InitE,
5134 bool Constant, const APValue &ConstantValue) {
5135 if (Constant) {
5136 S.Diag(InitE->getLocStart(),
5137 S.getLangOptions().CPlusPlus0x
5138 ? diag::err_init_list_constant_narrowing
5139 : diag::warn_init_list_constant_narrowing)
5140 << InitE->getSourceRange()
5141 << ConstantValue
5142 << EntityType;
5143 } else
5144 S.Diag(InitE->getLocStart(),
5145 S.getLangOptions().CPlusPlus0x
5146 ? diag::err_init_list_variable_narrowing
5147 : diag::warn_init_list_variable_narrowing)
5148 << InitE->getSourceRange()
5149 << InitE->getType()
5150 << EntityType;
5151
5152 llvm::SmallString<128> StaticCast;
5153 llvm::raw_svector_ostream OS(StaticCast);
5154 OS << "static_cast<";
5155 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5156 // It's important to use the typedef's name if there is one so that the
5157 // fixit doesn't break code using types like int64_t.
5158 //
5159 // FIXME: This will break if the typedef requires qualification. But
5160 // getQualifiedNameAsString() includes non-machine-parsable components.
5161 OS << TT->getDecl();
5162 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5163 OS << BT->getName(S.getLangOptions());
5164 else {
5165 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5166 // with a broken cast.
5167 return;
5168 }
5169 OS << ">(";
5170 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5171 << InitE->getSourceRange()
5172 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5173 << FixItHint::CreateInsertion(
5174 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5175}
5176
Douglas Gregore1314a62009-12-18 05:02:21 +00005177//===----------------------------------------------------------------------===//
5178// Initialization helper functions
5179//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005180bool
5181Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5182 ExprResult Init) {
5183 if (Init.isInvalid())
5184 return false;
5185
5186 Expr *InitE = Init.get();
5187 assert(InitE && "No initialization expression");
5188
5189 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5190 SourceLocation());
5191 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005192 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005193}
5194
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005196Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5197 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005198 ExprResult Init,
5199 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005200 if (Init.isInvalid())
5201 return ExprError();
5202
John McCall1f425642010-11-11 03:21:53 +00005203 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005204 assert(InitE && "No initialization expression?");
5205
5206 if (EqualLoc.isInvalid())
5207 EqualLoc = InitE->getLocStart();
5208
5209 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5210 EqualLoc);
5211 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5212 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005213
5214 bool Constant = false;
5215 APValue Result;
5216 if (TopLevelOfInitList &&
5217 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5218 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5219 Constant, Result);
5220 }
John McCallfaf5fb42010-08-26 23:41:50 +00005221 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005222}