blob: 1638693a2c61d2a3c7189d4d2b83d8e38ce68f13 [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//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.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());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner9ececce2009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000275
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor2bb07652009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCalldadc5752010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000346}
347
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351void
Douglas Gregor723796a2009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump11289f42009-09-09 15:08:12 +0000391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000409 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCalldadc5752010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redld201edf2011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000471
Douglas Gregor723796a2009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000477
Eli Friedman23a9e312008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000485
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Anders Carlsson6cabf312010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000533 else
David Blaikie83d382b2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000535
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000552
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000565
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000589 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000590 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000591}
592
Anders Carlsson6cabf312010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613
Eli Friedman85f54972008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000632 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman425038c2009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000655
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 }
659 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000660
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 } else if (DeclType->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000731 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000732 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000736 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson6cabf312010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000758 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000766
John McCall5decec92011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
John McCall5decec92011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000778 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 }
John McCall5decec92011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000801
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 }
John McCall5decec92011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley01296292011-04-08 18:41:53 +0000836 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCall5decec92011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000863}
864
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000917 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 }
John McCall643169b2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCall643169b2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
John McCall643169b2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001027}
1028
Anders Carlsson6cabf312010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001038
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall6a16b2f2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
John McCall6a16b2f2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001073 }
1074 }
John McCall6a16b2f2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
John McCall6a16b2f2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001092 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
John McCall6a16b2f2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
John McCall6a16b2f2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
John McCall6a16b2f2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall6a16b2f2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
1143
Anders Carlsson6cabf312010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCall66884dd2011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCall66884dd2011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001233 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001270}
1271
Eli Friedman3fa64df2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson6cabf312010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001321
Eli Friedman23a9e312008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump11289f42009-09-09 15:08:12 +00001327 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001363
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregora9add4e2009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregora9add4e2009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor51695702009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001396 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001397 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001398
Douglas Gregora82064c2011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001418
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001425 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001426
John McCalle40b58e2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 return;
1457
Eli Friedman3fa64df2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474}
Steve Narofff8ecff22008-05-01 22:18:59 +00001475
Douglas Gregord5846a12009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregord5846a12009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506}
Mike Stump11289f42009-09-09 15:08:12 +00001507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001514 while (IndirectFieldDecl *IF =
1515 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001516 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1517 return IF;
1518 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001519 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001520 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001521}
1522
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001523static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1524 DesignatedInitExpr *DIE) {
1525 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1526 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1527 for (unsigned I = 0; I < NumIndexExprs; ++I)
1528 IndexExprs[I] = DIE->getSubExpr(I + 1);
1529 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1530 DIE->size(), IndexExprs.data(),
1531 NumIndexExprs, DIE->getEqualOrColonLoc(),
1532 DIE->usesGNUSyntax(), DIE->getInit());
1533}
1534
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001535namespace {
1536
1537// Callback to only accept typo corrections that are for field members of
1538// the given struct or union.
1539class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1540 public:
1541 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1542 : Record(RD) {}
1543
1544 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1545 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1546 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1547 }
1548
1549 private:
1550 RecordDecl *Record;
1551};
1552
1553}
1554
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001555/// @brief Check the well-formedness of a C99 designated initializer.
1556///
1557/// Determines whether the designated initializer @p DIE, which
1558/// resides at the given @p Index within the initializer list @p
1559/// IList, is well-formed for a current object of type @p DeclType
1560/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001561/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001562/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001563///
1564/// @param IList The initializer list in which this designated
1565/// initializer occurs.
1566///
Douglas Gregora5324162009-04-15 04:56:10 +00001567/// @param DIE The designated initializer expression.
1568///
1569/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001570///
1571/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1572/// into which the designation in @p DIE should refer.
1573///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574/// @param NextField If non-NULL and the first designator in @p DIE is
1575/// a field, this will be set to the field declaration corresponding
1576/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001577///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578/// @param NextElementIndex If non-NULL and the first designator in @p
1579/// DIE is an array designator or GNU array-range designator, this
1580/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001581///
1582/// @param Index Index into @p IList where the designated initializer
1583/// @p DIE occurs.
1584///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001585/// @param StructuredList The initializer list expression that
1586/// describes all of the subobject initializers in the order they'll
1587/// actually be initialized.
1588///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001589/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001590bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001592 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001593 DesignatedInitExpr *DIE,
1594 unsigned DesigIdx,
1595 QualType &CurrentObjectType,
1596 RecordDecl::field_iterator *NextField,
1597 llvm::APSInt *NextElementIndex,
1598 unsigned &Index,
1599 InitListExpr *StructuredList,
1600 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001601 bool FinishSubobjectInit,
1602 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001603 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604 // Check the actual initialization for the designated object type.
1605 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001606
1607 // Temporarily remove the designator expression from the
1608 // initializer list that the child calls see, so that we don't try
1609 // to re-process the designator.
1610 unsigned OldIndex = Index;
1611 IList->setInit(OldIndex, DIE->getInit());
1612
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001613 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001614 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001615
1616 // Restore the designated initializer expression in the syntactic
1617 // form of the initializer list.
1618 if (IList->getInit(OldIndex) != DIE->getInit())
1619 DIE->setInit(IList->getInit(OldIndex));
1620 IList->setInit(OldIndex, DIE);
1621
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001623 }
1624
Douglas Gregora5324162009-04-15 04:56:10 +00001625 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001626 bool IsFirstDesignator = (DesigIdx == 0);
1627 if (!VerifyOnly) {
1628 assert((IsFirstDesignator || StructuredList) &&
1629 "Need a non-designated initializer list to start from");
1630
1631 // Determine the structural initializer list that corresponds to the
1632 // current subobject.
1633 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1634 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1635 StructuredList, StructuredIndex,
1636 SourceRange(D->getStartLocation(),
1637 DIE->getSourceRange().getEnd()));
1638 assert(StructuredList && "Expected a structured initializer list");
1639 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001640
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001641 if (D->isFieldDesignator()) {
1642 // C99 6.7.8p7:
1643 //
1644 // If a designator has the form
1645 //
1646 // . identifier
1647 //
1648 // then the current object (defined below) shall have
1649 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001650 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001651 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 if (!RT) {
1653 SourceLocation Loc = D->getDotLoc();
1654 if (Loc.isInvalid())
1655 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001656 if (!VerifyOnly)
1657 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1658 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001659 ++Index;
1660 return true;
1661 }
1662
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 // Note: we perform a linear search of the fields here, despite
1664 // the fact that we have a faster lookup method, because we always
1665 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001666 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001669 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001670 Field = RT->getDecl()->field_begin(),
1671 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001672 for (; Field != FieldEnd; ++Field) {
1673 if (Field->isUnnamedBitfield())
1674 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001676 // If we find a field representing an anonymous field, look in the
1677 // IndirectFieldDecl that follow for the designated initializer.
1678 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1679 if (IndirectFieldDecl *IF =
1680 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001681 // In verify mode, don't modify the original.
1682 if (VerifyOnly)
1683 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001684 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1685 D = DIE->getDesignator(DesigIdx);
1686 break;
1687 }
1688 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001689 if (KnownField && KnownField == *Field)
1690 break;
1691 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001692 break;
1693
1694 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001695 }
1696
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001697 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001698 if (VerifyOnly) {
1699 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001700 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001701 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702
Douglas Gregord5846a12009-04-15 06:41:24 +00001703 // There was no normal field in the struct with the designated
1704 // name. Perform another lookup for this name, which may find
1705 // something that we can't designate (e.g., a member function),
1706 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001707 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001708 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001709 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001711 // Name lookup didn't find anything. Determine whether this
1712 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001713 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001714 TypoCorrection Corrected = SemaRef.CorrectTypo(
1715 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001716 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001717 RT->getDecl());
1718 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001719 std::string CorrectedStr(
1720 Corrected.getAsString(SemaRef.getLangOptions()));
1721 std::string CorrectedQuotedStr(
1722 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001723 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001724 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001725 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001726 << FieldName << CurrentObjectType << CorrectedQuotedStr
1727 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001729 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001730 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001731 } else {
1732 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1733 << FieldName << CurrentObjectType;
1734 ++Index;
1735 return true;
1736 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001739 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001741 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001742 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001743 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001745 ++Index;
1746 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001747 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001748
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001749 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001750 // The replacement field comes from typo correction; find it
1751 // in the list of fields.
1752 FieldIndex = 0;
1753 Field = RT->getDecl()->field_begin();
1754 for (; Field != FieldEnd; ++Field) {
1755 if (Field->isUnnamedBitfield())
1756 continue;
1757
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001759 Field->getIdentifier() == ReplacementField->getIdentifier())
1760 break;
1761
1762 ++FieldIndex;
1763 }
1764 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001765 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001766
1767 // All of the fields of a union are located at the same place in
1768 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001769 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001770 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001771 if (!VerifyOnly)
1772 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001773 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001774
Douglas Gregora82064c2011-06-29 21:51:31 +00001775 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001776 bool InvalidUse;
1777 if (VerifyOnly)
1778 InvalidUse = !SemaRef.CanUseDecl(*Field);
1779 else
1780 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1781 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001782 ++Index;
1783 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001784 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001785
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001786 if (!VerifyOnly) {
1787 // Update the designator with the field declaration.
1788 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001790 // Make sure that our non-designated initializer list has space
1791 // for a subobject corresponding to this field.
1792 if (FieldIndex >= StructuredList->getNumInits())
1793 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1794 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001796 // This designator names a flexible array member.
1797 if (Field->getType()->isIncompleteArrayType()) {
1798 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001799 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001800 // We can't designate an object within the flexible array
1801 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001802 if (!VerifyOnly) {
1803 DesignatedInitExpr::Designator *NextD
1804 = DIE->getDesignator(DesigIdx + 1);
1805 SemaRef.Diag(NextD->getStartLocation(),
1806 diag::err_designator_into_flexible_array_member)
1807 << SourceRange(NextD->getStartLocation(),
1808 DIE->getSourceRange().getEnd());
1809 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1810 << *Field;
1811 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001812 Invalid = true;
1813 }
1814
Chris Lattner001b29c2010-10-10 17:49:49 +00001815 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1816 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001817 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001818 if (!VerifyOnly) {
1819 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1820 diag::err_flexible_array_init_needs_braces)
1821 << DIE->getInit()->getSourceRange();
1822 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1823 << *Field;
1824 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001825 Invalid = true;
1826 }
1827
Eli Friedman3fa64df2011-08-23 22:24:57 +00001828 // Check GNU flexible array initializer.
1829 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1830 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001832
1833 if (Invalid) {
1834 ++Index;
1835 return true;
1836 }
1837
1838 // Initialize the array.
1839 bool prevHadError = hadError;
1840 unsigned newStructuredIndex = FieldIndex;
1841 unsigned OldIndex = Index;
1842 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001843
1844 InitializedEntity MemberEntity =
1845 InitializedEntity::InitializeMember(*Field, &Entity);
1846 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001847 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001848
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001849 IList->setInit(OldIndex, DIE);
1850 if (hadError && !prevHadError) {
1851 ++Field;
1852 ++FieldIndex;
1853 if (NextField)
1854 *NextField = Field;
1855 StructuredIndex = FieldIndex;
1856 return true;
1857 }
1858 } else {
1859 // Recurse to check later designated subobjects.
1860 QualType FieldType = (*Field)->getType();
1861 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001863 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001864 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1866 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001867 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001868 true, false))
1869 return true;
1870 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871
1872 // Find the position of the next field to be initialized in this
1873 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001875 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001876
1877 // If this the first designator, our caller will continue checking
1878 // the rest of this struct/class/union subobject.
1879 if (IsFirstDesignator) {
1880 if (NextField)
1881 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001882 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001883 return false;
1884 }
1885
Douglas Gregor17bd0942009-01-28 23:36:17 +00001886 if (!FinishSubobjectInit)
1887 return false;
1888
Douglas Gregord5846a12009-04-15 06:41:24 +00001889 // We've already initialized something in the union; we're done.
1890 if (RT->getDecl()->isUnion())
1891 return hadError;
1892
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001893 // Check the remaining fields within this class/struct/union subobject.
1894 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Anders Carlsson6cabf312010-01-23 23:23:01 +00001896 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001897 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001898 return hadError && !prevHadError;
1899 }
1900
1901 // C99 6.7.8p6:
1902 //
1903 // If a designator has the form
1904 //
1905 // [ constant-expression ]
1906 //
1907 // then the current object (defined below) shall have array
1908 // type and the expression shall be an integer constant
1909 // expression. If the array is of unknown size, any
1910 // nonnegative value is valid.
1911 //
1912 // Additionally, cope with the GNU extension that permits
1913 // designators of the form
1914 //
1915 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001916 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001917 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001918 if (!VerifyOnly)
1919 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1920 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001921 ++Index;
1922 return true;
1923 }
1924
1925 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001926 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1927 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001928 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001929 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001930 DesignatedEndIndex = DesignatedStartIndex;
1931 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001932 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001933
Mike Stump11289f42009-09-09 15:08:12 +00001934 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001935 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001936 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001937 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001938 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001939
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001940 // Codegen can't handle evaluating array range designators that have side
1941 // effects, because we replicate the AST value for each initialized element.
1942 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1943 // elements with something that has a side effect, so codegen can emit an
1944 // "error unsupported" error instead of miscompiling the app.
1945 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001946 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001947 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001948 }
1949
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001950 if (isa<ConstantArrayType>(AT)) {
1951 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001952 DesignatedStartIndex
1953 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001955 DesignatedEndIndex
1956 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001957 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1958 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001959 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001960 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1961 diag::err_array_designator_too_large)
1962 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1963 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001964 ++Index;
1965 return true;
1966 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001967 } else {
1968 // Make sure the bit-widths and signedness match.
1969 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001970 DesignatedEndIndex
1971 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001972 else if (DesignatedStartIndex.getBitWidth() <
1973 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001974 DesignatedStartIndex
1975 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001976 DesignatedStartIndex.setIsUnsigned(true);
1977 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001978 }
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001980 // Make sure that our non-designated initializer list has space
1981 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001982 if (!VerifyOnly &&
1983 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001984 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001985 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001986
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 // Repeatedly perform subobject initializations in the range
1988 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001989
Douglas Gregor17bd0942009-01-28 23:36:17 +00001990 // Move to the next designator
1991 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1992 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001994 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001995 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001996
Douglas Gregor17bd0942009-01-28 23:36:17 +00001997 while (DesignatedStartIndex <= DesignatedEndIndex) {
1998 // Recurse to check later designated subobjects.
1999 QualType ElementType = AT->getElementType();
2000 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002002 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2004 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002005 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002006 (DesignatedStartIndex == DesignatedEndIndex),
2007 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002008 return true;
2009
2010 // Move to the next index in the array that we'll be initializing.
2011 ++DesignatedStartIndex;
2012 ElementIndex = DesignatedStartIndex.getZExtValue();
2013 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002014
2015 // If this the first designator, our caller will continue checking
2016 // the rest of this array subobject.
2017 if (IsFirstDesignator) {
2018 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002019 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002021 return false;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregor17bd0942009-01-28 23:36:17 +00002024 if (!FinishSubobjectInit)
2025 return false;
2026
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002027 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002028 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002030 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002031 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002032 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002033}
2034
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002035// Get the structured initializer list for a subobject of type
2036// @p CurrentObjectType.
2037InitListExpr *
2038InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2039 QualType CurrentObjectType,
2040 InitListExpr *StructuredList,
2041 unsigned StructuredIndex,
2042 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002043 if (VerifyOnly)
2044 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002045 Expr *ExistingInit = 0;
2046 if (!StructuredList)
2047 ExistingInit = SyntacticToSemantic[IList];
2048 else if (StructuredIndex < StructuredList->getNumInits())
2049 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002051 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2052 return Result;
2053
2054 if (ExistingInit) {
2055 // We are creating an initializer list that initializes the
2056 // subobjects of the current object, but there was already an
2057 // initialization that completely initialized the current
2058 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002059 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060 // struct X { int a, b; };
2061 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002062 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002063 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2064 // designated initializer re-initializes the whole
2065 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002066 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002067 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002068 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002069 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002071 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002072 << ExistingInit->getSourceRange();
2073 }
2074
Mike Stump11289f42009-09-09 15:08:12 +00002075 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002076 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2077 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002078 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002079
Douglas Gregora8a089b2010-07-13 18:40:04 +00002080 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002081
Douglas Gregor6d00c992009-03-20 23:58:33 +00002082 // Pre-allocate storage for the structured initializer list.
2083 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002084 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002085 bool GotNumInits = false;
2086 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002087 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002088 GotNumInits = true;
2089 } else if (Index < IList->getNumInits()) {
2090 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002091 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002092 GotNumInits = true;
2093 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002094 }
2095
Mike Stump11289f42009-09-09 15:08:12 +00002096 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002097 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2098 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2099 NumElements = CAType->getSize().getZExtValue();
2100 // Simple heuristic so that we don't allocate a very large
2101 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002102 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002103 NumElements = 0;
2104 }
John McCall9dd450b2009-09-21 23:43:11 +00002105 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002106 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002108 RecordDecl *RDecl = RType->getDecl();
2109 if (RDecl->isUnion())
2110 NumElements = 1;
2111 else
Mike Stump11289f42009-09-09 15:08:12 +00002112 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002113 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002114 }
2115
Ted Kremenekac034612010-04-13 23:39:13 +00002116 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002117
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002118 // Link this new initializer list into the structured initializer
2119 // lists.
2120 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002121 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002122 else {
2123 Result->setSyntacticForm(IList);
2124 SyntacticToSemantic[IList] = Result;
2125 }
2126
2127 return Result;
2128}
2129
2130/// Update the initializer at index @p StructuredIndex within the
2131/// structured initializer list to the value @p expr.
2132void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2133 unsigned &StructuredIndex,
2134 Expr *expr) {
2135 // No structured initializer list to update
2136 if (!StructuredList)
2137 return;
2138
Ted Kremenekac034612010-04-13 23:39:13 +00002139 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2140 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002141 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002142 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 diag::warn_initializer_overrides)
2144 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002145 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002146 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002147 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002148 << PrevInit->getSourceRange();
2149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002151 ++StructuredIndex;
2152}
2153
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002154/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002155/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002156/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002157/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002158/// failure. Returns the index expression, possibly with an implicit cast
2159/// added, on success. If everything went okay, Value will receive the
2160/// value of the constant expression.
2161static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002162CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002163 SourceLocation Loc = Index->getSourceRange().getBegin();
2164
2165 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002166 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2167 if (Result.isInvalid())
2168 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002169
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002170 if (Value.isSigned() && Value.isNegative())
2171 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002172 << Value.toString(10) << Index->getSourceRange();
2173
Douglas Gregor51650d32009-01-23 21:04:18 +00002174 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002175 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002176}
2177
John McCalldadc5752010-08-24 06:29:42 +00002178ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002179 SourceLocation Loc,
2180 bool GNUSyntax,
2181 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002182 typedef DesignatedInitExpr::Designator ASTDesignator;
2183
2184 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002185 SmallVector<ASTDesignator, 32> Designators;
2186 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002187
2188 // Build designators and check array designator expressions.
2189 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2190 const Designator &D = Desig.getDesignator(Idx);
2191 switch (D.getKind()) {
2192 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002193 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002194 D.getFieldLoc()));
2195 break;
2196
2197 case Designator::ArrayDesignator: {
2198 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2199 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002200 if (!Index->isTypeDependent() && !Index->isValueDependent())
2201 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2202 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002203 Invalid = true;
2204 else {
2205 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002206 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002207 D.getRBracketLoc()));
2208 InitExpressions.push_back(Index);
2209 }
2210 break;
2211 }
2212
2213 case Designator::ArrayRangeDesignator: {
2214 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2215 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2216 llvm::APSInt StartValue;
2217 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002218 bool StartDependent = StartIndex->isTypeDependent() ||
2219 StartIndex->isValueDependent();
2220 bool EndDependent = EndIndex->isTypeDependent() ||
2221 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002222 if (!StartDependent)
2223 StartIndex =
2224 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2225 if (!EndDependent)
2226 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2227
2228 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002229 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002230 else {
2231 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002232 if (StartDependent || EndDependent) {
2233 // Nothing to compute.
2234 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002235 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002236 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002237 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002238
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002239 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002240 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002241 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002242 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2243 Invalid = true;
2244 } else {
2245 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002246 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002247 D.getEllipsisLoc(),
2248 D.getRBracketLoc()));
2249 InitExpressions.push_back(StartIndex);
2250 InitExpressions.push_back(EndIndex);
2251 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002252 }
2253 break;
2254 }
2255 }
2256 }
2257
2258 if (Invalid || Init.isInvalid())
2259 return ExprError();
2260
2261 // Clear out the expressions within the designation.
2262 Desig.ClearExprs(*this);
2263
2264 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002265 = DesignatedInitExpr::Create(Context,
2266 Designators.data(), Designators.size(),
2267 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002268 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269
Richard Smithe4345902011-12-29 21:57:33 +00002270 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002271 Diag(DIE->getLocStart(), diag::ext_designated_init)
2272 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002273
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002274 return Owned(DIE);
2275}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002277//===----------------------------------------------------------------------===//
2278// Initialization entity
2279//===----------------------------------------------------------------------===//
2280
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002282 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002284{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002285 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2286 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002287 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002288 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002289 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002290 Type = VT->getElementType();
2291 } else {
2292 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2293 assert(CT && "Unexpected type");
2294 Kind = EK_ComplexElement;
2295 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002296 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002297}
2298
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002300 CXXBaseSpecifier *Base,
2301 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002302{
2303 InitializedEntity Result;
2304 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002305 Result.Base = reinterpret_cast<uintptr_t>(Base);
2306 if (IsInheritedVirtualBase)
2307 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
Douglas Gregor1b303932009-12-22 15:35:07 +00002309 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310 return Result;
2311}
2312
Douglas Gregor85dabae2009-12-16 01:38:02 +00002313DeclarationName InitializedEntity::getName() const {
2314 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002315 case EK_Parameter: {
2316 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2317 return (D ? D->getDeclName() : DeclarationName());
2318 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002319
2320 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002321 case EK_Member:
2322 return VariableOrMember->getDeclName();
2323
Douglas Gregor19666fb2012-02-15 16:57:26 +00002324 case EK_LambdaCapture:
2325 return Capture.Var->getDeclName();
2326
Douglas Gregor85dabae2009-12-16 01:38:02 +00002327 case EK_Result:
2328 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002329 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002330 case EK_Temporary:
2331 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002332 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002333 case EK_ArrayElement:
2334 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002335 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002336 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337 return DeclarationName();
2338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002339
David Blaikie8a40f702012-01-17 06:56:22 +00002340 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002341}
2342
Douglas Gregora4b592a2009-12-19 03:01:41 +00002343DeclaratorDecl *InitializedEntity::getDecl() const {
2344 switch (getKind()) {
2345 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002346 case EK_Member:
2347 return VariableOrMember;
2348
John McCall31168b02011-06-15 23:02:42 +00002349 case EK_Parameter:
2350 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2351
Douglas Gregora4b592a2009-12-19 03:01:41 +00002352 case EK_Result:
2353 case EK_Exception:
2354 case EK_New:
2355 case EK_Temporary:
2356 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002357 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002358 case EK_ArrayElement:
2359 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002360 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002361 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002362 case EK_LambdaCapture:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002363 return 0;
2364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
David Blaikie8a40f702012-01-17 06:56:22 +00002366 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002367}
2368
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002369bool InitializedEntity::allowsNRVO() const {
2370 switch (getKind()) {
2371 case EK_Result:
2372 case EK_Exception:
2373 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002375 case EK_Variable:
2376 case EK_Parameter:
2377 case EK_Member:
2378 case EK_New:
2379 case EK_Temporary:
2380 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002381 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002382 case EK_ArrayElement:
2383 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002384 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002385 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002386 case EK_LambdaCapture:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002387 break;
2388 }
2389
2390 return false;
2391}
2392
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002393//===----------------------------------------------------------------------===//
2394// Initialization sequence
2395//===----------------------------------------------------------------------===//
2396
2397void InitializationSequence::Step::Destroy() {
2398 switch (Kind) {
2399 case SK_ResolveAddressOfOverloadedFunction:
2400 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002401 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 case SK_CastDerivedToBaseLValue:
2403 case SK_BindReference:
2404 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002405 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 case SK_UserConversion:
2407 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002408 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002409 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002410 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002411 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002412 case SK_UnwrapInitList:
2413 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002414 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002415 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002416 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002417 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002418 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002419 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002420 case SK_PassByIndirectCopyRestore:
2421 case SK_PassByIndirectRestore:
2422 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002423 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002424 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002426 case SK_ConversionSequence:
2427 delete ICS;
2428 }
2429}
2430
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002432 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433}
2434
2435bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002436 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002437 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438
Douglas Gregor838fcc32010-03-26 20:14:36 +00002439 switch (getFailureKind()) {
2440 case FK_TooManyInitsForReference:
2441 case FK_ArrayNeedsInitList:
2442 case FK_ArrayNeedsInitListOrStringLiteral:
2443 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2444 case FK_NonConstLValueReferenceBindingToTemporary:
2445 case FK_NonConstLValueReferenceBindingToUnrelated:
2446 case FK_RValueReferenceBindingToLValue:
2447 case FK_ReferenceInitDropsQualifiers:
2448 case FK_ReferenceInitFailed:
2449 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002450 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002451 case FK_TooManyInitsForScalar:
2452 case FK_ReferenceBindingToInitList:
2453 case FK_InitListBadDestinationType:
2454 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002455 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002456 case FK_ArrayTypeMismatch:
2457 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002458 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002459 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002460 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002461 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002462 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
Douglas Gregor838fcc32010-03-26 20:14:36 +00002464 case FK_ReferenceInitOverloadFailed:
2465 case FK_UserConversionOverloadFailed:
2466 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002467 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002468 return FailedOverloadResult == OR_Ambiguous;
2469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470
David Blaikie8a40f702012-01-17 06:56:22 +00002471 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002472}
2473
Douglas Gregorb33eed02010-04-16 22:09:46 +00002474bool InitializationSequence::isConstructorInitialization() const {
2475 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2476}
2477
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002478void
2479InitializationSequence
2480::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2481 DeclAccessPair Found,
2482 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 Step S;
2484 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2485 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002486 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002487 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002488 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489 Steps.push_back(S);
2490}
2491
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002493 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002495 switch (VK) {
2496 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2497 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2498 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002499 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002500 S.Type = BaseType;
2501 Steps.push_back(S);
2502}
2503
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002504void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 bool BindingTemporary) {
2506 Step S;
2507 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2508 S.Type = T;
2509 Steps.push_back(S);
2510}
2511
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002512void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2513 Step S;
2514 S.Kind = SK_ExtraneousCopyToTemporary;
2515 S.Type = T;
2516 Steps.push_back(S);
2517}
2518
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002519void
2520InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2521 DeclAccessPair FoundDecl,
2522 QualType T,
2523 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 Step S;
2525 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002526 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002527 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002528 S.Function.Function = Function;
2529 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002530 Steps.push_back(S);
2531}
2532
2533void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002534 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002535 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002536 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002537 switch (VK) {
2538 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 S.Kind = SK_QualificationConversionRValue;
2540 break;
John McCall2536c6d2010-08-25 10:28:54 +00002541 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002542 S.Kind = SK_QualificationConversionXValue;
2543 break;
John McCall2536c6d2010-08-25 10:28:54 +00002544 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002545 S.Kind = SK_QualificationConversionLValue;
2546 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002547 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002548 S.Type = Ty;
2549 Steps.push_back(S);
2550}
2551
2552void InitializationSequence::AddConversionSequenceStep(
2553 const ImplicitConversionSequence &ICS,
2554 QualType T) {
2555 Step S;
2556 S.Kind = SK_ConversionSequence;
2557 S.Type = T;
2558 S.ICS = new ImplicitConversionSequence(ICS);
2559 Steps.push_back(S);
2560}
2561
Douglas Gregor51e77d52009-12-10 17:56:55 +00002562void InitializationSequence::AddListInitializationStep(QualType T) {
2563 Step S;
2564 S.Kind = SK_ListInitialization;
2565 S.Type = T;
2566 Steps.push_back(S);
2567}
2568
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002570InitializationSequence
2571::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2572 AccessSpecifier Access,
2573 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002574 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002575 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002576 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002577 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2578 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002579 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002580 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002581 S.Function.Function = Constructor;
2582 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002583 Steps.push_back(S);
2584}
2585
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002586void InitializationSequence::AddZeroInitializationStep(QualType T) {
2587 Step S;
2588 S.Kind = SK_ZeroInitialization;
2589 S.Type = T;
2590 Steps.push_back(S);
2591}
2592
Douglas Gregore1314a62009-12-18 05:02:21 +00002593void InitializationSequence::AddCAssignmentStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_CAssignment;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Eli Friedman78275202009-12-19 08:11:05 +00002600void InitializationSequence::AddStringInitStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_StringInit;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002607void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_ObjCObjectConversion;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
Douglas Gregore2f943b2011-02-22 18:29:51 +00002614void InitializationSequence::AddArrayInitStep(QualType T) {
2615 Step S;
2616 S.Kind = SK_ArrayInit;
2617 S.Type = T;
2618 Steps.push_back(S);
2619}
2620
John McCall31168b02011-06-15 23:02:42 +00002621void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2622 bool shouldCopy) {
2623 Step s;
2624 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2625 : SK_PassByIndirectRestore);
2626 s.Type = type;
2627 Steps.push_back(s);
2628}
2629
2630void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2631 Step S;
2632 S.Kind = SK_ProduceObjCObject;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Sebastian Redlc1839b12012-01-17 22:49:42 +00002637void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2638 Step S;
2639 S.Kind = SK_StdInitializerList;
2640 S.Type = T;
2641 Steps.push_back(S);
2642}
2643
Sebastian Redl29526f02011-11-27 16:50:07 +00002644void InitializationSequence::RewrapReferenceInitList(QualType T,
2645 InitListExpr *Syntactic) {
2646 assert(Syntactic->getNumInits() == 1 &&
2647 "Can only rewrap trivial init lists.");
2648 Step S;
2649 S.Kind = SK_UnwrapInitList;
2650 S.Type = Syntactic->getInit(0)->getType();
2651 Steps.insert(Steps.begin(), S);
2652
2653 S.Kind = SK_RewrapInitList;
2654 S.Type = T;
2655 S.WrappingSyntacticList = Syntactic;
2656 Steps.push_back(S);
2657}
2658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002659void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002660 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002661 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002662 this->Failure = Failure;
2663 this->FailedOverloadResult = Result;
2664}
2665
2666//===----------------------------------------------------------------------===//
2667// Attempt initialization
2668//===----------------------------------------------------------------------===//
2669
John McCall31168b02011-06-15 23:02:42 +00002670static void MaybeProduceObjCObject(Sema &S,
2671 InitializationSequence &Sequence,
2672 const InitializedEntity &Entity) {
2673 if (!S.getLangOptions().ObjCAutoRefCount) return;
2674
2675 /// When initializing a parameter, produce the value if it's marked
2676 /// __attribute__((ns_consumed)).
2677 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2678 if (!Entity.isParameterConsumed())
2679 return;
2680
2681 assert(Entity.getType()->isObjCRetainableType() &&
2682 "consuming an object of unretainable type?");
2683 Sequence.AddProduceObjCObjectStep(Entity.getType());
2684
2685 /// When initializing a return value, if the return type is a
2686 /// retainable type, then returns need to immediately retain the
2687 /// object. If an autorelease is required, it will be done at the
2688 /// last instant.
2689 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2690 if (!Entity.getType()->isObjCRetainableType())
2691 return;
2692
2693 Sequence.AddProduceObjCObjectStep(Entity.getType());
2694 }
2695}
2696
Sebastian Redled2e5322011-12-22 14:44:04 +00002697/// \brief When initializing from init list via constructor, deal with the
2698/// empty init list and std::initializer_list special cases.
2699///
2700/// \return True if this was a special case, false otherwise.
2701static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002702 InitListExpr *List,
Sebastian Redled2e5322011-12-22 14:44:04 +00002703 CXXRecordDecl *DestRecordDecl,
2704 QualType DestType,
2705 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002706 // C++11 [dcl.init.list]p3:
Richard Smith1bfe0682012-02-14 21:14:13 +00002707 // List-initialization of an object or reference of type T is defined as
2708 // follows:
2709 // - If T is an aggregate, aggregate initialization is performed.
2710 if (DestType->isAggregateType())
2711 return false;
2712
2713 // - Otherwise, if the initializer list has no elements and T is a class
2714 // type with a default constructor, the object is value-initialized.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002715 if (List->getNumInits() == 0) {
Sebastian Redled2e5322011-12-22 14:44:04 +00002716 if (CXXConstructorDecl *DefaultConstructor =
2717 S.LookupDefaultConstructor(DestRecordDecl)) {
2718 if (DefaultConstructor->isDeleted() ||
2719 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2720 // Fake an overload resolution failure.
2721 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2722 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2723 DefaultConstructor->getAccess());
2724 if (FunctionTemplateDecl *ConstructorTmpl =
2725 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2726 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2727 /*ExplicitArgs*/ 0,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002728 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002729 /*SuppressUserConversions*/ false);
2730 else
2731 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002732 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002733 /*SuppressUserConversions*/ false);
2734 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002735 InitializationSequence::FK_ListConstructorOverloadFailed,
2736 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002737 } else
2738 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2739 DefaultConstructor->getAccess(),
2740 DestType,
2741 /*MultipleCandidates=*/false,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002742 /*FromInitList=*/true,
2743 /*AsInitList=*/false);
Sebastian Redled2e5322011-12-22 14:44:04 +00002744 return true;
2745 }
2746 }
2747
2748 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002749 QualType E;
2750 if (S.isStdInitializerList(DestType, &E)) {
2751 // Check that each individual element can be copy-constructed. But since we
2752 // have no place to store further information, we'll recalculate everything
2753 // later.
2754 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2755 S.Context.getConstantArrayType(E,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002756 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2757 List->getNumInits()),
Sebastian Redlc1839b12012-01-17 22:49:42 +00002758 ArrayType::Normal, 0));
2759 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2760 0, HiddenArray);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002761 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002762 Element.setElementIndex(i);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002763 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002764 Sequence.SetFailed(
2765 InitializationSequence::FK_InitListElementCopyFailure);
2766 return true;
2767 }
2768 }
2769 Sequence.AddStdInitializerListConstructionStep(DestType);
2770 return true;
2771 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002772
2773 // Not a special case.
2774 return false;
2775}
2776
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002777static OverloadingResult
2778ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2779 Expr **Args, unsigned NumArgs,
2780 OverloadCandidateSet &CandidateSet,
2781 DeclContext::lookup_iterator Con,
2782 DeclContext::lookup_iterator ConEnd,
2783 OverloadCandidateSet::iterator &Best,
2784 bool CopyInitializing, bool AllowExplicit,
2785 bool OnlyListConstructors) {
2786 CandidateSet.clear();
2787
2788 for (; Con != ConEnd; ++Con) {
2789 NamedDecl *D = *Con;
2790 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2791 bool SuppressUserConversions = false;
2792
2793 // Find the constructor (which may be a template).
2794 CXXConstructorDecl *Constructor = 0;
2795 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2796 if (ConstructorTmpl)
2797 Constructor = cast<CXXConstructorDecl>(
2798 ConstructorTmpl->getTemplatedDecl());
2799 else {
2800 Constructor = cast<CXXConstructorDecl>(D);
2801
2802 // If we're performing copy initialization using a copy constructor, we
2803 // suppress user-defined conversions on the arguments.
2804 // FIXME: Move constructors?
2805 if (CopyInitializing && Constructor->isCopyConstructor())
2806 SuppressUserConversions = true;
2807 }
2808
2809 if (!Constructor->isInvalidDecl() &&
2810 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002811 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002812 if (ConstructorTmpl)
2813 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2814 /*ExplicitArgs*/ 0,
2815 Args, NumArgs, CandidateSet,
2816 SuppressUserConversions);
2817 else
2818 S.AddOverloadCandidate(Constructor, FoundDecl,
2819 Args, NumArgs, CandidateSet,
2820 SuppressUserConversions);
2821 }
2822 }
2823
2824 // Perform overload resolution and return the result.
2825 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2826}
2827
Sebastian Redled2e5322011-12-22 14:44:04 +00002828/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2829/// enumerates the constructors of the initialized entity and performs overload
2830/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002831/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002832/// class type.
2833static void TryConstructorInitialization(Sema &S,
2834 const InitializedEntity &Entity,
2835 const InitializationKind &Kind,
2836 Expr **Args, unsigned NumArgs,
2837 QualType DestType,
2838 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002839 bool InitListSyntax = false) {
2840 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2841 "InitListSyntax must come with a single initializer list argument.");
2842
Sebastian Redled2e5322011-12-22 14:44:04 +00002843 // Check constructor arguments for self reference.
2844 if (DeclaratorDecl *DD = Entity.getDecl())
2845 // Parameters arguments are occassionially constructed with itself,
2846 // for instance, in recursive functions. Skip them.
2847 if (!isa<ParmVarDecl>(DD))
2848 for (unsigned i = 0; i < NumArgs; ++i)
2849 S.CheckSelfReference(DD, Args[i]);
2850
Sebastian Redled2e5322011-12-22 14:44:04 +00002851 // The type we're constructing needs to be complete.
2852 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2853 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002854 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00002855 }
2856
2857 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2858 assert(DestRecordType && "Constructor initialization requires record type");
2859 CXXRecordDecl *DestRecordDecl
2860 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2861
Sebastian Redl88e4d492012-02-04 21:27:33 +00002862 if (InitListSyntax &&
2863 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2864 DestRecordDecl, DestType, Sequence))
Sebastian Redled2e5322011-12-22 14:44:04 +00002865 return;
2866
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002867 // Build the candidate set directly in the initialization sequence
2868 // structure, so that it will persist if we fail.
2869 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2870
2871 // Determine whether we are allowed to call explicit constructors or
2872 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00002873 bool AllowExplicit = Kind.AllowExplicit();
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002874 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00002875
Sebastian Redled2e5322011-12-22 14:44:04 +00002876 // - Otherwise, if T is a class type, constructors are considered. The
2877 // applicable constructors are enumerated, and the best one is chosen
2878 // through overload resolution.
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002879 DeclContext::lookup_iterator ConStart, ConEnd;
2880 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00002881
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002882 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00002883 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002884 bool AsInitializerList = false;
2885
2886 // C++11 [over.match.list]p1:
2887 // When objects of non-aggregate type T are list-initialized, overload
2888 // resolution selects the constructor in two phases:
2889 // - Initially, the candidate functions are the initializer-list
2890 // constructors of the class T and the argument list consists of the
2891 // initializer list as a single argument.
2892 if (InitListSyntax) {
2893 AsInitializerList = true;
2894 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2895 CandidateSet, ConStart, ConEnd, Best,
2896 CopyInitialization, AllowExplicit,
2897 /*OnlyListConstructor=*/true);
2898
2899 // Time to unwrap the init list.
2900 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2901 Args = ILE->getInits();
2902 NumArgs = ILE->getNumInits();
2903 }
2904
2905 // C++11 [over.match.list]p1:
2906 // - If no viable initializer-list constructor is found, overload resolution
2907 // is performed again, where the candidate functions are all the
2908 // constructors of the class T nad the argument list consists of the
2909 // elements of the initializer list.
2910 if (Result == OR_No_Viable_Function) {
2911 AsInitializerList = false;
2912 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2913 CandidateSet, ConStart, ConEnd, Best,
2914 CopyInitialization, AllowExplicit,
2915 /*OnlyListConstructors=*/false);
2916 }
2917 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002918 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002919 InitializationSequence::FK_ListConstructorOverloadFailed :
2920 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002921 Result);
2922 return;
2923 }
2924
2925 // C++0x [dcl.init]p6:
2926 // If a program calls for the default initialization of an object
2927 // of a const-qualified type T, T shall be a class type with a
2928 // user-provided default constructor.
2929 if (Kind.getKind() == InitializationKind::IK_Default &&
2930 Entity.getType().isConstQualified() &&
2931 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2932 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2933 return;
2934 }
2935
2936 // Add the constructor initialization step. Any cv-qualification conversion is
2937 // subsumed by the initialization.
2938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2939 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2940 Sequence.AddConstructorInitializationStep(CtorDecl,
2941 Best->FoundDecl.getAccess(),
2942 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002943 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00002944}
2945
Sebastian Redl29526f02011-11-27 16:50:07 +00002946static bool
2947ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2948 Expr *Initializer,
2949 QualType &SourceType,
2950 QualType &UnqualifiedSourceType,
2951 QualType UnqualifiedTargetType,
2952 InitializationSequence &Sequence) {
2953 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2954 S.Context.OverloadTy) {
2955 DeclAccessPair Found;
2956 bool HadMultipleCandidates = false;
2957 if (FunctionDecl *Fn
2958 = S.ResolveAddressOfOverloadedFunction(Initializer,
2959 UnqualifiedTargetType,
2960 false, Found,
2961 &HadMultipleCandidates)) {
2962 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2963 HadMultipleCandidates);
2964 SourceType = Fn->getType();
2965 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2966 } else if (!UnqualifiedTargetType->isRecordType()) {
2967 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2968 return true;
2969 }
2970 }
2971 return false;
2972}
2973
2974static void TryReferenceInitializationCore(Sema &S,
2975 const InitializedEntity &Entity,
2976 const InitializationKind &Kind,
2977 Expr *Initializer,
2978 QualType cv1T1, QualType T1,
2979 Qualifiers T1Quals,
2980 QualType cv2T2, QualType T2,
2981 Qualifiers T2Quals,
2982 InitializationSequence &Sequence);
2983
2984static void TryListInitialization(Sema &S,
2985 const InitializedEntity &Entity,
2986 const InitializationKind &Kind,
2987 InitListExpr *InitList,
2988 InitializationSequence &Sequence);
2989
2990/// \brief Attempt list initialization of a reference.
2991static void TryReferenceListInitialization(Sema &S,
2992 const InitializedEntity &Entity,
2993 const InitializationKind &Kind,
2994 InitListExpr *InitList,
2995 InitializationSequence &Sequence)
2996{
2997 // First, catch C++03 where this isn't possible.
2998 if (!S.getLangOptions().CPlusPlus0x) {
2999 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3000 return;
3001 }
3002
3003 QualType DestType = Entity.getType();
3004 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3005 Qualifiers T1Quals;
3006 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3007
3008 // Reference initialization via an initializer list works thus:
3009 // If the initializer list consists of a single element that is
3010 // reference-related to the referenced type, bind directly to that element
3011 // (possibly creating temporaries).
3012 // Otherwise, initialize a temporary with the initializer list and
3013 // bind to that.
3014 if (InitList->getNumInits() == 1) {
3015 Expr *Initializer = InitList->getInit(0);
3016 QualType cv2T2 = Initializer->getType();
3017 Qualifiers T2Quals;
3018 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3019
3020 // If this fails, creating a temporary wouldn't work either.
3021 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3022 T1, Sequence))
3023 return;
3024
3025 SourceLocation DeclLoc = Initializer->getLocStart();
3026 bool dummy1, dummy2, dummy3;
3027 Sema::ReferenceCompareResult RefRelationship
3028 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3029 dummy2, dummy3);
3030 if (RefRelationship >= Sema::Ref_Related) {
3031 // Try to bind the reference here.
3032 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3033 T1Quals, cv2T2, T2, T2Quals, Sequence);
3034 if (Sequence)
3035 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3036 return;
3037 }
3038 }
3039
3040 // Not reference-related. Create a temporary and bind to that.
3041 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3042
3043 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3044 if (Sequence) {
3045 if (DestType->isRValueReferenceType() ||
3046 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3047 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3048 else
3049 Sequence.SetFailed(
3050 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3051 }
3052}
3053
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003054/// \brief Attempt list initialization (C++0x [dcl.init.list])
3055static void TryListInitialization(Sema &S,
3056 const InitializedEntity &Entity,
3057 const InitializationKind &Kind,
3058 InitListExpr *InitList,
3059 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003060 QualType DestType = Entity.getType();
3061
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003062 // C++ doesn't allow scalar initialization with more than one argument.
3063 // But C99 complex numbers are scalars and it makes sense there.
3064 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3065 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3066 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3067 return;
3068 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003069 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003070 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003071 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003072 }
3073 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003074 if (S.getLangOptions().CPlusPlus0x) {
3075 Expr *Arg = InitList;
Sebastian Redl5a41f682012-02-12 16:37:24 +00003076 // A direct-initializer is not list-syntax, i.e. there's no special
3077 // treatment of "A a({1, 2});".
Sebastian Redl88e4d492012-02-04 21:27:33 +00003078 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
Sebastian Redl5a41f682012-02-12 16:37:24 +00003079 Sequence, Kind.getKind() != InitializationKind::IK_Direct);
Sebastian Redl88e4d492012-02-04 21:27:33 +00003080 } else
Sebastian Redled2e5322011-12-22 14:44:04 +00003081 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003082 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003083 }
3084
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003085 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003086 DestType, /*VerifyOnly=*/true,
Sebastian Redl5a41f682012-02-12 16:37:24 +00003087 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003088 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003089 if (CheckInitList.HadError()) {
3090 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3091 return;
3092 }
3093
3094 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003095 Sequence.AddListInitializationStep(DestType);
3096}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003097
3098/// \brief Try a reference initialization that involves calling a conversion
3099/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003100static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3101 const InitializedEntity &Entity,
3102 const InitializationKind &Kind,
3103 Expr *Initializer,
3104 bool AllowRValues,
3105 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003106 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003107 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3108 QualType T1 = cv1T1.getUnqualifiedType();
3109 QualType cv2T2 = Initializer->getType();
3110 QualType T2 = cv2T2.getUnqualifiedType();
3111
3112 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003113 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003114 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003116 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003117 ObjCConversion,
3118 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003120 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003121 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003122 (void)ObjCLifetimeConversion;
3123
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 // Build the candidate set directly in the initialization sequence
3125 // structure, so that it will persist if we fail.
3126 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3127 CandidateSet.clear();
3128
3129 // Determine whether we are allowed to call explicit constructors or
3130 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003131 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003134 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3135 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003136 // The type we're converting to is a class type. Enumerate its constructors
3137 // to see if there is a suitable conversion.
3138 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003139
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003141 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003143 NamedDecl *D = *Con;
3144 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3145
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003146 // Find the constructor (which may be a template).
3147 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003148 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003149 if (ConstructorTmpl)
3150 Constructor = cast<CXXConstructorDecl>(
3151 ConstructorTmpl->getTemplatedDecl());
3152 else
John McCalla0296f72010-03-19 07:35:19 +00003153 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003155 if (!Constructor->isInvalidDecl() &&
3156 Constructor->isConvertingConstructor(AllowExplicit)) {
3157 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003158 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003159 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003160 &Initializer, 1, CandidateSet,
3161 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003162 else
John McCalla0296f72010-03-19 07:35:19 +00003163 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003164 &Initializer, 1, CandidateSet,
3165 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 }
John McCall3696dcb2010-08-17 07:23:57 +00003169 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3170 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor496e8b342010-05-07 19:42:26 +00003172 const RecordType *T2RecordType = 0;
3173 if ((T2RecordType = T2->getAs<RecordType>()) &&
3174 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003175 // The type we're converting from is a class type, enumerate its conversion
3176 // functions.
3177 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3178
John McCallad371252010-01-20 00:46:10 +00003179 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003181 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3182 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 NamedDecl *D = *I;
3184 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3185 if (isa<UsingShadowDecl>(D))
3186 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3189 CXXConversionDecl *Conv;
3190 if (ConvTemplate)
3191 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3192 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003193 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 // If the conversion function doesn't return a reference type,
3196 // it can't be considered for this conversion unless we're allowed to
3197 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198 // FIXME: Do we need to make sure that we only consider conversion
3199 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 // break recursion.
3201 if ((AllowExplicit || !Conv->isExplicit()) &&
3202 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3203 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003204 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003205 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003206 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207 else
John McCalla0296f72010-03-19 07:35:19 +00003208 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003209 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003210 }
3211 }
3212 }
John McCall3696dcb2010-08-17 07:23:57 +00003213 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3214 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 SourceLocation DeclLoc = Initializer->getLocStart();
3217
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003218 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003219 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003221 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003222 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003223
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003225
Chandler Carruth30141632011-02-25 19:41:05 +00003226 // This is the overload that will actually be used for the initialization, so
3227 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003228 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003229
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003230 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 if (isa<CXXConversionDecl>(Function))
3232 T2 = Function->getResultType();
3233 else
3234 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003235
3236 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003237 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003238 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003239 T2.getNonLValueExprType(S.Context),
3240 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003241
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003243 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003244 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003245 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003246 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003247 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003248 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003251 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003252 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003253 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003255 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003256 NewDerivedToBase, NewObjCConversion,
3257 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003258 if (NewRefRelationship == Sema::Ref_Incompatible) {
3259 // If the type we've converted to is not reference-related to the
3260 // type we're looking for, then there is another conversion step
3261 // we need to perform to produce a temporary of the right type
3262 // that we'll be binding to.
3263 ImplicitConversionSequence ICS;
3264 ICS.setStandard();
3265 ICS.Standard = Best->FinalConversion;
3266 T2 = ICS.Standard.getToType(2);
3267 Sequence.AddConversionSequenceStep(ICS, T2);
3268 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003269 Sequence.AddDerivedToBaseCastStep(
3270 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003272 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003273 else if (NewObjCConversion)
3274 Sequence.AddObjCObjectConversionStep(
3275 S.Context.getQualifiedType(T1,
3276 T2.getNonReferenceType().getQualifiers()));
3277
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003278 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003279 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003281 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3282 return OR_Success;
3283}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284
Richard Smithc620f552011-10-19 16:55:56 +00003285static void CheckCXX98CompatAccessibleCopy(Sema &S,
3286 const InitializedEntity &Entity,
3287 Expr *CurInitExpr);
3288
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3290static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 const InitializedEntity &Entity,
3292 const InitializationKind &Kind,
3293 Expr *Initializer,
3294 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003295 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003296 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003297 Qualifiers T1Quals;
3298 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003299 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003300 Qualifiers T2Quals;
3301 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003302
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003303 // If the initializer is the address of an overloaded function, try
3304 // to resolve the overloaded function. If all goes well, T2 is the
3305 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003306 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3307 T1, Sequence))
3308 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003309
Sebastian Redl29526f02011-11-27 16:50:07 +00003310 // Delegate everything else to a subfunction.
3311 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3312 T1Quals, cv2T2, T2, T2Quals, Sequence);
3313}
3314
3315/// \brief Reference initialization without resolving overloaded functions.
3316static void TryReferenceInitializationCore(Sema &S,
3317 const InitializedEntity &Entity,
3318 const InitializationKind &Kind,
3319 Expr *Initializer,
3320 QualType cv1T1, QualType T1,
3321 Qualifiers T1Quals,
3322 QualType cv2T2, QualType T2,
3323 Qualifiers T2Quals,
3324 InitializationSequence &Sequence) {
3325 QualType DestType = Entity.getType();
3326 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 // Compute some basic properties of the types and the initializer.
3328 bool isLValueRef = DestType->isLValueReferenceType();
3329 bool isRValueRef = !isLValueRef;
3330 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003331 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003332 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003333 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003334 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003335 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003336 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003337
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003338 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003340 // "cv2 T2" as follows:
3341 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003343 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003344 // Note the analogous bullet points for rvlaue refs to functions. Because
3345 // there are no function rvalues in C++, rvalue refs to functions are treated
3346 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003348 bool T1Function = T1->isFunctionType();
3349 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003351 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003353 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 // reference-compatible with "cv2 T2," or
3356 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003358 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003359 // can occur. However, we do pay attention to whether it is a bit-field
3360 // to decide whether we're actually binding to a temporary created from
3361 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003362 if (DerivedToBase)
3363 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003365 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003366 else if (ObjCConversion)
3367 Sequence.AddObjCObjectConversionStep(
3368 S.Context.getQualifiedType(T1, T2Quals));
3369
Chandler Carruth04bdce62010-01-12 20:32:25 +00003370 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003371 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003372 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003373 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003374 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003375 return;
3376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
3378 // - has a class type (i.e., T2 is a class type), where T1 is not
3379 // reference-related to T2, and can be implicitly converted to an
3380 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3381 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003382 // applicable conversion functions (13.3.1.6) and choosing the best
3383 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003384 // If we have an rvalue ref to function type here, the rhs must be
3385 // an rvalue.
3386 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3387 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003389 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003390 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003391 Sequence);
3392 if (ConvOvlResult == OR_Success)
3393 return;
John McCall0d1da222010-01-12 00:44:57 +00003394 if (ConvOvlResult != OR_No_Viable_Function) {
3395 Sequence.SetOverloadFailure(
3396 InitializationSequence::FK_ReferenceInitOverloadFailed,
3397 ConvOvlResult);
3398 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003399 }
3400 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003403 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003404 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003405 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003406 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3407 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3408 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003409 Sequence.SetOverloadFailure(
3410 InitializationSequence::FK_ReferenceInitOverloadFailed,
3411 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003412 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003413 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003414 ? (RefRelationship == Sema::Ref_Related
3415 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3416 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3417 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003418
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 return;
3420 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003421
Douglas Gregor92e460e2011-01-20 16:44:54 +00003422 // - If the initializer expression
3423 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3424 // "cv1 T1" is reference-compatible with "cv2 T2"
3425 // Note: functions are handled below.
3426 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003427 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003429 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003430 (InitCategory.isXValue() ||
3431 (InitCategory.isPRValue() && T2->isRecordType()) ||
3432 (InitCategory.isPRValue() && T2->isArrayType()))) {
3433 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3434 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003435 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3436 // compiler the freedom to perform a copy here or bind to the
3437 // object, while C++0x requires that we bind directly to the
3438 // object. Hence, we always bind to the object without making an
3439 // extra copy. However, in C++03 requires that we check for the
3440 // presence of a suitable copy constructor:
3441 //
3442 // The constructor that would be used to make the copy shall
3443 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003444 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003445 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003446 else if (S.getLangOptions().CPlusPlus0x)
3447 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregor92e460e2011-01-20 16:44:54 +00003450 if (DerivedToBase)
3451 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3452 ValueKind);
3453 else if (ObjCConversion)
3454 Sequence.AddObjCObjectConversionStep(
3455 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregor92e460e2011-01-20 16:44:54 +00003457 if (T1Quals != T2Quals)
3458 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003460 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463
3464 // - has a class type (i.e., T2 is a class type), where T1 is not
3465 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003466 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3467 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003468 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003469 if (RefRelationship == Sema::Ref_Incompatible) {
3470 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3471 Kind, Initializer,
3472 /*AllowRValues=*/true,
3473 Sequence);
3474 if (ConvOvlResult)
3475 Sequence.SetOverloadFailure(
3476 InitializationSequence::FK_ReferenceInitOverloadFailed,
3477 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003479 return;
3480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003482 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3483 return;
3484 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003485
3486 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003487 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003489 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491 // Determine whether we are allowed to call explicit constructors or
3492 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003493 bool AllowExplicit = Kind.AllowExplicit();
John McCallec6f4e92010-06-04 02:29:22 +00003494
3495 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3496
John McCall31168b02011-06-15 23:02:42 +00003497 ImplicitConversionSequence ICS
3498 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003499 /*SuppressUserConversions*/ false,
3500 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003501 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003502 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3503 /*AllowObjCWritebackConversion=*/false);
3504
3505 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 // FIXME: Use the conversion function set stored in ICS to turn
3507 // this into an overloading ambiguity diagnostic. However, we need
3508 // to keep that set as an OverloadCandidateSet rather than as some
3509 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003510 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3511 Sequence.SetOverloadFailure(
3512 InitializationSequence::FK_ReferenceInitOverloadFailed,
3513 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003514 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3515 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003516 else
3517 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003518 return;
John McCall31168b02011-06-15 23:02:42 +00003519 } else {
3520 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003521 }
3522
3523 // [...] If T1 is reference-related to T2, cv1 must be the
3524 // same cv-qualification as, or greater cv-qualification
3525 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003526 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3527 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003529 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003530 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3531 return;
3532 }
3533
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003535 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003537 InitCategory.isLValue()) {
3538 Sequence.SetFailed(
3539 InitializationSequence::FK_RValueReferenceBindingToLValue);
3540 return;
3541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3544 return;
3545}
3546
3547/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548/// (C++ [dcl.init.string], C99 6.7.8).
3549static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550 const InitializedEntity &Entity,
3551 const InitializationKind &Kind,
3552 Expr *Initializer,
3553 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003554 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003555}
3556
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003557/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003559 const InitializedEntity &Entity,
3560 const InitializationKind &Kind,
3561 InitializationSequence &Sequence) {
Richard Smith1bfe0682012-02-14 21:14:13 +00003562 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003563 //
3564 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003565 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003567 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003568 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003570 if (const RecordType *RT = T->getAs<RecordType>()) {
3571 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smith1bfe0682012-02-14 21:14:13 +00003572 // C++98:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003573 // -- if T is a class type (clause 9) with a user-declared
3574 // constructor (12.1), then the default constructor for T is
3575 // called (and the initialization is ill-formed if T has no
3576 // accessible default constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003577 if (!S.getLangOptions().CPlusPlus0x) {
3578 if (ClassDecl->hasUserDeclaredConstructor())
3579 // FIXME: we really want to refer to a single subobject of the array,
3580 // but Entity doesn't have a way to capture that (yet).
3581 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3582 T, Sequence);
3583 } else {
3584 // C++11:
3585 // -- if T is a class type (clause 9) with either no default constructor
3586 // (12.1 [class.ctor]) or a default constructor that is user-provided
3587 // or deleted, then the object is default-initialized;
3588 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3589 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3590 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3591 T, Sequence);
3592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003593
Richard Smith1bfe0682012-02-14 21:14:13 +00003594 // -- if T is a (possibly cv-qualified) non-union class type without a
3595 // user-provided or deleted default constructor, then the object is
3596 // zero-initialized and, if T has a non-trivial default constructor,
3597 // default-initialized;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003598 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003599 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003600 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003602 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003603 }
3604 }
3605
Douglas Gregor1b303932009-12-22 15:35:07 +00003606 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003607}
3608
Douglas Gregor85dabae2009-12-16 01:38:02 +00003609/// \brief Attempt default initialization (C++ [dcl.init]p6).
3610static void TryDefaultInitialization(Sema &S,
3611 const InitializedEntity &Entity,
3612 const InitializationKind &Kind,
3613 InitializationSequence &Sequence) {
3614 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregor85dabae2009-12-16 01:38:02 +00003616 // C++ [dcl.init]p6:
3617 // To default-initialize an object of type T means:
3618 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003619 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3620
Douglas Gregor85dabae2009-12-16 01:38:02 +00003621 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3622 // constructor for T is called (and the initialization is ill-formed if
3623 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003624 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003625 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3626 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor85dabae2009-12-16 01:38:02 +00003629 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregor85dabae2009-12-16 01:38:02 +00003631 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003633 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003634 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003635 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003636 return;
3637 }
3638
3639 // If the destination type has a lifetime property, zero-initialize it.
3640 if (DestType.getQualifiers().hasObjCLifetime()) {
3641 Sequence.AddZeroInitializationStep(Entity.getType());
3642 return;
3643 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003644}
3645
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3647/// which enumerates all conversion functions and performs overload resolution
3648/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 const InitializedEntity &Entity,
3651 const InitializationKind &Kind,
3652 Expr *Initializer,
3653 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003654 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003655 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3656 QualType SourceType = Initializer->getType();
3657 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3658 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregor540c3b02009-12-14 17:27:33 +00003660 // Build the candidate set directly in the initialization sequence
3661 // structure, so that it will persist if we fail.
3662 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3663 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregor540c3b02009-12-14 17:27:33 +00003665 // Determine whether we are allowed to call explicit constructors or
3666 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003667 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
Douglas Gregor540c3b02009-12-14 17:27:33 +00003669 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3670 // The type we're converting to is a class type. Enumerate its constructors
3671 // to see if there is a suitable conversion.
3672 CXXRecordDecl *DestRecordDecl
3673 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregord9848152010-04-26 14:36:57 +00003675 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003677 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003678 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003679 Con != ConEnd; ++Con) {
3680 NamedDecl *D = *Con;
3681 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Douglas Gregord9848152010-04-26 14:36:57 +00003683 // Find the constructor (which may be a template).
3684 CXXConstructorDecl *Constructor = 0;
3685 FunctionTemplateDecl *ConstructorTmpl
3686 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003687 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003688 Constructor = cast<CXXConstructorDecl>(
3689 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003690 else
Douglas Gregord9848152010-04-26 14:36:57 +00003691 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003692
Douglas Gregord9848152010-04-26 14:36:57 +00003693 if (!Constructor->isInvalidDecl() &&
3694 Constructor->isConvertingConstructor(AllowExplicit)) {
3695 if (ConstructorTmpl)
3696 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3697 /*ExplicitArgs*/ 0,
3698 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003699 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003700 else
3701 S.AddOverloadCandidate(Constructor, FoundDecl,
3702 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003703 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705 }
Douglas Gregord9848152010-04-26 14:36:57 +00003706 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003707 }
Eli Friedman78275202009-12-19 08:11:05 +00003708
3709 SourceLocation DeclLoc = Initializer->getLocStart();
3710
Douglas Gregor540c3b02009-12-14 17:27:33 +00003711 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3712 // The type we're converting from is a class type, enumerate its conversion
3713 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003714
Eli Friedman4afe9a32009-12-20 22:12:03 +00003715 // We can only enumerate the conversion functions for a complete type; if
3716 // the type isn't complete, simply skip this step.
3717 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3718 CXXRecordDecl *SourceRecordDecl
3719 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
John McCallad371252010-01-20 00:46:10 +00003721 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003722 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003723 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003725 I != E; ++I) {
3726 NamedDecl *D = *I;
3727 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3728 if (isa<UsingShadowDecl>(D))
3729 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Eli Friedman4afe9a32009-12-20 22:12:03 +00003731 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3732 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003733 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003734 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003735 else
John McCallda4458e2010-03-31 01:36:47 +00003736 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Eli Friedman4afe9a32009-12-20 22:12:03 +00003738 if (AllowExplicit || !Conv->isExplicit()) {
3739 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003740 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003741 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003742 CandidateSet);
3743 else
John McCalla0296f72010-03-19 07:35:19 +00003744 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003745 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003746 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003747 }
3748 }
3749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
3751 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003752 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003753 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003754 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003755 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003757 Result);
3758 return;
3759 }
John McCall0d1da222010-01-12 00:44:57 +00003760
Douglas Gregor540c3b02009-12-14 17:27:33 +00003761 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003762 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003763 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
Douglas Gregor540c3b02009-12-14 17:27:33 +00003765 if (isa<CXXConstructorDecl>(Function)) {
3766 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00003767 // subsumed by the initialization. Per DR5, the created temporary is of the
3768 // cv-unqualified type of the destination.
3769 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3770 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003771 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003772 return;
3773 }
3774
3775 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003776 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003777 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00003778 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00003779 // the resulting temporary object (possible to create an object of
3780 // a base class type). That copy is not a separate conversion, so
3781 // we just make a note of the actual destination type (possibly a
3782 // base class of the type returned by the conversion function) and
3783 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003784 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3785 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003786 return;
3787 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003788
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003789 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3790 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor5ab11652010-04-17 22:01:05 +00003792 // If the conversion following the call to the conversion function
3793 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003794 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3795 Best->FinalConversion.Third) {
3796 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003797 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003798 ICS.Standard = Best->FinalConversion;
3799 Sequence.AddConversionSequenceStep(ICS, DestType);
3800 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003801}
3802
John McCall31168b02011-06-15 23:02:42 +00003803/// The non-zero enum values here are indexes into diagnostic alternatives.
3804enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3805
3806/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003807static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3808 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003809 // Skip parens.
3810 e = e->IgnoreParens();
3811
3812 // Skip address-of nodes.
3813 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3814 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003815 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003816
3817 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003818 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3819 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003820 case CK_Dependent:
3821 case CK_BitCast:
3822 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003823 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003824 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003825
3826 case CK_ArrayToPointerDecay:
3827 return IIK_nonscalar;
3828
3829 case CK_NullToPointer:
3830 return IIK_okay;
3831
3832 default:
3833 break;
3834 }
3835
3836 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003837 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3838 if (!isAddressOf) return IIK_nonlocal;
3839
3840 VarDecl *var;
3841 if (isa<DeclRefExpr>(e)) {
3842 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3843 if (!var) return IIK_nonlocal;
3844 } else {
3845 var = cast<BlockDeclRefExpr>(e)->getDecl();
3846 }
3847
3848 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003849
3850 // If we have a conditional operator, check both sides.
3851 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003852 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003853 return iik;
3854
John McCall63f84442011-06-27 23:59:58 +00003855 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003856
3857 // These are never scalar.
3858 } else if (isa<ArraySubscriptExpr>(e)) {
3859 return IIK_nonscalar;
3860
3861 // Otherwise, it needs to be a null pointer constant.
3862 } else {
3863 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3864 ? IIK_okay : IIK_nonlocal);
3865 }
3866
3867 return IIK_nonlocal;
3868}
3869
3870/// Check whether the given expression is a valid operand for an
3871/// indirect copy/restore.
3872static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3873 assert(src->isRValue());
3874
John McCall63f84442011-06-27 23:59:58 +00003875 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003876 if (iik == IIK_okay) return;
3877
3878 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3879 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3880 << src->getSourceRange();
3881}
3882
Douglas Gregore2f943b2011-02-22 18:29:51 +00003883/// \brief Determine whether we have compatible array types for the
3884/// purposes of GNU by-copy array initialization.
3885static bool hasCompatibleArrayTypes(ASTContext &Context,
3886 const ArrayType *Dest,
3887 const ArrayType *Source) {
3888 // If the source and destination array types are equivalent, we're
3889 // done.
3890 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3891 return true;
3892
3893 // Make sure that the element types are the same.
3894 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3895 return false;
3896
3897 // The only mismatch we allow is when the destination is an
3898 // incomplete array type and the source is a constant array type.
3899 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3900}
3901
John McCall31168b02011-06-15 23:02:42 +00003902static bool tryObjCWritebackConversion(Sema &S,
3903 InitializationSequence &Sequence,
3904 const InitializedEntity &Entity,
3905 Expr *Initializer) {
3906 bool ArrayDecay = false;
3907 QualType ArgType = Initializer->getType();
3908 QualType ArgPointee;
3909 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3910 ArrayDecay = true;
3911 ArgPointee = ArgArrayType->getElementType();
3912 ArgType = S.Context.getPointerType(ArgPointee);
3913 }
3914
3915 // Handle write-back conversion.
3916 QualType ConvertedArgType;
3917 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3918 ConvertedArgType))
3919 return false;
3920
3921 // We should copy unless we're passing to an argument explicitly
3922 // marked 'out'.
3923 bool ShouldCopy = true;
3924 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3925 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3926
3927 // Do we need an lvalue conversion?
3928 if (ArrayDecay || Initializer->isGLValue()) {
3929 ImplicitConversionSequence ICS;
3930 ICS.setStandard();
3931 ICS.Standard.setAsIdentityConversion();
3932
3933 QualType ResultType;
3934 if (ArrayDecay) {
3935 ICS.Standard.First = ICK_Array_To_Pointer;
3936 ResultType = S.Context.getPointerType(ArgPointee);
3937 } else {
3938 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3939 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3940 }
3941
3942 Sequence.AddConversionSequenceStep(ICS, ResultType);
3943 }
3944
3945 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3946 return true;
3947}
3948
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003949InitializationSequence::InitializationSequence(Sema &S,
3950 const InitializedEntity &Entity,
3951 const InitializationKind &Kind,
3952 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003953 unsigned NumArgs)
3954 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003955 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003957 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958 // The semantics of initializers are as follows. The destination type is
3959 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003960 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003962 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003963 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003964
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003965 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003966 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3967 SequenceKind = DependentSequence;
3968 return;
3969 }
3970
Sebastian Redld201edf2011-06-05 13:59:11 +00003971 // Almost everything is a normal sequence.
3972 setSequenceKind(NormalSequence);
3973
John McCalled75c092010-12-07 22:54:16 +00003974 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003975 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003976 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003977 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3978 if (result.isInvalid()) {
3979 SetFailed(FK_PlaceholderType);
3980 return;
John McCall4124c492011-10-17 18:40:02 +00003981 }
John McCalld5c98ae2011-11-15 01:35:18 +00003982 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003983 }
John McCalled75c092010-12-07 22:54:16 +00003984
John McCall4124c492011-10-17 18:40:02 +00003985
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003986 QualType SourceType;
3987 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003988 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003989 Initializer = Args[0];
3990 if (!isa<InitListExpr>(Initializer))
3991 SourceType = Initializer->getType();
3992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993
Sebastian Redl0501c632012-02-12 16:37:36 +00003994 // - If the initializer is a (non-parenthesized) braced-init-list, the
3995 // object is list-initialized (8.5.4).
3996 if (Kind.getKind() != InitializationKind::IK_Direct) {
3997 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3998 TryListInitialization(S, Entity, Kind, InitList, *this);
3999 return;
4000 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 // - If the destination type is a reference type, see 8.5.3.
4004 if (DestType->isReferenceType()) {
4005 // C++0x [dcl.init.ref]p1:
4006 // A variable declared to be a T& or T&&, that is, "reference to type T"
4007 // (8.3.2), shall be initialized by an object, or function, of type T or
4008 // by an object that can be converted into a T.
4009 // (Therefore, multiple arguments are not permitted.)
4010 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004011 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004013 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 return;
4015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004017 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004018 if (Kind.getKind() == InitializationKind::IK_Value ||
4019 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004020 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 return;
4022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregor85dabae2009-12-16 01:38:02 +00004024 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004025 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004026 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004027 return;
4028 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004029
John McCall66884dd2011-02-21 07:22:22 +00004030 // - If the destination type is an array of characters, an array of
4031 // char16_t, an array of char32_t, or an array of wchar_t, and the
4032 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004035 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004036 if (Initializer && isa<VariableArrayType>(DestAT)) {
4037 SetFailed(FK_VariableLengthArrayHasInitializer);
4038 return;
4039 }
4040
Douglas Gregore2f943b2011-02-22 18:29:51 +00004041 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004042 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004043 return;
4044 }
4045
Douglas Gregore2f943b2011-02-22 18:29:51 +00004046 // Note: as an GNU C extension, we allow initialization of an
4047 // array from a compound literal that creates an array of the same
4048 // type, so long as the initializer has no side effects.
4049 if (!S.getLangOptions().CPlusPlus && Initializer &&
4050 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4051 Initializer->getType()->isArrayType()) {
4052 const ArrayType *SourceAT
4053 = Context.getAsArrayType(Initializer->getType());
4054 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004055 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004056 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004057 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004058 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004059 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004060 }
4061 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004062 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004063 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004064 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066 return;
4067 }
Eli Friedman78275202009-12-19 08:11:05 +00004068
John McCall31168b02011-06-15 23:02:42 +00004069 // Determine whether we should consider writeback conversions for
4070 // Objective-C ARC.
4071 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4072 Entity.getKind() == InitializedEntity::EK_Parameter;
4073
4074 // We're at the end of the line for C: it's either a write-back conversion
4075 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004076 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004077 // If allowed, check whether this is an Objective-C writeback conversion.
4078 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004079 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004080 return;
4081 }
4082
4083 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004084 AddCAssignmentStep(DestType);
4085 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004086 return;
4087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
John McCall31168b02011-06-15 23:02:42 +00004089 assert(S.getLangOptions().CPlusPlus);
4090
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004091 // - If the destination type is a (possibly cv-qualified) class type:
4092 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093 // - If the initialization is direct-initialization, or if it is
4094 // copy-initialization where the cv-unqualified version of the
4095 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004096 // class of the destination, constructors are considered. [...]
4097 if (Kind.getKind() == InitializationKind::IK_Direct ||
4098 (Kind.getKind() == InitializationKind::IK_Copy &&
4099 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4100 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004102 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004104 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004106 // used) to a derived class thereof are enumerated as described in
4107 // 13.3.1.4, and the best one is chosen through overload resolution
4108 // (13.3).
4109 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004110 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004111 return;
4112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113
Douglas Gregor85dabae2009-12-16 01:38:02 +00004114 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004115 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004116 return;
4117 }
4118 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
4120 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004121 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004122 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004123 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4124 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004125 return;
4126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004128 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004129 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004130 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004132 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004133
4134 ImplicitConversionSequence ICS
4135 = S.TryImplicitConversion(Initializer, Entity.getType(),
4136 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004137 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004138 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004139 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4140 allowObjCWritebackConversion);
4141
4142 if (ICS.isStandard() &&
4143 ICS.Standard.Second == ICK_Writeback_Conversion) {
4144 // Objective-C ARC writeback conversion.
4145
4146 // We should copy unless we're passing to an argument explicitly
4147 // marked 'out'.
4148 bool ShouldCopy = true;
4149 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4150 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4151
4152 // If there was an lvalue adjustment, add it as a separate conversion.
4153 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4154 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4155 ImplicitConversionSequence LvalueICS;
4156 LvalueICS.setStandard();
4157 LvalueICS.Standard.setAsIdentityConversion();
4158 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4159 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004160 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004161 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004162
4163 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004164 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004165 DeclAccessPair dap;
4166 if (Initializer->getType() == Context.OverloadTy &&
4167 !S.ResolveAddressOfOverloadedFunction(Initializer
4168 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004169 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004170 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004171 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004172 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004173 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004174
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004175 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004176 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004177}
4178
4179InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181 StepEnd = Steps.end();
4182 Step != StepEnd; ++Step)
4183 Step->Destroy();
4184}
4185
4186//===----------------------------------------------------------------------===//
4187// Perform initialization
4188//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004190getAssignmentAction(const InitializedEntity &Entity) {
4191 switch(Entity.getKind()) {
4192 case InitializedEntity::EK_Variable:
4193 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004194 case InitializedEntity::EK_Exception:
4195 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004196 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004197 return Sema::AA_Initializing;
4198
4199 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004201 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4202 return Sema::AA_Sending;
4203
Douglas Gregore1314a62009-12-18 05:02:21 +00004204 return Sema::AA_Passing;
4205
4206 case InitializedEntity::EK_Result:
4207 return Sema::AA_Returning;
4208
Douglas Gregore1314a62009-12-18 05:02:21 +00004209 case InitializedEntity::EK_Temporary:
4210 // FIXME: Can we tell apart casting vs. converting?
4211 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212
Douglas Gregore1314a62009-12-18 05:02:21 +00004213 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004214 case InitializedEntity::EK_ArrayElement:
4215 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004216 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004217 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004218 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004219 return Sema::AA_Initializing;
4220 }
4221
David Blaikie8a40f702012-01-17 06:56:22 +00004222 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004223}
4224
Douglas Gregor95562572010-04-24 23:45:46 +00004225/// \brief Whether we should binding a created object as a temporary when
4226/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004227static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004228 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004229 case InitializedEntity::EK_ArrayElement:
4230 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004231 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004232 case InitializedEntity::EK_New:
4233 case InitializedEntity::EK_Variable:
4234 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004235 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004236 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004237 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004238 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004239 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004240 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004241 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregore1314a62009-12-18 05:02:21 +00004243 case InitializedEntity::EK_Parameter:
4244 case InitializedEntity::EK_Temporary:
4245 return true;
4246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregore1314a62009-12-18 05:02:21 +00004248 llvm_unreachable("missed an InitializedEntity kind?");
4249}
4250
Douglas Gregor95562572010-04-24 23:45:46 +00004251/// \brief Whether the given entity, when initialized with an object
4252/// created for that initialization, requires destruction.
4253static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4254 switch (Entity.getKind()) {
4255 case InitializedEntity::EK_Member:
4256 case InitializedEntity::EK_Result:
4257 case InitializedEntity::EK_New:
4258 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004259 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004260 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004261 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004262 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004263 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004264 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265
Douglas Gregor95562572010-04-24 23:45:46 +00004266 case InitializedEntity::EK_Variable:
4267 case InitializedEntity::EK_Parameter:
4268 case InitializedEntity::EK_Temporary:
4269 case InitializedEntity::EK_ArrayElement:
4270 case InitializedEntity::EK_Exception:
4271 return true;
4272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
4274 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004275}
4276
Richard Smithc620f552011-10-19 16:55:56 +00004277/// \brief Look for copy and move constructors and constructor templates, for
4278/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4279static void LookupCopyAndMoveConstructors(Sema &S,
4280 OverloadCandidateSet &CandidateSet,
4281 CXXRecordDecl *Class,
4282 Expr *CurInitExpr) {
4283 DeclContext::lookup_iterator Con, ConEnd;
4284 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4285 Con != ConEnd; ++Con) {
4286 CXXConstructorDecl *Constructor = 0;
4287
4288 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4289 // Handle copy/moveconstructors, only.
4290 if (!Constructor || Constructor->isInvalidDecl() ||
4291 !Constructor->isCopyOrMoveConstructor() ||
4292 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4293 continue;
4294
4295 DeclAccessPair FoundDecl
4296 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4297 S.AddOverloadCandidate(Constructor, FoundDecl,
4298 &CurInitExpr, 1, CandidateSet);
4299 continue;
4300 }
4301
4302 // Handle constructor templates.
4303 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4304 if (ConstructorTmpl->isInvalidDecl())
4305 continue;
4306
4307 Constructor = cast<CXXConstructorDecl>(
4308 ConstructorTmpl->getTemplatedDecl());
4309 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4310 continue;
4311
4312 // FIXME: Do we need to limit this to copy-constructor-like
4313 // candidates?
4314 DeclAccessPair FoundDecl
4315 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4316 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4317 &CurInitExpr, 1, CandidateSet, true);
4318 }
4319}
4320
4321/// \brief Get the location at which initialization diagnostics should appear.
4322static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4323 Expr *Initializer) {
4324 switch (Entity.getKind()) {
4325 case InitializedEntity::EK_Result:
4326 return Entity.getReturnLoc();
4327
4328 case InitializedEntity::EK_Exception:
4329 return Entity.getThrowLoc();
4330
4331 case InitializedEntity::EK_Variable:
4332 return Entity.getDecl()->getLocation();
4333
Douglas Gregor19666fb2012-02-15 16:57:26 +00004334 case InitializedEntity::EK_LambdaCapture:
4335 return Entity.getCaptureLoc();
4336
Richard Smithc620f552011-10-19 16:55:56 +00004337 case InitializedEntity::EK_ArrayElement:
4338 case InitializedEntity::EK_Member:
4339 case InitializedEntity::EK_Parameter:
4340 case InitializedEntity::EK_Temporary:
4341 case InitializedEntity::EK_New:
4342 case InitializedEntity::EK_Base:
4343 case InitializedEntity::EK_Delegating:
4344 case InitializedEntity::EK_VectorElement:
4345 case InitializedEntity::EK_ComplexElement:
4346 case InitializedEntity::EK_BlockElement:
4347 return Initializer->getLocStart();
4348 }
4349 llvm_unreachable("missed an InitializedEntity kind?");
4350}
4351
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004352/// \brief Make a (potentially elidable) temporary copy of the object
4353/// provided by the given initializer by calling the appropriate copy
4354/// constructor.
4355///
4356/// \param S The Sema object used for type-checking.
4357///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004358/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004359/// the type of the initializer expression or a superclass thereof.
4360///
4361/// \param Enter The entity being initialized.
4362///
4363/// \param CurInit The initializer expression.
4364///
4365/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4366/// is permitted in C++03 (but not C++0x) when binding a reference to
4367/// an rvalue.
4368///
4369/// \returns An expression that copies the initializer expression into
4370/// a temporary object, or an error expression if a copy could not be
4371/// created.
John McCalldadc5752010-08-24 06:29:42 +00004372static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004373 QualType T,
4374 const InitializedEntity &Entity,
4375 ExprResult CurInit,
4376 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004377 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004378 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004380 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004381 Class = cast<CXXRecordDecl>(Record->getDecl());
4382 if (!Class)
4383 return move(CurInit);
4384
Douglas Gregor5d369002011-01-21 18:05:27 +00004385 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004386 // When certain criteria are met, an implementation is allowed to
4387 // omit the copy/move construction of a class object, even if the
4388 // copy/move constructor and/or destructor for the object have
4389 // side effects. [...]
4390 // - when a temporary class object that has not been bound to a
4391 // reference (12.2) would be copied/moved to a class object
4392 // with the same cv-unqualified type, the copy/move operation
4393 // can be omitted by constructing the temporary object
4394 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004396 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004397 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004399 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004400 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004401 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004402
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004404 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4405 return move(CurInit);
4406
Douglas Gregorf282a762011-01-21 19:38:21 +00004407 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004408 // Only consider constructors and constructor templates. Per
4409 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4410 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004411 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004412 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004414 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4415
Douglas Gregore1314a62009-12-18 05:02:21 +00004416 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004417 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004418 case OR_Success:
4419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregore1314a62009-12-18 05:02:21 +00004421 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004422 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4423 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4424 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004425 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004426 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004427 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004428 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004429 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004430 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregore1314a62009-12-18 05:02:21 +00004432 case OR_Ambiguous:
4433 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004434 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004435 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004436 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004437 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438
Douglas Gregore1314a62009-12-18 05:02:21 +00004439 case OR_Deleted:
4440 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004441 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004442 << CurInitExpr->getSourceRange();
4443 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004444 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004445 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004446 }
4447
Douglas Gregor5ab11652010-04-17 22:01:05 +00004448 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004449 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004450 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004451
Anders Carlssona01874b2010-04-21 18:47:17 +00004452 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004453 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004454
4455 if (IsExtraneousCopy) {
4456 // If this is a totally extraneous copy for C++03 reference
4457 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004458 // expression. We don't generate an (elided) copy operation here
4459 // because doing so would require us to pass down a flag to avoid
4460 // infinite recursion, where each step adds another extraneous,
4461 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004462
Douglas Gregor30b52772010-04-18 07:57:34 +00004463 // Instantiate the default arguments of any extra parameters in
4464 // the selected copy constructor, as if we were going to create a
4465 // proper call to the copy constructor.
4466 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4467 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4468 if (S.RequireCompleteType(Loc, Parm->getType(),
4469 S.PDiag(diag::err_call_incomplete_argument)))
4470 break;
4471
4472 // Build the default argument expression; we don't actually care
4473 // if this succeeds or not, because this routine will complain
4474 // if there was a problem.
4475 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4476 }
4477
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004478 return S.Owned(CurInitExpr);
4479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Eli Friedmanfa0df832012-02-02 03:46:19 +00004481 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004482
Douglas Gregor5ab11652010-04-17 22:01:05 +00004483 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004484 // constructor call (we might have derived-to-base conversions, or
4485 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004486 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004487 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004488 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004489
Douglas Gregord0ace022010-04-25 00:55:24 +00004490 // Actually perform the constructor call.
4491 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004492 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004493 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004494 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004495 CXXConstructExpr::CK_Complete,
4496 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
Douglas Gregord0ace022010-04-25 00:55:24 +00004498 // If we're supposed to bind temporaries, do so.
4499 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4500 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4501 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004502}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004503
Richard Smithc620f552011-10-19 16:55:56 +00004504/// \brief Check whether elidable copy construction for binding a reference to
4505/// a temporary would have succeeded if we were building in C++98 mode, for
4506/// -Wc++98-compat.
4507static void CheckCXX98CompatAccessibleCopy(Sema &S,
4508 const InitializedEntity &Entity,
4509 Expr *CurInitExpr) {
4510 assert(S.getLangOptions().CPlusPlus0x);
4511
4512 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4513 if (!Record)
4514 return;
4515
4516 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4517 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4518 == DiagnosticsEngine::Ignored)
4519 return;
4520
4521 // Find constructors which would have been considered.
4522 OverloadCandidateSet CandidateSet(Loc);
4523 LookupCopyAndMoveConstructors(
4524 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4525
4526 // Perform overload resolution.
4527 OverloadCandidateSet::iterator Best;
4528 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4529
4530 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4531 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4532 << CurInitExpr->getSourceRange();
4533
4534 switch (OR) {
4535 case OR_Success:
4536 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4537 Best->FoundDecl.getAccess(), Diag);
4538 // FIXME: Check default arguments as far as that's possible.
4539 break;
4540
4541 case OR_No_Viable_Function:
4542 S.Diag(Loc, Diag);
4543 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4544 break;
4545
4546 case OR_Ambiguous:
4547 S.Diag(Loc, Diag);
4548 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4549 break;
4550
4551 case OR_Deleted:
4552 S.Diag(Loc, Diag);
4553 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4554 << 1 << Best->Function->isDeleted();
4555 break;
4556 }
4557}
4558
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004559void InitializationSequence::PrintInitLocationNote(Sema &S,
4560 const InitializedEntity &Entity) {
4561 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4562 if (Entity.getDecl()->getLocation().isInvalid())
4563 return;
4564
4565 if (Entity.getDecl()->getDeclName())
4566 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4567 << Entity.getDecl()->getDeclName();
4568 else
4569 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4570 }
4571}
4572
Sebastian Redl112aa822011-07-14 19:07:55 +00004573static bool isReferenceBinding(const InitializationSequence::Step &s) {
4574 return s.Kind == InitializationSequence::SK_BindReference ||
4575 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4576}
4577
Sebastian Redled2e5322011-12-22 14:44:04 +00004578static ExprResult
4579PerformConstructorInitialization(Sema &S,
4580 const InitializedEntity &Entity,
4581 const InitializationKind &Kind,
4582 MultiExprArg Args,
4583 const InitializationSequence::Step& Step,
4584 bool &ConstructorInitRequiresZeroInit) {
4585 unsigned NumArgs = Args.size();
4586 CXXConstructorDecl *Constructor
4587 = cast<CXXConstructorDecl>(Step.Function.Function);
4588 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4589
4590 // Build a call to the selected constructor.
4591 ASTOwningVector<Expr*> ConstructorArgs(S);
4592 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4593 ? Kind.getEqualLoc()
4594 : Kind.getLocation();
4595
4596 if (Kind.getKind() == InitializationKind::IK_Default) {
4597 // Force even a trivial, implicit default constructor to be
4598 // semantically checked. We do this explicitly because we don't build
4599 // the definition for completely trivial constructors.
4600 CXXRecordDecl *ClassDecl = Constructor->getParent();
4601 assert(ClassDecl && "No parent class for constructor.");
4602 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4603 ClassDecl->hasTrivialDefaultConstructor() &&
4604 !Constructor->isUsed(false))
4605 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4606 }
4607
4608 ExprResult CurInit = S.Owned((Expr *)0);
4609
4610 // Determine the arguments required to actually perform the constructor
4611 // call.
4612 if (S.CompleteConstructorCall(Constructor, move(Args),
4613 Loc, ConstructorArgs))
4614 return ExprError();
4615
4616
4617 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4618 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4619 (Kind.getKind() == InitializationKind::IK_Direct ||
4620 Kind.getKind() == InitializationKind::IK_Value)) {
4621 // An explicitly-constructed temporary, e.g., X(1, 2).
4622 unsigned NumExprs = ConstructorArgs.size();
4623 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004624 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004625 S.DiagnoseUseOfDecl(Constructor, Loc);
4626
4627 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4628 if (!TSInfo)
4629 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4630
4631 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4632 Constructor,
4633 TSInfo,
4634 Exprs,
4635 NumExprs,
4636 Kind.getParenRange(),
4637 HadMultipleCandidates,
4638 ConstructorInitRequiresZeroInit));
4639 } else {
4640 CXXConstructExpr::ConstructionKind ConstructKind =
4641 CXXConstructExpr::CK_Complete;
4642
4643 if (Entity.getKind() == InitializedEntity::EK_Base) {
4644 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4645 CXXConstructExpr::CK_VirtualBase :
4646 CXXConstructExpr::CK_NonVirtualBase;
4647 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4648 ConstructKind = CXXConstructExpr::CK_Delegating;
4649 }
4650
4651 // Only get the parenthesis range if it is a direct construction.
4652 SourceRange parenRange =
4653 Kind.getKind() == InitializationKind::IK_Direct ?
4654 Kind.getParenRange() : SourceRange();
4655
4656 // If the entity allows NRVO, mark the construction as elidable
4657 // unconditionally.
4658 if (Entity.allowsNRVO())
4659 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4660 Constructor, /*Elidable=*/true,
4661 move_arg(ConstructorArgs),
4662 HadMultipleCandidates,
4663 ConstructorInitRequiresZeroInit,
4664 ConstructKind,
4665 parenRange);
4666 else
4667 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4668 Constructor,
4669 move_arg(ConstructorArgs),
4670 HadMultipleCandidates,
4671 ConstructorInitRequiresZeroInit,
4672 ConstructKind,
4673 parenRange);
4674 }
4675 if (CurInit.isInvalid())
4676 return ExprError();
4677
4678 // Only check access if all of that succeeded.
4679 S.CheckConstructorAccess(Loc, Constructor, Entity,
4680 Step.Function.FoundDecl.getAccess());
4681 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4682
4683 if (shouldBindAsTemporary(Entity))
4684 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4685
4686 return move(CurInit);
4687}
4688
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004690InitializationSequence::Perform(Sema &S,
4691 const InitializedEntity &Entity,
4692 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004693 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004694 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004695 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004696 unsigned NumArgs = Args.size();
4697 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004698 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Sebastian Redld201edf2011-06-05 13:59:11 +00004701 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004702 // If the declaration is a non-dependent, incomplete array type
4703 // that has an initializer, then its type will be completed once
4704 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004705 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004706 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004707 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004708 if (const IncompleteArrayType *ArrayT
4709 = S.Context.getAsIncompleteArrayType(DeclType)) {
4710 // FIXME: We don't currently have the ability to accurately
4711 // compute the length of an initializer list without
4712 // performing full type-checking of the initializer list
4713 // (since we have to determine where braces are implicitly
4714 // introduced and such). So, we fall back to making the array
4715 // type a dependently-sized array type with no specified
4716 // bound.
4717 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4718 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004719
Douglas Gregor51e77d52009-12-10 17:56:55 +00004720 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004721 if (DeclaratorDecl *DD = Entity.getDecl()) {
4722 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4723 TypeLoc TL = TInfo->getTypeLoc();
4724 if (IncompleteArrayTypeLoc *ArrayLoc
4725 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4726 Brackets = ArrayLoc->getBracketsRange();
4727 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004728 }
4729
4730 *ResultType
4731 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4732 /*NumElts=*/0,
4733 ArrayT->getSizeModifier(),
4734 ArrayT->getIndexTypeCVRQualifiers(),
4735 Brackets);
4736 }
4737
4738 }
4739 }
Sebastian Redla9351792012-02-11 23:51:47 +00004740 if (Kind.getKind() == InitializationKind::IK_Direct &&
4741 !Kind.isExplicitCast()) {
4742 // Rebuild the ParenListExpr.
4743 SourceRange ParenRange = Kind.getParenRange();
4744 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4745 move(Args));
4746 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004747 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4748 Kind.isExplicitCast());
4749 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004750 }
4751
Sebastian Redld201edf2011-06-05 13:59:11 +00004752 // No steps means no initialization.
4753 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004754 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755
Douglas Gregor1b303932009-12-22 15:35:07 +00004756 QualType DestType = Entity.getType().getNonReferenceType();
4757 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004758 // the same as Entity.getDecl()->getType() in cases involving type merging,
4759 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004760 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004761 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004762 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004763
John McCalldadc5752010-08-24 06:29:42 +00004764 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004767 // grab the only argument out the Args and place it into the "current"
4768 // initializer.
4769 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004770 case SK_ResolveAddressOfOverloadedFunction:
4771 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004772 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004773 case SK_CastDerivedToBaseLValue:
4774 case SK_BindReference:
4775 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004776 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004777 case SK_UserConversion:
4778 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004779 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004780 case SK_QualificationConversionRValue:
4781 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004782 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004783 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004784 case SK_UnwrapInitList:
4785 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004786 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004787 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004788 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004789 case SK_ArrayInit:
4790 case SK_PassByIndirectCopyRestore:
4791 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004792 case SK_ProduceObjCObject:
4793 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004794 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004795 CurInit = Args.get()[0];
4796 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004797 break;
John McCall34376a62010-12-04 03:47:34 +00004798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799
Douglas Gregore1314a62009-12-18 05:02:21 +00004800 case SK_ConstructorInitialization:
4801 case SK_ZeroInitialization:
4802 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804
4805 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004806 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004807 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004808 for (step_iterator Step = step_begin(), StepEnd = step_end();
4809 Step != StepEnd; ++Step) {
4810 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004811 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812
John Wiegley01296292011-04-08 18:41:53 +00004813 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004815 switch (Step->Kind) {
4816 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004818 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004819 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004820 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004821 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004822 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004823 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004826 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004827 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 case SK_CastDerivedToBaseLValue: {
4829 // We have a derived-to-base cast that produces either an rvalue or an
4830 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
John McCallcf142162010-08-07 06:22:56 +00004832 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004833
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004834 // Casts to inaccessible base classes are allowed with C-style casts.
4835 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4836 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004837 CurInit.get()->getLocStart(),
4838 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004839 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004840 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor88d292c2010-05-13 16:44:06 +00004842 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4843 QualType T = SourceType;
4844 if (const PointerType *Pointer = T->getAs<PointerType>())
4845 T = Pointer->getPointeeType();
4846 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004847 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004848 cast<CXXRecordDecl>(RecordTy->getDecl()));
4849 }
4850
John McCall2536c6d2010-08-25 10:28:54 +00004851 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004852 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004853 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004854 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004855 VK_XValue :
4856 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004857 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4858 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004859 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004860 CurInit.get(),
4861 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004862 break;
4863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004864
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004865 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004866 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004867 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4868 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004869 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004870 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004871 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004872 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004873 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004874 }
Anders Carlssona91be642010-01-29 02:47:33 +00004875
John Wiegley01296292011-04-08 18:41:53 +00004876 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004877 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004878 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4879 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004880 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004881 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004882 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004885 // Reference binding does not have any corresponding ASTs.
4886
4887 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004888 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004889 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004890
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004891 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004892
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004893 case SK_BindReferenceToTemporary:
4894 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004895 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004896 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897
Douglas Gregorfe314812011-06-21 17:03:29 +00004898 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004899 CurInit = new (S.Context) MaterializeTemporaryExpr(
4900 Entity.getType().getNonReferenceType(),
4901 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004902 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004903
4904 // If we're binding to an Objective-C object that has lifetime, we
4905 // need cleanups.
4906 if (S.getLangOptions().ObjCAutoRefCount &&
4907 CurInit.get()->getType()->isObjCLifetimeType())
4908 S.ExprNeedsCleanups = true;
4909
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004910 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004912 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004914 /*IsExtraneousCopy=*/true);
4915 break;
4916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004917 case SK_UserConversion: {
4918 // We have a user-defined conversion that invokes either a constructor
4919 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004920 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004921 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004922 FunctionDecl *Fn = Step->Function.Function;
4923 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004924 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004925 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004926 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004927 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004928 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004929 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004930 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004931
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004932 // Determine the arguments required to actually perform the constructor
4933 // call.
John Wiegley01296292011-04-08 18:41:53 +00004934 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004935 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004936 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004937 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004938 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
Richard Smithb24f0672012-02-11 19:22:50 +00004940 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004942 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004943 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004944 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004945 CXXConstructExpr::CK_Complete,
4946 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004947 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004948 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004949
Anders Carlssona01874b2010-04-21 18:47:17 +00004950 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004951 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004952 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
John McCalle3027922010-08-25 11:45:40 +00004954 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004955 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4956 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4957 S.IsDerivedFrom(SourceType, Class))
4958 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959
Douglas Gregor95562572010-04-24 23:45:46 +00004960 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 } else {
4962 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004963 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004964 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004965 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004966 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
4968 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004969 // derived-to-base conversion? I believe the answer is "no", because
4970 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004971 ExprResult CurInitExprRes =
4972 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4973 FoundFn, Conversion);
4974 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004975 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004976 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004978 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004979 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4980 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004981 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004982 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983
John McCalle3027922010-08-25 11:45:40 +00004984 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
Douglas Gregor95562572010-04-24 23:45:46 +00004986 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988
Sebastian Redl112aa822011-07-14 19:07:55 +00004989 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004990 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4991
4992 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004993 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004994 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004996 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004997 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004998 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004999 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00005000 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005001 }
5002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003
John McCallcf142162010-08-07 06:22:56 +00005004 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005005 CurInit.get()->getType(),
5006 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005007 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005008 if (MaybeBindToTemp)
5009 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005010 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005011 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5012 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005013 break;
5014 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005016 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005017 case SK_QualificationConversionXValue:
5018 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005019 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005020 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005021 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005022 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005023 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005024 VK_XValue :
5025 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005026 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005027 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005028 }
5029
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005030 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005031 Sema::CheckedConversionKind CCK
5032 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5033 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005034 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005035 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005036 ExprResult CurInitExprRes =
5037 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005038 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005039 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005040 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005041 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005042 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Douglas Gregor51e77d52009-12-10 17:56:55 +00005045 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005046 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005047 // Hack: We must pass *ResultType if available in order to set the type
5048 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5049 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5050 // temporary, not a reference, so we should pass Ty.
5051 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5052 // Since this step is never used for a reference directly, we explicitly
5053 // unwrap references here and rewrap them afterwards.
5054 // We also need to create a InitializeTemporary entity for this.
5055 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5056 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5057 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5058 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5059 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005060 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005061 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005062 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005063 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005064
Sebastian Redl29526f02011-11-27 16:50:07 +00005065 if (ResultType) {
5066 if ((*ResultType)->isRValueReferenceType())
5067 Ty = S.Context.getRValueReferenceType(Ty);
5068 else if ((*ResultType)->isLValueReferenceType())
5069 Ty = S.Context.getLValueReferenceType(Ty,
5070 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5071 *ResultType = Ty;
5072 }
5073
5074 InitListExpr *StructuredInitList =
5075 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005076 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005077 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005078 break;
5079 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005080
Sebastian Redled2e5322011-12-22 14:44:04 +00005081 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005082 // When an initializer list is passed for a parameter of type "reference
5083 // to object", we don't get an EK_Temporary entity, but instead an
5084 // EK_Parameter entity with reference type.
5085 // FIXME: This is a hack. Why is this necessary here, but not in other
5086 // places where implicit temporaries are created?
5087 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5088 Entity.getType().getNonReferenceType());
5089 bool UseTemporary = Entity.getType()->isReferenceType();
Sebastian Redled2e5322011-12-22 14:44:04 +00005090 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5091 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00005092 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5093 Entity,
5094 Kind, move(Arg), *Step,
Sebastian Redled2e5322011-12-22 14:44:04 +00005095 ConstructorInitRequiresZeroInit);
5096 break;
5097 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005098
Sebastian Redl29526f02011-11-27 16:50:07 +00005099 case SK_UnwrapInitList:
5100 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5101 break;
5102
5103 case SK_RewrapInitList: {
5104 Expr *E = CurInit.take();
5105 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5106 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5107 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5108 ILE->setSyntacticForm(Syntactic);
5109 ILE->setType(E->getType());
5110 ILE->setValueKind(E->getValueKind());
5111 CurInit = S.Owned(ILE);
5112 break;
5113 }
5114
Sebastian Redled2e5322011-12-22 14:44:04 +00005115 case SK_ConstructorInitialization:
5116 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5117 *Step,
5118 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005120
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005121 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005122 step_iterator NextStep = Step;
5123 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005125 NextStep->Kind == SK_ConstructorInitialization) {
5126 // The need for zero-initialization is recorded directly into
5127 // the call to the object's constructor within the next step.
5128 ConstructorInitRequiresZeroInit = true;
5129 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5130 S.getLangOptions().CPlusPlus &&
5131 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005132 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5133 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005135 Kind.getRange().getBegin());
5136
5137 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5138 TSInfo->getType().getNonLValueExprType(S.Context),
5139 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005140 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005141 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005142 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005143 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005144 break;
5145 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005146
5147 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005148 QualType SourceType = CurInit.get()->getType();
5149 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005150 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005151 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5152 if (Result.isInvalid())
5153 return ExprError();
5154 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005155
5156 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005157 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005158 if (ConvTy != Sema::Compatible &&
5159 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005160 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005161 == Sema::Compatible)
5162 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005163 if (CurInitExprRes.isInvalid())
5164 return ExprError();
5165 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005166
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005167 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005168 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5169 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005170 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005171 getAssignmentAction(Entity),
5172 &Complained)) {
5173 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005174 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005175 } else if (Complained)
5176 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005177 break;
5178 }
Eli Friedman78275202009-12-19 08:11:05 +00005179
5180 case SK_StringInit: {
5181 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005182 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005183 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005184 break;
5185 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005186
5187 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005188 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005189 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005190 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005191 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005192
5193 case SK_ArrayInit:
5194 // Okay: we checked everything before creating this step. Note that
5195 // this is a GNU extension.
5196 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005197 << Step->Type << CurInit.get()->getType()
5198 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005199
5200 // If the destination type is an incomplete array type, update the
5201 // type accordingly.
5202 if (ResultType) {
5203 if (const IncompleteArrayType *IncompleteDest
5204 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5205 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005206 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005207 *ResultType = S.Context.getConstantArrayType(
5208 IncompleteDest->getElementType(),
5209 ConstantSource->getSize(),
5210 ArrayType::Normal, 0);
5211 }
5212 }
5213 }
John McCall31168b02011-06-15 23:02:42 +00005214 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005215
John McCall31168b02011-06-15 23:02:42 +00005216 case SK_PassByIndirectCopyRestore:
5217 case SK_PassByIndirectRestore:
5218 checkIndirectCopyRestoreSource(S, CurInit.get());
5219 CurInit = S.Owned(new (S.Context)
5220 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5221 Step->Kind == SK_PassByIndirectCopyRestore));
5222 break;
5223
5224 case SK_ProduceObjCObject:
5225 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005226 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005227 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005228 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005229
5230 case SK_StdInitializerList: {
5231 QualType Dest = Step->Type;
5232 QualType E;
5233 bool Success = S.isStdInitializerList(Dest, &E);
5234 (void)Success;
5235 assert(Success && "Destination type changed?");
5236 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5237 unsigned NumInits = ILE->getNumInits();
5238 SmallVector<Expr*, 16> Converted(NumInits);
5239 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5240 S.Context.getConstantArrayType(E,
5241 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5242 NumInits),
5243 ArrayType::Normal, 0));
5244 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5245 0, HiddenArray);
5246 for (unsigned i = 0; i < NumInits; ++i) {
5247 Element.setElementIndex(i);
5248 ExprResult Init = S.Owned(ILE->getInit(i));
5249 ExprResult Res = S.PerformCopyInitialization(Element,
5250 Init.get()->getExprLoc(),
5251 Init);
5252 assert(!Res.isInvalid() && "Result changed since try phase.");
5253 Converted[i] = Res.take();
5254 }
5255 InitListExpr *Semantic = new (S.Context)
5256 InitListExpr(S.Context, ILE->getLBraceLoc(),
5257 Converted.data(), NumInits, ILE->getRBraceLoc());
5258 Semantic->setSyntacticForm(ILE);
5259 Semantic->setType(Dest);
5260 CurInit = S.Owned(Semantic);
5261 break;
5262 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005263 }
5264 }
John McCall1f425642010-11-11 03:21:53 +00005265
5266 // Diagnose non-fatal problems with the completed initialization.
5267 if (Entity.getKind() == InitializedEntity::EK_Member &&
5268 cast<FieldDecl>(Entity.getDecl())->isBitField())
5269 S.CheckBitFieldInitialization(Kind.getLocation(),
5270 cast<FieldDecl>(Entity.getDecl()),
5271 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 return move(CurInit);
5274}
5275
5276//===----------------------------------------------------------------------===//
5277// Diagnose initialization failures
5278//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005280 const InitializedEntity &Entity,
5281 const InitializationKind &Kind,
5282 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005283 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285
Douglas Gregor1b303932009-12-22 15:35:07 +00005286 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005287 switch (Failure) {
5288 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005289 // FIXME: Customize for the initialized entity?
5290 if (NumArgs == 0)
5291 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5292 << DestType.getNonReferenceType();
5293 else // FIXME: diagnostic below could be better!
5294 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5295 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005296 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005297
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298 case FK_ArrayNeedsInitList:
5299 case FK_ArrayNeedsInitListOrStringLiteral:
5300 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5301 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5302 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregore2f943b2011-02-22 18:29:51 +00005304 case FK_ArrayTypeMismatch:
5305 case FK_NonConstantArrayInit:
5306 S.Diag(Kind.getLocation(),
5307 (Failure == FK_ArrayTypeMismatch
5308 ? diag::err_array_init_different_type
5309 : diag::err_array_init_non_constant_array))
5310 << DestType.getNonReferenceType()
5311 << Args[0]->getType()
5312 << Args[0]->getSourceRange();
5313 break;
5314
John McCalla59dc2f2012-01-05 00:13:19 +00005315 case FK_VariableLengthArrayHasInitializer:
5316 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5317 << Args[0]->getSourceRange();
5318 break;
5319
John McCall16df1e52010-03-30 21:47:33 +00005320 case FK_AddressOfOverloadFailed: {
5321 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005324 true,
5325 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005326 break;
John McCall16df1e52010-03-30 21:47:33 +00005327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005329 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005330 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 switch (FailedOverloadResult) {
5332 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005333 if (Failure == FK_UserConversionOverloadFailed)
5334 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5335 << Args[0]->getType() << DestType
5336 << Args[0]->getSourceRange();
5337 else
5338 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5339 << DestType << Args[0]->getType()
5340 << Args[0]->getSourceRange();
5341
John McCall5c32be02010-08-24 20:38:10 +00005342 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005343 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005345 case OR_No_Viable_Function:
5346 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5347 << Args[0]->getType() << DestType.getNonReferenceType()
5348 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005349 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005350 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005351
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005352 case OR_Deleted: {
5353 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5354 << Args[0]->getType() << DestType.getNonReferenceType()
5355 << Args[0]->getSourceRange();
5356 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005357 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005358 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5359 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005360 if (Ovl == OR_Deleted) {
5361 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005362 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005363 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005364 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005365 }
5366 break;
5367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005369 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005370 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005371 }
5372 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005374 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005375 if (isa<InitListExpr>(Args[0])) {
5376 S.Diag(Kind.getLocation(),
5377 diag::err_lvalue_reference_bind_to_initlist)
5378 << DestType.getNonReferenceType().isVolatileQualified()
5379 << DestType.getNonReferenceType()
5380 << Args[0]->getSourceRange();
5381 break;
5382 }
5383 // Intentional fallthrough
5384
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005385 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005386 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005387 Failure == FK_NonConstLValueReferenceBindingToTemporary
5388 ? diag::err_lvalue_reference_bind_to_temporary
5389 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005390 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005391 << DestType.getNonReferenceType()
5392 << Args[0]->getType()
5393 << Args[0]->getSourceRange();
5394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005395
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005396 case FK_RValueReferenceBindingToLValue:
5397 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005398 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005399 << Args[0]->getSourceRange();
5400 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005401
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005402 case FK_ReferenceInitDropsQualifiers:
5403 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5404 << DestType.getNonReferenceType()
5405 << Args[0]->getType()
5406 << Args[0]->getSourceRange();
5407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005408
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005409 case FK_ReferenceInitFailed:
5410 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5411 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005412 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005413 << Args[0]->getType()
5414 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005415 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5416 Args[0]->getType()->isObjCObjectPointerType())
5417 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
Douglas Gregorb491ed32011-02-19 21:32:49 +00005420 case FK_ConversionFailed: {
5421 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005422 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005423 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005424 << DestType
John McCall086a4642010-11-24 05:12:34 +00005425 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005426 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005427 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005428 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5429 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005430 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5431 Args[0]->getType()->isObjCObjectPointerType())
5432 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005433 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005434 }
John Wiegley01296292011-04-08 18:41:53 +00005435
5436 case FK_ConversionFromPropertyFailed:
5437 // No-op. This error has already been reported.
5438 break;
5439
Douglas Gregor51e77d52009-12-10 17:56:55 +00005440 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005441 SourceRange R;
5442
5443 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005444 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005445 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005446 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005447 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005448
Douglas Gregor8ec51732010-09-08 21:40:08 +00005449 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5450 if (Kind.isCStyleOrFunctionalCast())
5451 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5452 << R;
5453 else
5454 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5455 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005456 break;
5457 }
5458
5459 case FK_ReferenceBindingToInitList:
5460 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5461 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5462 break;
5463
5464 case FK_InitListBadDestinationType:
5465 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5466 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5467 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005469 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005470 case FK_ConstructorOverloadFailed: {
5471 SourceRange ArgsRange;
5472 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005474 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005476 if (Failure == FK_ListConstructorOverloadFailed) {
5477 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5478 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5479 Args = InitList->getInits();
5480 NumArgs = InitList->getNumInits();
5481 }
5482
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005483 // FIXME: Using "DestType" for the entity we're printing is probably
5484 // bad.
5485 switch (FailedOverloadResult) {
5486 case OR_Ambiguous:
5487 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5488 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005489 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5490 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005491 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005493 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005494 if (Kind.getKind() == InitializationKind::IK_Default &&
5495 (Entity.getKind() == InitializedEntity::EK_Base ||
5496 Entity.getKind() == InitializedEntity::EK_Member) &&
5497 isa<CXXConstructorDecl>(S.CurContext)) {
5498 // This is implicit default initialization of a member or
5499 // base within a constructor. If no viable function was
5500 // found, notify the user that she needs to explicitly
5501 // initialize this base/member.
5502 CXXConstructorDecl *Constructor
5503 = cast<CXXConstructorDecl>(S.CurContext);
5504 if (Entity.getKind() == InitializedEntity::EK_Base) {
5505 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5506 << Constructor->isImplicit()
5507 << S.Context.getTypeDeclType(Constructor->getParent())
5508 << /*base=*/0
5509 << Entity.getType();
5510
5511 RecordDecl *BaseDecl
5512 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5513 ->getDecl();
5514 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5515 << S.Context.getTagDeclType(BaseDecl);
5516 } else {
5517 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5518 << Constructor->isImplicit()
5519 << S.Context.getTypeDeclType(Constructor->getParent())
5520 << /*member=*/1
5521 << Entity.getName();
5522 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5523
5524 if (const RecordType *Record
5525 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005527 diag::note_previous_decl)
5528 << S.Context.getTagDeclType(Record->getDecl());
5529 }
5530 break;
5531 }
5532
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005533 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5534 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005535 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005536 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005537
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005538 case OR_Deleted: {
5539 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5540 << true << DestType << ArgsRange;
5541 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005542 OverloadingResult Ovl
5543 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005544 if (Ovl == OR_Deleted) {
5545 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005546 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005547 } else {
5548 llvm_unreachable("Inconsistent overload resolution?");
5549 }
5550 break;
5551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005553 case OR_Success:
5554 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005555 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005556 }
David Blaikie60deeee2012-01-17 08:24:58 +00005557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregor85dabae2009-12-16 01:38:02 +00005559 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005560 if (Entity.getKind() == InitializedEntity::EK_Member &&
5561 isa<CXXConstructorDecl>(S.CurContext)) {
5562 // This is implicit default-initialization of a const member in
5563 // a constructor. Complain that it needs to be explicitly
5564 // initialized.
5565 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5566 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5567 << Constructor->isImplicit()
5568 << S.Context.getTypeDeclType(Constructor->getParent())
5569 << /*const=*/1
5570 << Entity.getName();
5571 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5572 << Entity.getName();
5573 } else {
5574 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5575 << DestType << (bool)DestType->getAs<RecordType>();
5576 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005579 case FK_Incomplete:
5580 S.RequireCompleteType(Kind.getLocation(), DestType,
5581 diag::err_init_incomplete_type);
5582 break;
5583
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005584 case FK_ListInitializationFailed: {
5585 // Run the init list checker again to emit diagnostics.
5586 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5587 QualType DestType = Entity.getType();
5588 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005589 DestType, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005590 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005591 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005592 assert(DiagnoseInitList.HadError() &&
5593 "Inconsistent init list check result.");
5594 break;
5595 }
John McCall4124c492011-10-17 18:40:02 +00005596
5597 case FK_PlaceholderType: {
5598 // FIXME: Already diagnosed!
5599 break;
5600 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005601
5602 case FK_InitListElementCopyFailure: {
5603 // Try to perform all copies again.
5604 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5605 unsigned NumInits = InitList->getNumInits();
5606 QualType DestType = Entity.getType();
5607 QualType E;
5608 bool Success = S.isStdInitializerList(DestType, &E);
5609 (void)Success;
5610 assert(Success && "Where did the std::initializer_list go?");
5611 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5612 S.Context.getConstantArrayType(E,
5613 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5614 NumInits),
5615 ArrayType::Normal, 0));
5616 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5617 0, HiddenArray);
5618 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5619 // where the init list type is wrong, e.g.
5620 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5621 // FIXME: Emit a note if we hit the limit?
5622 int ErrorCount = 0;
5623 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5624 Element.setElementIndex(i);
5625 ExprResult Init = S.Owned(InitList->getInit(i));
5626 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5627 .isInvalid())
5628 ++ErrorCount;
5629 }
5630 break;
5631 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005634 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005635 return true;
5636}
Douglas Gregore1314a62009-12-18 05:02:21 +00005637
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005638void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005639 switch (SequenceKind) {
5640 case FailedSequence: {
5641 OS << "Failed sequence: ";
5642 switch (Failure) {
5643 case FK_TooManyInitsForReference:
5644 OS << "too many initializers for reference";
5645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005647 case FK_ArrayNeedsInitList:
5648 OS << "array requires initializer list";
5649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005651 case FK_ArrayNeedsInitListOrStringLiteral:
5652 OS << "array requires initializer list or string literal";
5653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654
Douglas Gregore2f943b2011-02-22 18:29:51 +00005655 case FK_ArrayTypeMismatch:
5656 OS << "array type mismatch";
5657 break;
5658
5659 case FK_NonConstantArrayInit:
5660 OS << "non-constant array initializer";
5661 break;
5662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005663 case FK_AddressOfOverloadFailed:
5664 OS << "address of overloaded function failed";
5665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005667 case FK_ReferenceInitOverloadFailed:
5668 OS << "overload resolution for reference initialization failed";
5669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005671 case FK_NonConstLValueReferenceBindingToTemporary:
5672 OS << "non-const lvalue reference bound to temporary";
5673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005675 case FK_NonConstLValueReferenceBindingToUnrelated:
5676 OS << "non-const lvalue reference bound to unrelated type";
5677 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005679 case FK_RValueReferenceBindingToLValue:
5680 OS << "rvalue reference bound to an lvalue";
5681 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005683 case FK_ReferenceInitDropsQualifiers:
5684 OS << "reference initialization drops qualifiers";
5685 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005687 case FK_ReferenceInitFailed:
5688 OS << "reference initialization failed";
5689 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005691 case FK_ConversionFailed:
5692 OS << "conversion failed";
5693 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694
John Wiegley01296292011-04-08 18:41:53 +00005695 case FK_ConversionFromPropertyFailed:
5696 OS << "conversion from property failed";
5697 break;
5698
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005699 case FK_TooManyInitsForScalar:
5700 OS << "too many initializers for scalar";
5701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005703 case FK_ReferenceBindingToInitList:
5704 OS << "referencing binding to initializer list";
5705 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005707 case FK_InitListBadDestinationType:
5708 OS << "initializer list for non-aggregate, non-scalar type";
5709 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005711 case FK_UserConversionOverloadFailed:
5712 OS << "overloading failed for user-defined conversion";
5713 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005715 case FK_ConstructorOverloadFailed:
5716 OS << "constructor overloading failed";
5717 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005719 case FK_DefaultInitOfConst:
5720 OS << "default initialization of a const variable";
5721 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005723 case FK_Incomplete:
5724 OS << "initialization of incomplete type";
5725 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005726
5727 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005728 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005729 break;
5730
John McCalla59dc2f2012-01-05 00:13:19 +00005731 case FK_VariableLengthArrayHasInitializer:
5732 OS << "variable length array has an initializer";
5733 break;
5734
John McCall4124c492011-10-17 18:40:02 +00005735 case FK_PlaceholderType:
5736 OS << "initializer expression isn't contextually valid";
5737 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005738
5739 case FK_ListConstructorOverloadFailed:
5740 OS << "list constructor overloading failed";
5741 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005742
5743 case FK_InitListElementCopyFailure:
5744 OS << "copy construction of initializer list element failed";
5745 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005747 OS << '\n';
5748 return;
5749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005751 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005752 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005753 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754
Sebastian Redld201edf2011-06-05 13:59:11 +00005755 case NormalSequence:
5756 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005757 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005760 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5761 if (S != step_begin()) {
5762 OS << " -> ";
5763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005765 switch (S->Kind) {
5766 case SK_ResolveAddressOfOverloadedFunction:
5767 OS << "resolve address of overloaded function";
5768 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005769
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005770 case SK_CastDerivedToBaseRValue:
5771 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005774 case SK_CastDerivedToBaseXValue:
5775 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005778 case SK_CastDerivedToBaseLValue:
5779 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005782 case SK_BindReference:
5783 OS << "bind reference to lvalue";
5784 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005786 case SK_BindReferenceToTemporary:
5787 OS << "bind reference to a temporary";
5788 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005790 case SK_ExtraneousCopyToTemporary:
5791 OS << "extraneous C++03 copy to temporary";
5792 break;
5793
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005794 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005795 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005796 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005797
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005798 case SK_QualificationConversionRValue:
5799 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005800 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005801
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005802 case SK_QualificationConversionXValue:
5803 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005804 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005805
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005806 case SK_QualificationConversionLValue:
5807 OS << "qualification conversion (lvalue)";
5808 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005809
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005810 case SK_ConversionSequence:
5811 OS << "implicit conversion sequence (";
5812 S->ICS->DebugPrint(); // FIXME: use OS
5813 OS << ")";
5814 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005816 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005817 OS << "list aggregate initialization";
5818 break;
5819
5820 case SK_ListConstructorCall:
5821 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005822 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005823
Sebastian Redl29526f02011-11-27 16:50:07 +00005824 case SK_UnwrapInitList:
5825 OS << "unwrap reference initializer list";
5826 break;
5827
5828 case SK_RewrapInitList:
5829 OS << "rewrap reference initializer list";
5830 break;
5831
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005832 case SK_ConstructorInitialization:
5833 OS << "constructor initialization";
5834 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005835
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005836 case SK_ZeroInitialization:
5837 OS << "zero initialization";
5838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005840 case SK_CAssignment:
5841 OS << "C assignment";
5842 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005844 case SK_StringInit:
5845 OS << "string initialization";
5846 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005847
5848 case SK_ObjCObjectConversion:
5849 OS << "Objective-C object conversion";
5850 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005851
5852 case SK_ArrayInit:
5853 OS << "array initialization";
5854 break;
John McCall31168b02011-06-15 23:02:42 +00005855
5856 case SK_PassByIndirectCopyRestore:
5857 OS << "pass by indirect copy and restore";
5858 break;
5859
5860 case SK_PassByIndirectRestore:
5861 OS << "pass by indirect restore";
5862 break;
5863
5864 case SK_ProduceObjCObject:
5865 OS << "Objective-C object retension";
5866 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005867
5868 case SK_StdInitializerList:
5869 OS << "std::initializer_list from initializer list";
5870 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005871 }
5872 }
5873}
5874
5875void InitializationSequence::dump() const {
5876 dump(llvm::errs());
5877}
5878
Richard Smith66e05fe2012-01-18 05:21:49 +00005879static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5880 QualType EntityType,
5881 const Expr *PreInit,
5882 const Expr *PostInit) {
5883 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5884 return;
5885
5886 // A narrowing conversion can only appear as the final implicit conversion in
5887 // an initialization sequence.
5888 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5889 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5890 return;
5891
5892 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5893 const StandardConversionSequence *SCS = 0;
5894 switch (ICS.getKind()) {
5895 case ImplicitConversionSequence::StandardConversion:
5896 SCS = &ICS.Standard;
5897 break;
5898 case ImplicitConversionSequence::UserDefinedConversion:
5899 SCS = &ICS.UserDefined.After;
5900 break;
5901 case ImplicitConversionSequence::AmbiguousConversion:
5902 case ImplicitConversionSequence::EllipsisConversion:
5903 case ImplicitConversionSequence::BadConversion:
5904 return;
5905 }
5906
5907 // Determine the type prior to the narrowing conversion. If a conversion
5908 // operator was used, this may be different from both the type of the entity
5909 // and of the pre-initialization expression.
5910 QualType PreNarrowingType = PreInit->getType();
5911 if (Seq.step_begin() + 1 != Seq.step_end())
5912 PreNarrowingType = Seq.step_end()[-2].Type;
5913
5914 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5915 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005916 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005917 case NK_Not_Narrowing:
5918 // No narrowing occurred.
5919 return;
5920
5921 case NK_Type_Narrowing:
5922 // This was a floating-to-integer conversion, which is always considered a
5923 // narrowing conversion even if the value is a constant and can be
5924 // represented exactly as an integer.
5925 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005926 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5927 diag::warn_init_list_type_narrowing
5928 : S.isSFINAEContext()?
5929 diag::err_init_list_type_narrowing_sfinae
5930 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005931 << PostInit->getSourceRange()
5932 << PreNarrowingType.getLocalUnqualifiedType()
5933 << EntityType.getLocalUnqualifiedType();
5934 break;
5935
5936 case NK_Constant_Narrowing:
5937 // A constant value was narrowed.
5938 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005939 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5940 diag::warn_init_list_constant_narrowing
5941 : S.isSFINAEContext()?
5942 diag::err_init_list_constant_narrowing_sfinae
5943 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005944 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005945 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005946 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005947 break;
5948
5949 case NK_Variable_Narrowing:
5950 // A variable's value may have been narrowed.
5951 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005952 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5953 diag::warn_init_list_variable_narrowing
5954 : S.isSFINAEContext()?
5955 diag::err_init_list_variable_narrowing_sfinae
5956 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005957 << PostInit->getSourceRange()
5958 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005959 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005960 break;
5961 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005962
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005963 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005964 llvm::raw_svector_ostream OS(StaticCast);
5965 OS << "static_cast<";
5966 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5967 // It's important to use the typedef's name if there is one so that the
5968 // fixit doesn't break code using types like int64_t.
5969 //
5970 // FIXME: This will break if the typedef requires qualification. But
5971 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005972 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005973 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5974 OS << BT->getName(S.getLangOptions());
5975 else {
5976 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5977 // with a broken cast.
5978 return;
5979 }
5980 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005981 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5982 << PostInit->getSourceRange()
5983 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005984 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005985 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005986}
5987
Douglas Gregore1314a62009-12-18 05:02:21 +00005988//===----------------------------------------------------------------------===//
5989// Initialization helper functions
5990//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005991bool
5992Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5993 ExprResult Init) {
5994 if (Init.isInvalid())
5995 return false;
5996
5997 Expr *InitE = Init.get();
5998 assert(InitE && "No initialization expression");
5999
6000 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6001 SourceLocation());
6002 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00006003 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00006004}
6005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00006007Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6008 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006009 ExprResult Init,
6010 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006011 if (Init.isInvalid())
6012 return ExprError();
6013
John McCall1f425642010-11-11 03:21:53 +00006014 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00006015 assert(InitE && "No initialization expression?");
6016
6017 if (EqualLoc.isInvalid())
6018 EqualLoc = InitE->getLocStart();
6019
6020 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6021 EqualLoc);
6022 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6023 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006024
Richard Smith66e05fe2012-01-18 05:21:49 +00006025 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6026
6027 if (!Result.isInvalid() && TopLevelOfInitList)
6028 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6029 InitE, Result.get());
6030
6031 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00006032}