blob: b8892b5e978c36876ab7e60a5200b90d3b032a5d [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();
1514 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1515 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1516 return IF;
1517 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001518 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001519 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001520}
1521
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1529 DIE->size(), IndexExprs.data(),
1530 NumIndexExprs, DIE->getEqualOrColonLoc(),
1531 DIE->usesGNUSyntax(), DIE->getInit());
1532}
1533
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001534namespace {
1535
1536// Callback to only accept typo corrections that are for field members of
1537// the given struct or union.
1538class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1539 public:
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1541 : Record(RD) {}
1542
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1546 }
1547
1548 private:
1549 RecordDecl *Record;
1550};
1551
1552}
1553
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001554/// @brief Check the well-formedness of a C99 designated initializer.
1555///
1556/// Determines whether the designated initializer @p DIE, which
1557/// resides at the given @p Index within the initializer list @p
1558/// IList, is well-formed for a current object of type @p DeclType
1559/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001560/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001562///
1563/// @param IList The initializer list in which this designated
1564/// initializer occurs.
1565///
Douglas Gregora5324162009-04-15 04:56:10 +00001566/// @param DIE The designated initializer expression.
1567///
1568/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001569///
1570/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1571/// into which the designation in @p DIE should refer.
1572///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573/// @param NextField If non-NULL and the first designator in @p DIE is
1574/// a field, this will be set to the field declaration corresponding
1575/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001576///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577/// @param NextElementIndex If non-NULL and the first designator in @p
1578/// DIE is an array designator or GNU array-range designator, this
1579/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001580///
1581/// @param Index Index into @p IList where the designated initializer
1582/// @p DIE occurs.
1583///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001584/// @param StructuredList The initializer list expression that
1585/// describes all of the subobject initializers in the order they'll
1586/// actually be initialized.
1587///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001588/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001589bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001590InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001591 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001592 DesignatedInitExpr *DIE,
1593 unsigned DesigIdx,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1597 unsigned &Index,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001602 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001605
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1611
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001614
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1620
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001622 }
1623
Douglas Gregora5324162009-04-15 04:56:10 +00001624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001625 bool IsFirstDesignator = (DesigIdx == 0);
1626 if (!VerifyOnly) {
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1629
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
1632 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1638 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 if (D->isFieldDesignator()) {
1641 // C99 6.7.8p7:
1642 //
1643 // If a designator has the form
1644 //
1645 // . identifier
1646 //
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001649 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651 if (!RT) {
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655 if (!VerifyOnly)
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1657 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 ++Index;
1659 return true;
1660 }
1661
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001665 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001668 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1673 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
1679 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001680 // In verify mode, don't modify the original.
1681 if (VerifyOnly)
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1685 break;
1686 }
1687 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001688 if (KnownField && KnownField == *Field)
1689 break;
1690 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 break;
1692
1693 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 }
1695
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001697 if (VerifyOnly) {
1698 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001700 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001701
Douglas Gregord5846a12009-04-15 06:41:24 +00001702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001706 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001712 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001716 RT->getDecl());
1717 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001718 std::string CorrectedStr(
1719 Corrected.getAsString(SemaRef.getLangOptions()));
1720 std::string CorrectedQuotedStr(
1721 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001724 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001728 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001729 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001730 } else {
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1733 ++Index;
1734 return true;
1735 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001738 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001744 ++Index;
1745 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001746 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001748 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1751 FieldIndex = 0;
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1755 continue;
1756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001758 Field->getIdentifier() == ReplacementField->getIdentifier())
1759 break;
1760
1761 ++FieldIndex;
1762 }
1763 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001764 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001768 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001770 if (!VerifyOnly)
1771 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001772 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773
Douglas Gregora82064c2011-06-29 21:51:31 +00001774 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001775 bool InvalidUse;
1776 if (VerifyOnly)
1777 InvalidUse = !SemaRef.CanUseDecl(*Field);
1778 else
1779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1780 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001781 ++Index;
1782 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001784
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001785 if (!VerifyOnly) {
1786 // Update the designator with the field declaration.
1787 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1793 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001798 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001801 if (!VerifyOnly) {
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1809 << *Field;
1810 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001811 Invalid = true;
1812 }
1813
Chris Lattner001b29c2010-10-10 17:49:49 +00001814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001816 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 if (!VerifyOnly) {
1818 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1822 << *Field;
1823 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001824 Invalid = true;
1825 }
1826
Eli Friedman3fa64df2011-08-23 22:24:57 +00001827 // Check GNU flexible array initializer.
1828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1829 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001830 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831
1832 if (Invalid) {
1833 ++Index;
1834 return true;
1835 }
1836
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842
1843 InitializedEntity MemberEntity =
1844 InitializedEntity::InitializeMember(*Field, &Entity);
1845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001847
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1850 ++Field;
1851 ++FieldIndex;
1852 if (NextField)
1853 *NextField = Field;
1854 StructuredIndex = FieldIndex;
1855 return true;
1856 }
1857 } else {
1858 // Recurse to check later designated subobjects.
1859 QualType FieldType = (*Field)->getType();
1860 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001862 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001863 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001866 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001867 true, false))
1868 return true;
1869 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001870
1871 // Find the position of the next field to be initialized in this
1872 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001875
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1879 if (NextField)
1880 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001882 return false;
1883 }
1884
Douglas Gregor17bd0942009-01-28 23:36:17 +00001885 if (!FinishSubobjectInit)
1886 return false;
1887
Douglas Gregord5846a12009-04-15 06:41:24 +00001888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1890 return hadError;
1891
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Anders Carlsson6cabf312010-01-23 23:23:01 +00001895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001897 return hadError && !prevHadError;
1898 }
1899
1900 // C99 6.7.8p6:
1901 //
1902 // If a designator has the form
1903 //
1904 // [ constant-expression ]
1905 //
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1910 //
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1913 //
1914 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001917 if (!VerifyOnly)
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001920 ++Index;
1921 return true;
1922 }
1923
1924 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001929 DesignatedEndIndex = DesignatedStartIndex;
1930 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001935 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001937 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001938
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001946 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 }
1948
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001954 DesignatedEndIndex
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001958 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001963 ++Index;
1964 return true;
1965 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 } else {
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001969 DesignatedEndIndex
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001981 if (!VerifyOnly &&
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001983 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001985
Douglas Gregor17bd0942009-01-28 23:36:17 +00001986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001988
Douglas Gregor17bd0942009-01-28 23:36:17 +00001989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001995
Douglas Gregor17bd0942009-01-28 23:36:17 +00001996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
1999 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002001 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002004 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002005 (DesignatedStartIndex == DesignatedEndIndex),
2006 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002007 return true;
2008
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2012 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002013
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002018 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002019 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002020 return false;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor17bd0942009-01-28 23:36:17 +00002023 if (!FinishSubobjectInit)
2024 return false;
2025
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002026 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002029 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002031 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002032}
2033
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002034// Get the structured initializer list for a subobject of type
2035// @p CurrentObjectType.
2036InitListExpr *
2037InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002042 if (VerifyOnly)
2043 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
2046 ExistingInit = SyntacticToSemantic[IList];
2047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2051 return Result;
2052
2053 if (ExistingInit) {
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002058 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002061 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002065 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002066 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002068 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002070 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002071 << ExistingInit->getSourceRange();
2072 }
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2076 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002077 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002078
Douglas Gregora8a089b2010-07-13 18:40:04 +00002079 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002080
Douglas Gregor6d00c992009-03-20 23:58:33 +00002081 // Pre-allocate storage for the structured initializer list.
2082 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002083 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002084 bool GotNumInits = false;
2085 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002086 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002087 GotNumInits = true;
2088 } else if (Index < IList->getNumInits()) {
2089 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002090 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002091 GotNumInits = true;
2092 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002093 }
2094
Mike Stump11289f42009-09-09 15:08:12 +00002095 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002096 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2097 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2098 NumElements = CAType->getSize().getZExtValue();
2099 // Simple heuristic so that we don't allocate a very large
2100 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002101 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002102 NumElements = 0;
2103 }
John McCall9dd450b2009-09-21 23:43:11 +00002104 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002106 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002107 RecordDecl *RDecl = RType->getDecl();
2108 if (RDecl->isUnion())
2109 NumElements = 1;
2110 else
Mike Stump11289f42009-09-09 15:08:12 +00002111 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002112 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002113 }
2114
Ted Kremenekac034612010-04-13 23:39:13 +00002115 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002116
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 // Link this new initializer list into the structured initializer
2118 // lists.
2119 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002120 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 else {
2122 Result->setSyntacticForm(IList);
2123 SyntacticToSemantic[IList] = Result;
2124 }
2125
2126 return Result;
2127}
2128
2129/// Update the initializer at index @p StructuredIndex within the
2130/// structured initializer list to the value @p expr.
2131void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2132 unsigned &StructuredIndex,
2133 Expr *expr) {
2134 // No structured initializer list to update
2135 if (!StructuredList)
2136 return;
2137
Ted Kremenekac034612010-04-13 23:39:13 +00002138 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2139 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002141 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002142 diag::warn_initializer_overrides)
2143 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002144 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002146 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002147 << PrevInit->getSourceRange();
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002150 ++StructuredIndex;
2151}
2152
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002153/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002154/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002155/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002156/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002157/// failure. Returns the index expression, possibly with an implicit cast
2158/// added, on success. If everything went okay, Value will receive the
2159/// value of the constant expression.
2160static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002161CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162 SourceLocation Loc = Index->getSourceRange().getBegin();
2163
2164 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002165 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2166 if (Result.isInvalid())
2167 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002169 if (Value.isSigned() && Value.isNegative())
2170 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 << Value.toString(10) << Index->getSourceRange();
2172
Douglas Gregor51650d32009-01-23 21:04:18 +00002173 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002174 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175}
2176
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002178 SourceLocation Loc,
2179 bool GNUSyntax,
2180 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181 typedef DesignatedInitExpr::Designator ASTDesignator;
2182
2183 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002184 SmallVector<ASTDesignator, 32> Designators;
2185 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002186
2187 // Build designators and check array designator expressions.
2188 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2189 const Designator &D = Desig.getDesignator(Idx);
2190 switch (D.getKind()) {
2191 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002192 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002193 D.getFieldLoc()));
2194 break;
2195
2196 case Designator::ArrayDesignator: {
2197 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2198 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002199 if (!Index->isTypeDependent() && !Index->isValueDependent())
2200 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2201 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202 Invalid = true;
2203 else {
2204 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002205 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002206 D.getRBracketLoc()));
2207 InitExpressions.push_back(Index);
2208 }
2209 break;
2210 }
2211
2212 case Designator::ArrayRangeDesignator: {
2213 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2214 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2215 llvm::APSInt StartValue;
2216 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002217 bool StartDependent = StartIndex->isTypeDependent() ||
2218 StartIndex->isValueDependent();
2219 bool EndDependent = EndIndex->isTypeDependent() ||
2220 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002221 if (!StartDependent)
2222 StartIndex =
2223 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2224 if (!EndDependent)
2225 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2226
2227 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002228 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else {
2230 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002231 if (StartDependent || EndDependent) {
2232 // Nothing to compute.
2233 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002234 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002236 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002237
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002238 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002239 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002240 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002241 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2242 Invalid = true;
2243 } else {
2244 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002245 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002246 D.getEllipsisLoc(),
2247 D.getRBracketLoc()));
2248 InitExpressions.push_back(StartIndex);
2249 InitExpressions.push_back(EndIndex);
2250 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002251 }
2252 break;
2253 }
2254 }
2255 }
2256
2257 if (Invalid || Init.isInvalid())
2258 return ExprError();
2259
2260 // Clear out the expressions within the designation.
2261 Desig.ClearExprs(*this);
2262
2263 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002264 = DesignatedInitExpr::Create(Context,
2265 Designators.data(), Designators.size(),
2266 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002267 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
Richard Smithe4345902011-12-29 21:57:33 +00002269 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002270 Diag(DIE->getLocStart(), diag::ext_designated_init)
2271 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002273 return Owned(DIE);
2274}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276//===----------------------------------------------------------------------===//
2277// Initialization entity
2278//===----------------------------------------------------------------------===//
2279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002281 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002283{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002284 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2285 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002286 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002287 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002288 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002289 Type = VT->getElementType();
2290 } else {
2291 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2292 assert(CT && "Unexpected type");
2293 Kind = EK_ComplexElement;
2294 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002295 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002296}
2297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002299 CXXBaseSpecifier *Base,
2300 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002301{
2302 InitializedEntity Result;
2303 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002304 Result.Base = reinterpret_cast<uintptr_t>(Base);
2305 if (IsInheritedVirtualBase)
2306 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor1b303932009-12-22 15:35:07 +00002308 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 return Result;
2310}
2311
Douglas Gregor85dabae2009-12-16 01:38:02 +00002312DeclarationName InitializedEntity::getName() const {
2313 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002314 case EK_Parameter: {
2315 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2316 return (D ? D->getDeclName() : DeclarationName());
2317 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002318
2319 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Member:
2321 return VariableOrMember->getDeclName();
2322
2323 case EK_Result:
2324 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002325 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002326 case EK_Temporary:
2327 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002328 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002329 case EK_ArrayElement:
2330 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002331 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002332 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002333 return DeclarationName();
2334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335
David Blaikie8a40f702012-01-17 06:56:22 +00002336 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337}
2338
Douglas Gregora4b592a2009-12-19 03:01:41 +00002339DeclaratorDecl *InitializedEntity::getDecl() const {
2340 switch (getKind()) {
2341 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002342 case EK_Member:
2343 return VariableOrMember;
2344
John McCall31168b02011-06-15 23:02:42 +00002345 case EK_Parameter:
2346 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2347
Douglas Gregora4b592a2009-12-19 03:01:41 +00002348 case EK_Result:
2349 case EK_Exception:
2350 case EK_New:
2351 case EK_Temporary:
2352 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002353 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002354 case EK_ArrayElement:
2355 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002356 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002357 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002358 return 0;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie8a40f702012-01-17 06:56:22 +00002361 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002362}
2363
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002364bool InitializedEntity::allowsNRVO() const {
2365 switch (getKind()) {
2366 case EK_Result:
2367 case EK_Exception:
2368 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002370 case EK_Variable:
2371 case EK_Parameter:
2372 case EK_Member:
2373 case EK_New:
2374 case EK_Temporary:
2375 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002376 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 case EK_ArrayElement:
2378 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002379 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002380 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002381 break;
2382 }
2383
2384 return false;
2385}
2386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002387//===----------------------------------------------------------------------===//
2388// Initialization sequence
2389//===----------------------------------------------------------------------===//
2390
2391void InitializationSequence::Step::Destroy() {
2392 switch (Kind) {
2393 case SK_ResolveAddressOfOverloadedFunction:
2394 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002395 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_CastDerivedToBaseLValue:
2397 case SK_BindReference:
2398 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002399 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 case SK_UserConversion:
2401 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002402 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002404 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002405 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002406 case SK_UnwrapInitList:
2407 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002408 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002409 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002410 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002411 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002412 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002413 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002414 case SK_PassByIndirectCopyRestore:
2415 case SK_PassByIndirectRestore:
2416 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002417 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 case SK_ConversionSequence:
2421 delete ICS;
2422 }
2423}
2424
Douglas Gregor838fcc32010-03-26 20:14:36 +00002425bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002426 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002427}
2428
2429bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002430 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433 switch (getFailureKind()) {
2434 case FK_TooManyInitsForReference:
2435 case FK_ArrayNeedsInitList:
2436 case FK_ArrayNeedsInitListOrStringLiteral:
2437 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2438 case FK_NonConstLValueReferenceBindingToTemporary:
2439 case FK_NonConstLValueReferenceBindingToUnrelated:
2440 case FK_RValueReferenceBindingToLValue:
2441 case FK_ReferenceInitDropsQualifiers:
2442 case FK_ReferenceInitFailed:
2443 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002444 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002445 case FK_TooManyInitsForScalar:
2446 case FK_ReferenceBindingToInitList:
2447 case FK_InitListBadDestinationType:
2448 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002449 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002450 case FK_ArrayTypeMismatch:
2451 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002452 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002453 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002454 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002455 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregor838fcc32010-03-26 20:14:36 +00002458 case FK_ReferenceInitOverloadFailed:
2459 case FK_UserConversionOverloadFailed:
2460 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002461 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002462 return FailedOverloadResult == OR_Ambiguous;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
David Blaikie8a40f702012-01-17 06:56:22 +00002465 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002466}
2467
Douglas Gregorb33eed02010-04-16 22:09:46 +00002468bool InitializationSequence::isConstructorInitialization() const {
2469 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2470}
2471
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002472void
2473InitializationSequence
2474::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2475 DeclAccessPair Found,
2476 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Step S;
2478 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2479 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002480 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002481 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002482 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 Steps.push_back(S);
2484}
2485
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002487 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002489 switch (VK) {
2490 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2491 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2492 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 S.Type = BaseType;
2495 Steps.push_back(S);
2496}
2497
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 bool BindingTemporary) {
2500 Step S;
2501 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2502 S.Type = T;
2503 Steps.push_back(S);
2504}
2505
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002506void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2507 Step S;
2508 S.Kind = SK_ExtraneousCopyToTemporary;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002513void
2514InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2515 DeclAccessPair FoundDecl,
2516 QualType T,
2517 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 Step S;
2519 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002520 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002521 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002522 S.Function.Function = Function;
2523 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 Steps.push_back(S);
2525}
2526
2527void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002528 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002530 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002531 switch (VK) {
2532 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002533 S.Kind = SK_QualificationConversionRValue;
2534 break;
John McCall2536c6d2010-08-25 10:28:54 +00002535 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002536 S.Kind = SK_QualificationConversionXValue;
2537 break;
John McCall2536c6d2010-08-25 10:28:54 +00002538 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 S.Kind = SK_QualificationConversionLValue;
2540 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 S.Type = Ty;
2543 Steps.push_back(S);
2544}
2545
2546void InitializationSequence::AddConversionSequenceStep(
2547 const ImplicitConversionSequence &ICS,
2548 QualType T) {
2549 Step S;
2550 S.Kind = SK_ConversionSequence;
2551 S.Type = T;
2552 S.ICS = new ImplicitConversionSequence(ICS);
2553 Steps.push_back(S);
2554}
2555
Douglas Gregor51e77d52009-12-10 17:56:55 +00002556void InitializationSequence::AddListInitializationStep(QualType T) {
2557 Step S;
2558 S.Kind = SK_ListInitialization;
2559 S.Type = T;
2560 Steps.push_back(S);
2561}
2562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002564InitializationSequence
2565::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2566 AccessSpecifier Access,
2567 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002568 bool HadMultipleCandidates,
2569 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002570 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002571 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002572 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002573 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002574 S.Function.Function = Constructor;
2575 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002576 Steps.push_back(S);
2577}
2578
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002579void InitializationSequence::AddZeroInitializationStep(QualType T) {
2580 Step S;
2581 S.Kind = SK_ZeroInitialization;
2582 S.Type = T;
2583 Steps.push_back(S);
2584}
2585
Douglas Gregore1314a62009-12-18 05:02:21 +00002586void InitializationSequence::AddCAssignmentStep(QualType T) {
2587 Step S;
2588 S.Kind = SK_CAssignment;
2589 S.Type = T;
2590 Steps.push_back(S);
2591}
2592
Eli Friedman78275202009-12-19 08:11:05 +00002593void InitializationSequence::AddStringInitStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_StringInit;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002600void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_ObjCObjectConversion;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Douglas Gregore2f943b2011-02-22 18:29:51 +00002607void InitializationSequence::AddArrayInitStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_ArrayInit;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
John McCall31168b02011-06-15 23:02:42 +00002614void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2615 bool shouldCopy) {
2616 Step s;
2617 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2618 : SK_PassByIndirectRestore);
2619 s.Type = type;
2620 Steps.push_back(s);
2621}
2622
2623void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2624 Step S;
2625 S.Kind = SK_ProduceObjCObject;
2626 S.Type = T;
2627 Steps.push_back(S);
2628}
2629
Sebastian Redlc1839b12012-01-17 22:49:42 +00002630void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2631 Step S;
2632 S.Kind = SK_StdInitializerList;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Sebastian Redl29526f02011-11-27 16:50:07 +00002637void InitializationSequence::RewrapReferenceInitList(QualType T,
2638 InitListExpr *Syntactic) {
2639 assert(Syntactic->getNumInits() == 1 &&
2640 "Can only rewrap trivial init lists.");
2641 Step S;
2642 S.Kind = SK_UnwrapInitList;
2643 S.Type = Syntactic->getInit(0)->getType();
2644 Steps.insert(Steps.begin(), S);
2645
2646 S.Kind = SK_RewrapInitList;
2647 S.Type = T;
2648 S.WrappingSyntacticList = Syntactic;
2649 Steps.push_back(S);
2650}
2651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002654 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002655 this->Failure = Failure;
2656 this->FailedOverloadResult = Result;
2657}
2658
2659//===----------------------------------------------------------------------===//
2660// Attempt initialization
2661//===----------------------------------------------------------------------===//
2662
John McCall31168b02011-06-15 23:02:42 +00002663static void MaybeProduceObjCObject(Sema &S,
2664 InitializationSequence &Sequence,
2665 const InitializedEntity &Entity) {
2666 if (!S.getLangOptions().ObjCAutoRefCount) return;
2667
2668 /// When initializing a parameter, produce the value if it's marked
2669 /// __attribute__((ns_consumed)).
2670 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2671 if (!Entity.isParameterConsumed())
2672 return;
2673
2674 assert(Entity.getType()->isObjCRetainableType() &&
2675 "consuming an object of unretainable type?");
2676 Sequence.AddProduceObjCObjectStep(Entity.getType());
2677
2678 /// When initializing a return value, if the return type is a
2679 /// retainable type, then returns need to immediately retain the
2680 /// object. If an autorelease is required, it will be done at the
2681 /// last instant.
2682 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2683 if (!Entity.getType()->isObjCRetainableType())
2684 return;
2685
2686 Sequence.AddProduceObjCObjectStep(Entity.getType());
2687 }
2688}
2689
Sebastian Redled2e5322011-12-22 14:44:04 +00002690/// \brief When initializing from init list via constructor, deal with the
2691/// empty init list and std::initializer_list special cases.
2692///
2693/// \return True if this was a special case, false otherwise.
2694static bool TryListConstructionSpecialCases(Sema &S,
2695 Expr **Args, unsigned NumArgs,
2696 CXXRecordDecl *DestRecordDecl,
2697 QualType DestType,
2698 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002699 // C++11 [dcl.init.list]p3:
Sebastian Redled2e5322011-12-22 14:44:04 +00002700 // List-initialization of an object of type T is defined as follows:
2701 // - If the initializer list has no elements and T is a class type with
2702 // a default constructor, the object is value-initialized.
2703 if (NumArgs == 0) {
2704 if (CXXConstructorDecl *DefaultConstructor =
2705 S.LookupDefaultConstructor(DestRecordDecl)) {
2706 if (DefaultConstructor->isDeleted() ||
2707 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2708 // Fake an overload resolution failure.
2709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2710 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2711 DefaultConstructor->getAccess());
2712 if (FunctionTemplateDecl *ConstructorTmpl =
2713 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2714 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2715 /*ExplicitArgs*/ 0,
2716 Args, NumArgs, CandidateSet,
2717 /*SuppressUserConversions*/ false);
2718 else
2719 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2720 Args, NumArgs, CandidateSet,
2721 /*SuppressUserConversions*/ false);
2722 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002723 InitializationSequence::FK_ListConstructorOverloadFailed,
2724 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002725 } else
2726 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2727 DefaultConstructor->getAccess(),
2728 DestType,
2729 /*MultipleCandidates=*/false,
2730 /*FromInitList=*/true);
2731 return true;
2732 }
2733 }
2734
2735 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002736 QualType E;
2737 if (S.isStdInitializerList(DestType, &E)) {
2738 // Check that each individual element can be copy-constructed. But since we
2739 // have no place to store further information, we'll recalculate everything
2740 // later.
2741 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2742 S.Context.getConstantArrayType(E,
2743 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),NumArgs),
2744 ArrayType::Normal, 0));
2745 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2746 0, HiddenArray);
2747 for (unsigned i = 0; i < NumArgs; ++i) {
2748 Element.setElementIndex(i);
2749 if (!S.CanPerformCopyInitialization(Element, Args[i])) {
2750 Sequence.SetFailed(
2751 InitializationSequence::FK_InitListElementCopyFailure);
2752 return true;
2753 }
2754 }
2755 Sequence.AddStdInitializerListConstructionStep(DestType);
2756 return true;
2757 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002758
2759 // Not a special case.
2760 return false;
2761}
2762
2763/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2764/// enumerates the constructors of the initialized entity and performs overload
2765/// resolution to select the best.
2766/// If FromInitList is true, this is list-initialization of a non-aggregate
2767/// class type.
2768static void TryConstructorInitialization(Sema &S,
2769 const InitializedEntity &Entity,
2770 const InitializationKind &Kind,
2771 Expr **Args, unsigned NumArgs,
2772 QualType DestType,
2773 InitializationSequence &Sequence,
2774 bool FromInitList = false) {
2775 // Check constructor arguments for self reference.
2776 if (DeclaratorDecl *DD = Entity.getDecl())
2777 // Parameters arguments are occassionially constructed with itself,
2778 // for instance, in recursive functions. Skip them.
2779 if (!isa<ParmVarDecl>(DD))
2780 for (unsigned i = 0; i < NumArgs; ++i)
2781 S.CheckSelfReference(DD, Args[i]);
2782
2783 // Build the candidate set directly in the initialization sequence
2784 // structure, so that it will persist if we fail.
2785 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2786 CandidateSet.clear();
2787
2788 // Determine whether we are allowed to call explicit constructors or
2789 // explicit conversion operators.
2790 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2791 Kind.getKind() == InitializationKind::IK_Value ||
2792 Kind.getKind() == InitializationKind::IK_Default);
2793
2794 // The type we're constructing needs to be complete.
2795 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2796 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2797 }
2798
2799 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2800 assert(DestRecordType && "Constructor initialization requires record type");
2801 CXXRecordDecl *DestRecordDecl
2802 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2803
2804 if (FromInitList &&
2805 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2806 DestType, Sequence))
2807 return;
2808
2809 // - Otherwise, if T is a class type, constructors are considered. The
2810 // applicable constructors are enumerated, and the best one is chosen
2811 // through overload resolution.
2812 DeclContext::lookup_iterator Con, ConEnd;
2813 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2814 Con != ConEnd; ++Con) {
2815 NamedDecl *D = *Con;
2816 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2817 bool SuppressUserConversions = false;
2818
2819 // Find the constructor (which may be a template).
2820 CXXConstructorDecl *Constructor = 0;
2821 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2822 if (ConstructorTmpl)
2823 Constructor = cast<CXXConstructorDecl>(
2824 ConstructorTmpl->getTemplatedDecl());
2825 else {
2826 Constructor = cast<CXXConstructorDecl>(D);
2827
2828 // If we're performing copy initialization using a copy constructor, we
2829 // suppress user-defined conversions on the arguments.
2830 // FIXME: Move constructors?
2831 if (Kind.getKind() == InitializationKind::IK_Copy &&
2832 Constructor->isCopyConstructor())
2833 SuppressUserConversions = true;
2834 }
2835
2836 if (!Constructor->isInvalidDecl() &&
2837 (AllowExplicit || !Constructor->isExplicit())) {
2838 if (ConstructorTmpl)
2839 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2840 /*ExplicitArgs*/ 0,
2841 Args, NumArgs, CandidateSet,
2842 SuppressUserConversions);
2843 else
2844 S.AddOverloadCandidate(Constructor, FoundDecl,
2845 Args, NumArgs, CandidateSet,
2846 SuppressUserConversions);
2847 }
2848 }
2849
2850 SourceLocation DeclLoc = Kind.getLocation();
2851
2852 // Perform overload resolution. If it fails, return the failed result.
2853 OverloadCandidateSet::iterator Best;
2854 if (OverloadingResult Result
2855 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002856 Sequence.SetOverloadFailure(FromInitList ?
2857 InitializationSequence::FK_ListConstructorOverloadFailed :
2858 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002859 Result);
2860 return;
2861 }
2862
2863 // C++0x [dcl.init]p6:
2864 // If a program calls for the default initialization of an object
2865 // of a const-qualified type T, T shall be a class type with a
2866 // user-provided default constructor.
2867 if (Kind.getKind() == InitializationKind::IK_Default &&
2868 Entity.getType().isConstQualified() &&
2869 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2870 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2871 return;
2872 }
2873
2874 // Add the constructor initialization step. Any cv-qualification conversion is
2875 // subsumed by the initialization.
2876 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2877 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2878 Sequence.AddConstructorInitializationStep(CtorDecl,
2879 Best->FoundDecl.getAccess(),
2880 DestType, HadMultipleCandidates,
2881 FromInitList);
2882}
2883
Sebastian Redl29526f02011-11-27 16:50:07 +00002884static bool
2885ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2886 Expr *Initializer,
2887 QualType &SourceType,
2888 QualType &UnqualifiedSourceType,
2889 QualType UnqualifiedTargetType,
2890 InitializationSequence &Sequence) {
2891 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2892 S.Context.OverloadTy) {
2893 DeclAccessPair Found;
2894 bool HadMultipleCandidates = false;
2895 if (FunctionDecl *Fn
2896 = S.ResolveAddressOfOverloadedFunction(Initializer,
2897 UnqualifiedTargetType,
2898 false, Found,
2899 &HadMultipleCandidates)) {
2900 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2901 HadMultipleCandidates);
2902 SourceType = Fn->getType();
2903 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2904 } else if (!UnqualifiedTargetType->isRecordType()) {
2905 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2906 return true;
2907 }
2908 }
2909 return false;
2910}
2911
2912static void TryReferenceInitializationCore(Sema &S,
2913 const InitializedEntity &Entity,
2914 const InitializationKind &Kind,
2915 Expr *Initializer,
2916 QualType cv1T1, QualType T1,
2917 Qualifiers T1Quals,
2918 QualType cv2T2, QualType T2,
2919 Qualifiers T2Quals,
2920 InitializationSequence &Sequence);
2921
2922static void TryListInitialization(Sema &S,
2923 const InitializedEntity &Entity,
2924 const InitializationKind &Kind,
2925 InitListExpr *InitList,
2926 InitializationSequence &Sequence);
2927
2928/// \brief Attempt list initialization of a reference.
2929static void TryReferenceListInitialization(Sema &S,
2930 const InitializedEntity &Entity,
2931 const InitializationKind &Kind,
2932 InitListExpr *InitList,
2933 InitializationSequence &Sequence)
2934{
2935 // First, catch C++03 where this isn't possible.
2936 if (!S.getLangOptions().CPlusPlus0x) {
2937 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2938 return;
2939 }
2940
2941 QualType DestType = Entity.getType();
2942 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2943 Qualifiers T1Quals;
2944 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2945
2946 // Reference initialization via an initializer list works thus:
2947 // If the initializer list consists of a single element that is
2948 // reference-related to the referenced type, bind directly to that element
2949 // (possibly creating temporaries).
2950 // Otherwise, initialize a temporary with the initializer list and
2951 // bind to that.
2952 if (InitList->getNumInits() == 1) {
2953 Expr *Initializer = InitList->getInit(0);
2954 QualType cv2T2 = Initializer->getType();
2955 Qualifiers T2Quals;
2956 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2957
2958 // If this fails, creating a temporary wouldn't work either.
2959 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
2960 T1, Sequence))
2961 return;
2962
2963 SourceLocation DeclLoc = Initializer->getLocStart();
2964 bool dummy1, dummy2, dummy3;
2965 Sema::ReferenceCompareResult RefRelationship
2966 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
2967 dummy2, dummy3);
2968 if (RefRelationship >= Sema::Ref_Related) {
2969 // Try to bind the reference here.
2970 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
2971 T1Quals, cv2T2, T2, T2Quals, Sequence);
2972 if (Sequence)
2973 Sequence.RewrapReferenceInitList(cv1T1, InitList);
2974 return;
2975 }
2976 }
2977
2978 // Not reference-related. Create a temporary and bind to that.
2979 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2980
2981 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
2982 if (Sequence) {
2983 if (DestType->isRValueReferenceType() ||
2984 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
2985 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2986 else
2987 Sequence.SetFailed(
2988 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2989 }
2990}
2991
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002992/// \brief Attempt list initialization (C++0x [dcl.init.list])
2993static void TryListInitialization(Sema &S,
2994 const InitializedEntity &Entity,
2995 const InitializationKind &Kind,
2996 InitListExpr *InitList,
2997 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002998 QualType DestType = Entity.getType();
2999
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003000 // C++ doesn't allow scalar initialization with more than one argument.
3001 // But C99 complex numbers are scalars and it makes sense there.
3002 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3003 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3004 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3005 return;
3006 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003007 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003008 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003009 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003010 }
3011 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003012 if (S.getLangOptions().CPlusPlus0x)
3013 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3014 InitList->getNumInits(), DestType, Sequence,
3015 /*FromInitList=*/true);
3016 else
3017 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003018 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003019 }
3020
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003021 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003022 DestType, /*VerifyOnly=*/true,
3023 Kind.getKind() != InitializationKind::IK_Direct ||
3024 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003025 if (CheckInitList.HadError()) {
3026 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3027 return;
3028 }
3029
3030 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003031 Sequence.AddListInitializationStep(DestType);
3032}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033
3034/// \brief Try a reference initialization that involves calling a conversion
3035/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003036static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3037 const InitializedEntity &Entity,
3038 const InitializationKind &Kind,
3039 Expr *Initializer,
3040 bool AllowRValues,
3041 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003042 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003043 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3044 QualType T1 = cv1T1.getUnqualifiedType();
3045 QualType cv2T2 = Initializer->getType();
3046 QualType T2 = cv2T2.getUnqualifiedType();
3047
3048 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003049 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003050 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003052 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003053 ObjCConversion,
3054 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003055 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003056 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003057 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003058 (void)ObjCLifetimeConversion;
3059
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003060 // Build the candidate set directly in the initialization sequence
3061 // structure, so that it will persist if we fail.
3062 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3063 CandidateSet.clear();
3064
3065 // Determine whether we are allowed to call explicit constructors or
3066 // explicit conversion operators.
3067 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003068
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003069 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003070 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3071 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003072 // The type we're converting to is a class type. Enumerate its constructors
3073 // to see if there is a suitable conversion.
3074 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003075
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003076 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003077 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003078 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003079 NamedDecl *D = *Con;
3080 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3081
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003082 // Find the constructor (which may be a template).
3083 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003084 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003085 if (ConstructorTmpl)
3086 Constructor = cast<CXXConstructorDecl>(
3087 ConstructorTmpl->getTemplatedDecl());
3088 else
John McCalla0296f72010-03-19 07:35:19 +00003089 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003091 if (!Constructor->isInvalidDecl() &&
3092 Constructor->isConvertingConstructor(AllowExplicit)) {
3093 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003094 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003095 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003096 &Initializer, 1, CandidateSet,
3097 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003098 else
John McCalla0296f72010-03-19 07:35:19 +00003099 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003100 &Initializer, 1, CandidateSet,
3101 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003104 }
John McCall3696dcb2010-08-17 07:23:57 +00003105 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3106 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Douglas Gregor496e8b342010-05-07 19:42:26 +00003108 const RecordType *T2RecordType = 0;
3109 if ((T2RecordType = T2->getAs<RecordType>()) &&
3110 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003111 // The type we're converting from is a class type, enumerate its conversion
3112 // functions.
3113 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3114
John McCallad371252010-01-20 00:46:10 +00003115 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003116 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003117 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3118 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119 NamedDecl *D = *I;
3120 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3121 if (isa<UsingShadowDecl>(D))
3122 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3125 CXXConversionDecl *Conv;
3126 if (ConvTemplate)
3127 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3128 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003129 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 // If the conversion function doesn't return a reference type,
3132 // it can't be considered for this conversion unless we're allowed to
3133 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134 // FIXME: Do we need to make sure that we only consider conversion
3135 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003136 // break recursion.
3137 if ((AllowExplicit || !Conv->isExplicit()) &&
3138 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3139 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003140 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003141 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003142 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 else
John McCalla0296f72010-03-19 07:35:19 +00003144 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003145 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003146 }
3147 }
3148 }
John McCall3696dcb2010-08-17 07:23:57 +00003149 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3150 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152 SourceLocation DeclLoc = Initializer->getLocStart();
3153
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003155 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003157 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003159
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003161
Chandler Carruth30141632011-02-25 19:41:05 +00003162 // This is the overload that will actually be used for the initialization, so
3163 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003164 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003165
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003166 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 if (isa<CXXConversionDecl>(Function))
3168 T2 = Function->getResultType();
3169 else
3170 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003171
3172 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003174 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003175 T2.getNonLValueExprType(S.Context),
3176 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003179 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003180 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003181 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003182 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003183 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003184 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003185
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003186 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003187 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003188 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003189 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003191 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003192 NewDerivedToBase, NewObjCConversion,
3193 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003194 if (NewRefRelationship == Sema::Ref_Incompatible) {
3195 // If the type we've converted to is not reference-related to the
3196 // type we're looking for, then there is another conversion step
3197 // we need to perform to produce a temporary of the right type
3198 // that we'll be binding to.
3199 ImplicitConversionSequence ICS;
3200 ICS.setStandard();
3201 ICS.Standard = Best->FinalConversion;
3202 T2 = ICS.Standard.getToType(2);
3203 Sequence.AddConversionSequenceStep(ICS, T2);
3204 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003205 Sequence.AddDerivedToBaseCastStep(
3206 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003208 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003209 else if (NewObjCConversion)
3210 Sequence.AddObjCObjectConversionStep(
3211 S.Context.getQualifiedType(T1,
3212 T2.getNonReferenceType().getQualifiers()));
3213
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003215 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003217 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3218 return OR_Success;
3219}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220
Richard Smithc620f552011-10-19 16:55:56 +00003221static void CheckCXX98CompatAccessibleCopy(Sema &S,
3222 const InitializedEntity &Entity,
3223 Expr *CurInitExpr);
3224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3226static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003227 const InitializedEntity &Entity,
3228 const InitializationKind &Kind,
3229 Expr *Initializer,
3230 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003231 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003232 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003233 Qualifiers T1Quals;
3234 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003235 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003236 Qualifiers T2Quals;
3237 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003238
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003239 // If the initializer is the address of an overloaded function, try
3240 // to resolve the overloaded function. If all goes well, T2 is the
3241 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003242 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3243 T1, Sequence))
3244 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003245
Sebastian Redl29526f02011-11-27 16:50:07 +00003246 // Delegate everything else to a subfunction.
3247 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3248 T1Quals, cv2T2, T2, T2Quals, Sequence);
3249}
3250
3251/// \brief Reference initialization without resolving overloaded functions.
3252static void TryReferenceInitializationCore(Sema &S,
3253 const InitializedEntity &Entity,
3254 const InitializationKind &Kind,
3255 Expr *Initializer,
3256 QualType cv1T1, QualType T1,
3257 Qualifiers T1Quals,
3258 QualType cv2T2, QualType T2,
3259 Qualifiers T2Quals,
3260 InitializationSequence &Sequence) {
3261 QualType DestType = Entity.getType();
3262 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003263 // Compute some basic properties of the types and the initializer.
3264 bool isLValueRef = DestType->isLValueReferenceType();
3265 bool isRValueRef = !isLValueRef;
3266 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003267 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003268 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003269 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003271 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003272 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003273
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 // "cv2 T2" as follows:
3277 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003280 // Note the analogous bullet points for rvlaue refs to functions. Because
3281 // there are no function rvalues in C++, rvalue refs to functions are treated
3282 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003283 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003284 bool T1Function = T1->isFunctionType();
3285 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003287 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003289 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 // reference-compatible with "cv2 T2," or
3292 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003294 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003295 // can occur. However, we do pay attention to whether it is a bit-field
3296 // to decide whether we're actually binding to a temporary created from
3297 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003298 if (DerivedToBase)
3299 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003301 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003302 else if (ObjCConversion)
3303 Sequence.AddObjCObjectConversionStep(
3304 S.Context.getQualifiedType(T1, T2Quals));
3305
Chandler Carruth04bdce62010-01-12 20:32:25 +00003306 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003307 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003308 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003309 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003310 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003311 return;
3312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313
3314 // - has a class type (i.e., T2 is a class type), where T1 is not
3315 // reference-related to T2, and can be implicitly converted to an
3316 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3317 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003318 // applicable conversion functions (13.3.1.6) and choosing the best
3319 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003320 // If we have an rvalue ref to function type here, the rhs must be
3321 // an rvalue.
3322 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3323 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003325 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003326 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 Sequence);
3328 if (ConvOvlResult == OR_Success)
3329 return;
John McCall0d1da222010-01-12 00:44:57 +00003330 if (ConvOvlResult != OR_No_Viable_Function) {
3331 Sequence.SetOverloadFailure(
3332 InitializationSequence::FK_ReferenceInitOverloadFailed,
3333 ConvOvlResult);
3334 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003335 }
3336 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003337
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003338 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003340 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003341 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003342 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3343 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3344 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003345 Sequence.SetOverloadFailure(
3346 InitializationSequence::FK_ReferenceInitOverloadFailed,
3347 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003348 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003349 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003350 ? (RefRelationship == Sema::Ref_Related
3351 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3352 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3353 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003354
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 return;
3356 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003357
Douglas Gregor92e460e2011-01-20 16:44:54 +00003358 // - If the initializer expression
3359 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3360 // "cv1 T1" is reference-compatible with "cv2 T2"
3361 // Note: functions are handled below.
3362 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003363 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003365 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003366 (InitCategory.isXValue() ||
3367 (InitCategory.isPRValue() && T2->isRecordType()) ||
3368 (InitCategory.isPRValue() && T2->isArrayType()))) {
3369 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3370 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003371 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3372 // compiler the freedom to perform a copy here or bind to the
3373 // object, while C++0x requires that we bind directly to the
3374 // object. Hence, we always bind to the object without making an
3375 // extra copy. However, in C++03 requires that we check for the
3376 // presence of a suitable copy constructor:
3377 //
3378 // The constructor that would be used to make the copy shall
3379 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003380 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003381 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003382 else if (S.getLangOptions().CPlusPlus0x)
3383 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
Douglas Gregor92e460e2011-01-20 16:44:54 +00003386 if (DerivedToBase)
3387 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3388 ValueKind);
3389 else if (ObjCConversion)
3390 Sequence.AddObjCObjectConversionStep(
3391 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor92e460e2011-01-20 16:44:54 +00003393 if (T1Quals != T2Quals)
3394 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003396 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
3400 // - has a class type (i.e., T2 is a class type), where T1 is not
3401 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003402 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3403 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003404 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 if (RefRelationship == Sema::Ref_Incompatible) {
3406 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3407 Kind, Initializer,
3408 /*AllowRValues=*/true,
3409 Sequence);
3410 if (ConvOvlResult)
3411 Sequence.SetOverloadFailure(
3412 InitializationSequence::FK_ReferenceInitOverloadFailed,
3413 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 return;
3416 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003418 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3419 return;
3420 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003421
3422 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003423 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003425 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003426
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003427 // Determine whether we are allowed to call explicit constructors or
3428 // explicit conversion operators.
3429 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003430
3431 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3432
John McCall31168b02011-06-15 23:02:42 +00003433 ImplicitConversionSequence ICS
3434 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003435 /*SuppressUserConversions*/ false,
3436 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003437 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003438 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3439 /*AllowObjCWritebackConversion=*/false);
3440
3441 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 // FIXME: Use the conversion function set stored in ICS to turn
3443 // this into an overloading ambiguity diagnostic. However, we need
3444 // to keep that set as an OverloadCandidateSet rather than as some
3445 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003446 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3447 Sequence.SetOverloadFailure(
3448 InitializationSequence::FK_ReferenceInitOverloadFailed,
3449 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003450 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3451 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003452 else
3453 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003454 return;
John McCall31168b02011-06-15 23:02:42 +00003455 } else {
3456 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003457 }
3458
3459 // [...] If T1 is reference-related to T2, cv1 must be the
3460 // same cv-qualification as, or greater cv-qualification
3461 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003462 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3463 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003465 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003466 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3467 return;
3468 }
3469
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003471 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003473 InitCategory.isLValue()) {
3474 Sequence.SetFailed(
3475 InitializationSequence::FK_RValueReferenceBindingToLValue);
3476 return;
3477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003479 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3480 return;
3481}
3482
3483/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484/// (C++ [dcl.init.string], C99 6.7.8).
3485static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003486 const InitializedEntity &Entity,
3487 const InitializationKind &Kind,
3488 Expr *Initializer,
3489 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003490 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491}
3492
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003493/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003495 const InitializedEntity &Entity,
3496 const InitializationKind &Kind,
3497 InitializationSequence &Sequence) {
3498 // C++ [dcl.init]p5:
3499 //
3500 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003501 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003503 // -- if T is an array type, then each element is value-initialized;
3504 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3505 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003507 if (const RecordType *RT = T->getAs<RecordType>()) {
3508 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3509 // -- if T is a class type (clause 9) with a user-declared
3510 // constructor (12.1), then the default constructor for T is
3511 // called (and the initialization is ill-formed if T has no
3512 // accessible default constructor);
3513 //
3514 // FIXME: we really want to refer to a single subobject of the array,
3515 // but Entity doesn't have a way to capture that (yet).
3516 if (ClassDecl->hasUserDeclaredConstructor())
3517 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003519 // -- if T is a (possibly cv-qualified) non-union class type
3520 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003521 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003522 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003523 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003524 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003525 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003527 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003528 }
3529 }
3530
Douglas Gregor1b303932009-12-22 15:35:07 +00003531 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003532}
3533
Douglas Gregor85dabae2009-12-16 01:38:02 +00003534/// \brief Attempt default initialization (C++ [dcl.init]p6).
3535static void TryDefaultInitialization(Sema &S,
3536 const InitializedEntity &Entity,
3537 const InitializationKind &Kind,
3538 InitializationSequence &Sequence) {
3539 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregor85dabae2009-12-16 01:38:02 +00003541 // C++ [dcl.init]p6:
3542 // To default-initialize an object of type T means:
3543 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003544 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3545
Douglas Gregor85dabae2009-12-16 01:38:02 +00003546 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3547 // constructor for T is called (and the initialization is ill-formed if
3548 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003549 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003550 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3551 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553
Douglas Gregor85dabae2009-12-16 01:38:02 +00003554 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregor85dabae2009-12-16 01:38:02 +00003556 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003558 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003559 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003560 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003561 return;
3562 }
3563
3564 // If the destination type has a lifetime property, zero-initialize it.
3565 if (DestType.getQualifiers().hasObjCLifetime()) {
3566 Sequence.AddZeroInitializationStep(Entity.getType());
3567 return;
3568 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003569}
3570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3572/// which enumerates all conversion functions and performs overload resolution
3573/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003575 const InitializedEntity &Entity,
3576 const InitializationKind &Kind,
3577 Expr *Initializer,
3578 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003579 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003580 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3581 QualType SourceType = Initializer->getType();
3582 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3583 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregor540c3b02009-12-14 17:27:33 +00003585 // Build the candidate set directly in the initialization sequence
3586 // structure, so that it will persist if we fail.
3587 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3588 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Douglas Gregor540c3b02009-12-14 17:27:33 +00003590 // Determine whether we are allowed to call explicit constructors or
3591 // explicit conversion operators.
3592 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003593
Douglas Gregor540c3b02009-12-14 17:27:33 +00003594 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3595 // The type we're converting to is a class type. Enumerate its constructors
3596 // to see if there is a suitable conversion.
3597 CXXRecordDecl *DestRecordDecl
3598 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregord9848152010-04-26 14:36:57 +00003600 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003602 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003603 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003604 Con != ConEnd; ++Con) {
3605 NamedDecl *D = *Con;
3606 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregord9848152010-04-26 14:36:57 +00003608 // Find the constructor (which may be a template).
3609 CXXConstructorDecl *Constructor = 0;
3610 FunctionTemplateDecl *ConstructorTmpl
3611 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003612 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003613 Constructor = cast<CXXConstructorDecl>(
3614 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003615 else
Douglas Gregord9848152010-04-26 14:36:57 +00003616 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
Douglas Gregord9848152010-04-26 14:36:57 +00003618 if (!Constructor->isInvalidDecl() &&
3619 Constructor->isConvertingConstructor(AllowExplicit)) {
3620 if (ConstructorTmpl)
3621 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3622 /*ExplicitArgs*/ 0,
3623 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003624 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003625 else
3626 S.AddOverloadCandidate(Constructor, FoundDecl,
3627 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003628 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630 }
Douglas Gregord9848152010-04-26 14:36:57 +00003631 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003632 }
Eli Friedman78275202009-12-19 08:11:05 +00003633
3634 SourceLocation DeclLoc = Initializer->getLocStart();
3635
Douglas Gregor540c3b02009-12-14 17:27:33 +00003636 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3637 // The type we're converting from is a class type, enumerate its conversion
3638 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003639
Eli Friedman4afe9a32009-12-20 22:12:03 +00003640 // We can only enumerate the conversion functions for a complete type; if
3641 // the type isn't complete, simply skip this step.
3642 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3643 CXXRecordDecl *SourceRecordDecl
3644 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
John McCallad371252010-01-20 00:46:10 +00003646 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003647 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003648 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003650 I != E; ++I) {
3651 NamedDecl *D = *I;
3652 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3653 if (isa<UsingShadowDecl>(D))
3654 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Eli Friedman4afe9a32009-12-20 22:12:03 +00003656 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3657 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003658 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003659 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003660 else
John McCallda4458e2010-03-31 01:36:47 +00003661 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Eli Friedman4afe9a32009-12-20 22:12:03 +00003663 if (AllowExplicit || !Conv->isExplicit()) {
3664 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003665 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003666 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003667 CandidateSet);
3668 else
John McCalla0296f72010-03-19 07:35:19 +00003669 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003670 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003671 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003672 }
3673 }
3674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
3676 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003677 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003678 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003679 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003680 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003682 Result);
3683 return;
3684 }
John McCall0d1da222010-01-12 00:44:57 +00003685
Douglas Gregor540c3b02009-12-14 17:27:33 +00003686 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003687 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003688 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689
Douglas Gregor540c3b02009-12-14 17:27:33 +00003690 if (isa<CXXConstructorDecl>(Function)) {
3691 // Add the user-defined conversion step. Any cv-qualification conversion is
3692 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003693 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3694 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003695 return;
3696 }
3697
3698 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003699 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003700 if (ConvType->getAs<RecordType>()) {
3701 // If we're converting to a class type, there may be an copy if
3702 // the resulting temporary object (possible to create an object of
3703 // a base class type). That copy is not a separate conversion, so
3704 // we just make a note of the actual destination type (possibly a
3705 // base class of the type returned by the conversion function) and
3706 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003707 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3708 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003709 return;
3710 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003711
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003712 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3713 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregor5ab11652010-04-17 22:01:05 +00003715 // If the conversion following the call to the conversion function
3716 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003717 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3718 Best->FinalConversion.Third) {
3719 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003720 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003721 ICS.Standard = Best->FinalConversion;
3722 Sequence.AddConversionSequenceStep(ICS, DestType);
3723 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724}
3725
John McCall31168b02011-06-15 23:02:42 +00003726/// The non-zero enum values here are indexes into diagnostic alternatives.
3727enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3728
3729/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003730static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3731 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003732 // Skip parens.
3733 e = e->IgnoreParens();
3734
3735 // Skip address-of nodes.
3736 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3737 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003738 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003739
3740 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003741 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3742 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003743 case CK_Dependent:
3744 case CK_BitCast:
3745 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003746 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003747 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003748
3749 case CK_ArrayToPointerDecay:
3750 return IIK_nonscalar;
3751
3752 case CK_NullToPointer:
3753 return IIK_okay;
3754
3755 default:
3756 break;
3757 }
3758
3759 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003760 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3761 if (!isAddressOf) return IIK_nonlocal;
3762
3763 VarDecl *var;
3764 if (isa<DeclRefExpr>(e)) {
3765 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3766 if (!var) return IIK_nonlocal;
3767 } else {
3768 var = cast<BlockDeclRefExpr>(e)->getDecl();
3769 }
3770
3771 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003772
3773 // If we have a conditional operator, check both sides.
3774 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003775 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003776 return iik;
3777
John McCall63f84442011-06-27 23:59:58 +00003778 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003779
3780 // These are never scalar.
3781 } else if (isa<ArraySubscriptExpr>(e)) {
3782 return IIK_nonscalar;
3783
3784 // Otherwise, it needs to be a null pointer constant.
3785 } else {
3786 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3787 ? IIK_okay : IIK_nonlocal);
3788 }
3789
3790 return IIK_nonlocal;
3791}
3792
3793/// Check whether the given expression is a valid operand for an
3794/// indirect copy/restore.
3795static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3796 assert(src->isRValue());
3797
John McCall63f84442011-06-27 23:59:58 +00003798 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003799 if (iik == IIK_okay) return;
3800
3801 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3802 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3803 << src->getSourceRange();
3804}
3805
Douglas Gregore2f943b2011-02-22 18:29:51 +00003806/// \brief Determine whether we have compatible array types for the
3807/// purposes of GNU by-copy array initialization.
3808static bool hasCompatibleArrayTypes(ASTContext &Context,
3809 const ArrayType *Dest,
3810 const ArrayType *Source) {
3811 // If the source and destination array types are equivalent, we're
3812 // done.
3813 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3814 return true;
3815
3816 // Make sure that the element types are the same.
3817 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3818 return false;
3819
3820 // The only mismatch we allow is when the destination is an
3821 // incomplete array type and the source is a constant array type.
3822 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3823}
3824
John McCall31168b02011-06-15 23:02:42 +00003825static bool tryObjCWritebackConversion(Sema &S,
3826 InitializationSequence &Sequence,
3827 const InitializedEntity &Entity,
3828 Expr *Initializer) {
3829 bool ArrayDecay = false;
3830 QualType ArgType = Initializer->getType();
3831 QualType ArgPointee;
3832 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3833 ArrayDecay = true;
3834 ArgPointee = ArgArrayType->getElementType();
3835 ArgType = S.Context.getPointerType(ArgPointee);
3836 }
3837
3838 // Handle write-back conversion.
3839 QualType ConvertedArgType;
3840 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3841 ConvertedArgType))
3842 return false;
3843
3844 // We should copy unless we're passing to an argument explicitly
3845 // marked 'out'.
3846 bool ShouldCopy = true;
3847 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3848 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3849
3850 // Do we need an lvalue conversion?
3851 if (ArrayDecay || Initializer->isGLValue()) {
3852 ImplicitConversionSequence ICS;
3853 ICS.setStandard();
3854 ICS.Standard.setAsIdentityConversion();
3855
3856 QualType ResultType;
3857 if (ArrayDecay) {
3858 ICS.Standard.First = ICK_Array_To_Pointer;
3859 ResultType = S.Context.getPointerType(ArgPointee);
3860 } else {
3861 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3862 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3863 }
3864
3865 Sequence.AddConversionSequenceStep(ICS, ResultType);
3866 }
3867
3868 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3869 return true;
3870}
3871
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003872InitializationSequence::InitializationSequence(Sema &S,
3873 const InitializedEntity &Entity,
3874 const InitializationKind &Kind,
3875 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003876 unsigned NumArgs)
3877 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003878 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003880 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881 // The semantics of initializers are as follows. The destination type is
3882 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003883 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003885 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003886 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003887
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003888 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003889 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3890 SequenceKind = DependentSequence;
3891 return;
3892 }
3893
Sebastian Redld201edf2011-06-05 13:59:11 +00003894 // Almost everything is a normal sequence.
3895 setSequenceKind(NormalSequence);
3896
John McCalled75c092010-12-07 22:54:16 +00003897 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003898 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003899 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003900 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3901 if (result.isInvalid()) {
3902 SetFailed(FK_PlaceholderType);
3903 return;
John McCall4124c492011-10-17 18:40:02 +00003904 }
John McCalld5c98ae2011-11-15 01:35:18 +00003905 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003906 }
John McCalled75c092010-12-07 22:54:16 +00003907
John McCall4124c492011-10-17 18:40:02 +00003908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 QualType SourceType;
3910 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003911 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003912 Initializer = Args[0];
3913 if (!isa<InitListExpr>(Initializer))
3914 SourceType = Initializer->getType();
3915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
3917 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003918 // list-initialized (8.5.4).
3919 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003920 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003921 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003924 // - If the destination type is a reference type, see 8.5.3.
3925 if (DestType->isReferenceType()) {
3926 // C++0x [dcl.init.ref]p1:
3927 // A variable declared to be a T& or T&&, that is, "reference to type T"
3928 // (8.3.2), shall be initialized by an object, or function, of type T or
3929 // by an object that can be converted into a T.
3930 // (Therefore, multiple arguments are not permitted.)
3931 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003932 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003933 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003934 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003935 return;
3936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003938 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003939 if (Kind.getKind() == InitializationKind::IK_Value ||
3940 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003941 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 return;
3943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944
Douglas Gregor85dabae2009-12-16 01:38:02 +00003945 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003946 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003947 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003948 return;
3949 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003950
John McCall66884dd2011-02-21 07:22:22 +00003951 // - If the destination type is an array of characters, an array of
3952 // char16_t, an array of char32_t, or an array of wchar_t, and the
3953 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003955 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003956 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00003957 if (Initializer && isa<VariableArrayType>(DestAT)) {
3958 SetFailed(FK_VariableLengthArrayHasInitializer);
3959 return;
3960 }
3961
Douglas Gregore2f943b2011-02-22 18:29:51 +00003962 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003963 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003964 return;
3965 }
3966
Douglas Gregore2f943b2011-02-22 18:29:51 +00003967 // Note: as an GNU C extension, we allow initialization of an
3968 // array from a compound literal that creates an array of the same
3969 // type, so long as the initializer has no side effects.
3970 if (!S.getLangOptions().CPlusPlus && Initializer &&
3971 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3972 Initializer->getType()->isArrayType()) {
3973 const ArrayType *SourceAT
3974 = Context.getAsArrayType(Initializer->getType());
3975 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003976 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003977 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003978 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003979 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003980 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003981 }
3982 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003983 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003984 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003985 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003987 return;
3988 }
Eli Friedman78275202009-12-19 08:11:05 +00003989
John McCall31168b02011-06-15 23:02:42 +00003990 // Determine whether we should consider writeback conversions for
3991 // Objective-C ARC.
3992 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3993 Entity.getKind() == InitializedEntity::EK_Parameter;
3994
3995 // We're at the end of the line for C: it's either a write-back conversion
3996 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003997 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003998 // If allowed, check whether this is an Objective-C writeback conversion.
3999 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004000 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004001 return;
4002 }
4003
4004 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004005 AddCAssignmentStep(DestType);
4006 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004007 return;
4008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009
John McCall31168b02011-06-15 23:02:42 +00004010 assert(S.getLangOptions().CPlusPlus);
4011
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 // - If the destination type is a (possibly cv-qualified) class type:
4013 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014 // - If the initialization is direct-initialization, or if it is
4015 // copy-initialization where the cv-unqualified version of the
4016 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004017 // class of the destination, constructors are considered. [...]
4018 if (Kind.getKind() == InitializationKind::IK_Direct ||
4019 (Kind.getKind() == InitializationKind::IK_Copy &&
4020 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4021 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004023 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004025 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004027 // used) to a derived class thereof are enumerated as described in
4028 // 13.3.1.4, and the best one is chosen through overload resolution
4029 // (13.3).
4030 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004031 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 return;
4033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034
Douglas Gregor85dabae2009-12-16 01:38:02 +00004035 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004036 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004037 return;
4038 }
4039 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
4041 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004043 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004044 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4045 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046 return;
4047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004050 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004051 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004054
4055 ImplicitConversionSequence ICS
4056 = S.TryImplicitConversion(Initializer, Entity.getType(),
4057 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004058 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004059 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004060 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4061 allowObjCWritebackConversion);
4062
4063 if (ICS.isStandard() &&
4064 ICS.Standard.Second == ICK_Writeback_Conversion) {
4065 // Objective-C ARC writeback conversion.
4066
4067 // We should copy unless we're passing to an argument explicitly
4068 // marked 'out'.
4069 bool ShouldCopy = true;
4070 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4071 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4072
4073 // If there was an lvalue adjustment, add it as a separate conversion.
4074 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4075 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4076 ImplicitConversionSequence LvalueICS;
4077 LvalueICS.setStandard();
4078 LvalueICS.Standard.setAsIdentityConversion();
4079 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4080 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004081 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004082 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004083
4084 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004085 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004086 DeclAccessPair dap;
4087 if (Initializer->getType() == Context.OverloadTy &&
4088 !S.ResolveAddressOfOverloadedFunction(Initializer
4089 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004090 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004091 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004092 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004093 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004094 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004095
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004096 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004097 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004098}
4099
4100InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004101 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004102 StepEnd = Steps.end();
4103 Step != StepEnd; ++Step)
4104 Step->Destroy();
4105}
4106
4107//===----------------------------------------------------------------------===//
4108// Perform initialization
4109//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004111getAssignmentAction(const InitializedEntity &Entity) {
4112 switch(Entity.getKind()) {
4113 case InitializedEntity::EK_Variable:
4114 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004115 case InitializedEntity::EK_Exception:
4116 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004117 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004118 return Sema::AA_Initializing;
4119
4120 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004122 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4123 return Sema::AA_Sending;
4124
Douglas Gregore1314a62009-12-18 05:02:21 +00004125 return Sema::AA_Passing;
4126
4127 case InitializedEntity::EK_Result:
4128 return Sema::AA_Returning;
4129
Douglas Gregore1314a62009-12-18 05:02:21 +00004130 case InitializedEntity::EK_Temporary:
4131 // FIXME: Can we tell apart casting vs. converting?
4132 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
Douglas Gregore1314a62009-12-18 05:02:21 +00004134 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004135 case InitializedEntity::EK_ArrayElement:
4136 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004137 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004138 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004139 return Sema::AA_Initializing;
4140 }
4141
David Blaikie8a40f702012-01-17 06:56:22 +00004142 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004143}
4144
Douglas Gregor95562572010-04-24 23:45:46 +00004145/// \brief Whether we should binding a created object as a temporary when
4146/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004147static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004148 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004149 case InitializedEntity::EK_ArrayElement:
4150 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004151 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004152 case InitializedEntity::EK_New:
4153 case InitializedEntity::EK_Variable:
4154 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004155 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004156 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004157 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004158 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004159 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004160 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregore1314a62009-12-18 05:02:21 +00004162 case InitializedEntity::EK_Parameter:
4163 case InitializedEntity::EK_Temporary:
4164 return true;
4165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Douglas Gregore1314a62009-12-18 05:02:21 +00004167 llvm_unreachable("missed an InitializedEntity kind?");
4168}
4169
Douglas Gregor95562572010-04-24 23:45:46 +00004170/// \brief Whether the given entity, when initialized with an object
4171/// created for that initialization, requires destruction.
4172static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4173 switch (Entity.getKind()) {
4174 case InitializedEntity::EK_Member:
4175 case InitializedEntity::EK_Result:
4176 case InitializedEntity::EK_New:
4177 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004178 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004179 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004180 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004181 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004182 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183
Douglas Gregor95562572010-04-24 23:45:46 +00004184 case InitializedEntity::EK_Variable:
4185 case InitializedEntity::EK_Parameter:
4186 case InitializedEntity::EK_Temporary:
4187 case InitializedEntity::EK_ArrayElement:
4188 case InitializedEntity::EK_Exception:
4189 return true;
4190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191
4192 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004193}
4194
Richard Smithc620f552011-10-19 16:55:56 +00004195/// \brief Look for copy and move constructors and constructor templates, for
4196/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4197static void LookupCopyAndMoveConstructors(Sema &S,
4198 OverloadCandidateSet &CandidateSet,
4199 CXXRecordDecl *Class,
4200 Expr *CurInitExpr) {
4201 DeclContext::lookup_iterator Con, ConEnd;
4202 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4203 Con != ConEnd; ++Con) {
4204 CXXConstructorDecl *Constructor = 0;
4205
4206 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4207 // Handle copy/moveconstructors, only.
4208 if (!Constructor || Constructor->isInvalidDecl() ||
4209 !Constructor->isCopyOrMoveConstructor() ||
4210 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4211 continue;
4212
4213 DeclAccessPair FoundDecl
4214 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4215 S.AddOverloadCandidate(Constructor, FoundDecl,
4216 &CurInitExpr, 1, CandidateSet);
4217 continue;
4218 }
4219
4220 // Handle constructor templates.
4221 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4222 if (ConstructorTmpl->isInvalidDecl())
4223 continue;
4224
4225 Constructor = cast<CXXConstructorDecl>(
4226 ConstructorTmpl->getTemplatedDecl());
4227 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4228 continue;
4229
4230 // FIXME: Do we need to limit this to copy-constructor-like
4231 // candidates?
4232 DeclAccessPair FoundDecl
4233 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4234 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4235 &CurInitExpr, 1, CandidateSet, true);
4236 }
4237}
4238
4239/// \brief Get the location at which initialization diagnostics should appear.
4240static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4241 Expr *Initializer) {
4242 switch (Entity.getKind()) {
4243 case InitializedEntity::EK_Result:
4244 return Entity.getReturnLoc();
4245
4246 case InitializedEntity::EK_Exception:
4247 return Entity.getThrowLoc();
4248
4249 case InitializedEntity::EK_Variable:
4250 return Entity.getDecl()->getLocation();
4251
4252 case InitializedEntity::EK_ArrayElement:
4253 case InitializedEntity::EK_Member:
4254 case InitializedEntity::EK_Parameter:
4255 case InitializedEntity::EK_Temporary:
4256 case InitializedEntity::EK_New:
4257 case InitializedEntity::EK_Base:
4258 case InitializedEntity::EK_Delegating:
4259 case InitializedEntity::EK_VectorElement:
4260 case InitializedEntity::EK_ComplexElement:
4261 case InitializedEntity::EK_BlockElement:
4262 return Initializer->getLocStart();
4263 }
4264 llvm_unreachable("missed an InitializedEntity kind?");
4265}
4266
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004267/// \brief Make a (potentially elidable) temporary copy of the object
4268/// provided by the given initializer by calling the appropriate copy
4269/// constructor.
4270///
4271/// \param S The Sema object used for type-checking.
4272///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004273/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004274/// the type of the initializer expression or a superclass thereof.
4275///
4276/// \param Enter The entity being initialized.
4277///
4278/// \param CurInit The initializer expression.
4279///
4280/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4281/// is permitted in C++03 (but not C++0x) when binding a reference to
4282/// an rvalue.
4283///
4284/// \returns An expression that copies the initializer expression into
4285/// a temporary object, or an error expression if a copy could not be
4286/// created.
John McCalldadc5752010-08-24 06:29:42 +00004287static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004288 QualType T,
4289 const InitializedEntity &Entity,
4290 ExprResult CurInit,
4291 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004292 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004293 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004295 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004296 Class = cast<CXXRecordDecl>(Record->getDecl());
4297 if (!Class)
4298 return move(CurInit);
4299
Douglas Gregor5d369002011-01-21 18:05:27 +00004300 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004301 // When certain criteria are met, an implementation is allowed to
4302 // omit the copy/move construction of a class object, even if the
4303 // copy/move constructor and/or destructor for the object have
4304 // side effects. [...]
4305 // - when a temporary class object that has not been bound to a
4306 // reference (12.2) would be copied/moved to a class object
4307 // with the same cv-unqualified type, the copy/move operation
4308 // can be omitted by constructing the temporary object
4309 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004311 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004312 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004314 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004315 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004316 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004317
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004319 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4320 return move(CurInit);
4321
Douglas Gregorf282a762011-01-21 19:38:21 +00004322 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004323 // Only consider constructors and constructor templates. Per
4324 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4325 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004326 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004327 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004329 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4330
Douglas Gregore1314a62009-12-18 05:02:21 +00004331 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004332 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004333 case OR_Success:
4334 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Douglas Gregore1314a62009-12-18 05:02:21 +00004336 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004337 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4338 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4339 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004340 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004341 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004342 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004343 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004344 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004345 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregore1314a62009-12-18 05:02:21 +00004347 case OR_Ambiguous:
4348 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004349 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004350 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004351 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004352 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
Douglas Gregore1314a62009-12-18 05:02:21 +00004354 case OR_Deleted:
4355 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004356 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004357 << CurInitExpr->getSourceRange();
4358 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004359 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004360 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004361 }
4362
Douglas Gregor5ab11652010-04-17 22:01:05 +00004363 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004364 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004365 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004366
Anders Carlssona01874b2010-04-21 18:47:17 +00004367 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004368 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004369
4370 if (IsExtraneousCopy) {
4371 // If this is a totally extraneous copy for C++03 reference
4372 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004373 // expression. We don't generate an (elided) copy operation here
4374 // because doing so would require us to pass down a flag to avoid
4375 // infinite recursion, where each step adds another extraneous,
4376 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004377
Douglas Gregor30b52772010-04-18 07:57:34 +00004378 // Instantiate the default arguments of any extra parameters in
4379 // the selected copy constructor, as if we were going to create a
4380 // proper call to the copy constructor.
4381 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4382 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4383 if (S.RequireCompleteType(Loc, Parm->getType(),
4384 S.PDiag(diag::err_call_incomplete_argument)))
4385 break;
4386
4387 // Build the default argument expression; we don't actually care
4388 // if this succeeds or not, because this routine will complain
4389 // if there was a problem.
4390 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4391 }
4392
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004393 return S.Owned(CurInitExpr);
4394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
Eli Friedmanfa0df832012-02-02 03:46:19 +00004396 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004397
Douglas Gregor5ab11652010-04-17 22:01:05 +00004398 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004399 // constructor call (we might have derived-to-base conversions, or
4400 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004401 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004402 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004403 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004404
Douglas Gregord0ace022010-04-25 00:55:24 +00004405 // Actually perform the constructor call.
4406 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004407 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004408 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004409 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004410 CXXConstructExpr::CK_Complete,
4411 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Douglas Gregord0ace022010-04-25 00:55:24 +00004413 // If we're supposed to bind temporaries, do so.
4414 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4415 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4416 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004417}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004418
Richard Smithc620f552011-10-19 16:55:56 +00004419/// \brief Check whether elidable copy construction for binding a reference to
4420/// a temporary would have succeeded if we were building in C++98 mode, for
4421/// -Wc++98-compat.
4422static void CheckCXX98CompatAccessibleCopy(Sema &S,
4423 const InitializedEntity &Entity,
4424 Expr *CurInitExpr) {
4425 assert(S.getLangOptions().CPlusPlus0x);
4426
4427 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4428 if (!Record)
4429 return;
4430
4431 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4432 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4433 == DiagnosticsEngine::Ignored)
4434 return;
4435
4436 // Find constructors which would have been considered.
4437 OverloadCandidateSet CandidateSet(Loc);
4438 LookupCopyAndMoveConstructors(
4439 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4440
4441 // Perform overload resolution.
4442 OverloadCandidateSet::iterator Best;
4443 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4444
4445 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4446 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4447 << CurInitExpr->getSourceRange();
4448
4449 switch (OR) {
4450 case OR_Success:
4451 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4452 Best->FoundDecl.getAccess(), Diag);
4453 // FIXME: Check default arguments as far as that's possible.
4454 break;
4455
4456 case OR_No_Viable_Function:
4457 S.Diag(Loc, Diag);
4458 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4459 break;
4460
4461 case OR_Ambiguous:
4462 S.Diag(Loc, Diag);
4463 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4464 break;
4465
4466 case OR_Deleted:
4467 S.Diag(Loc, Diag);
4468 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4469 << 1 << Best->Function->isDeleted();
4470 break;
4471 }
4472}
4473
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004474void InitializationSequence::PrintInitLocationNote(Sema &S,
4475 const InitializedEntity &Entity) {
4476 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4477 if (Entity.getDecl()->getLocation().isInvalid())
4478 return;
4479
4480 if (Entity.getDecl()->getDeclName())
4481 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4482 << Entity.getDecl()->getDeclName();
4483 else
4484 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4485 }
4486}
4487
Sebastian Redl112aa822011-07-14 19:07:55 +00004488static bool isReferenceBinding(const InitializationSequence::Step &s) {
4489 return s.Kind == InitializationSequence::SK_BindReference ||
4490 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4491}
4492
Sebastian Redled2e5322011-12-22 14:44:04 +00004493static ExprResult
4494PerformConstructorInitialization(Sema &S,
4495 const InitializedEntity &Entity,
4496 const InitializationKind &Kind,
4497 MultiExprArg Args,
4498 const InitializationSequence::Step& Step,
4499 bool &ConstructorInitRequiresZeroInit) {
4500 unsigned NumArgs = Args.size();
4501 CXXConstructorDecl *Constructor
4502 = cast<CXXConstructorDecl>(Step.Function.Function);
4503 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4504
4505 // Build a call to the selected constructor.
4506 ASTOwningVector<Expr*> ConstructorArgs(S);
4507 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4508 ? Kind.getEqualLoc()
4509 : Kind.getLocation();
4510
4511 if (Kind.getKind() == InitializationKind::IK_Default) {
4512 // Force even a trivial, implicit default constructor to be
4513 // semantically checked. We do this explicitly because we don't build
4514 // the definition for completely trivial constructors.
4515 CXXRecordDecl *ClassDecl = Constructor->getParent();
4516 assert(ClassDecl && "No parent class for constructor.");
4517 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4518 ClassDecl->hasTrivialDefaultConstructor() &&
4519 !Constructor->isUsed(false))
4520 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4521 }
4522
4523 ExprResult CurInit = S.Owned((Expr *)0);
4524
4525 // Determine the arguments required to actually perform the constructor
4526 // call.
4527 if (S.CompleteConstructorCall(Constructor, move(Args),
4528 Loc, ConstructorArgs))
4529 return ExprError();
4530
4531
4532 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4533 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4534 (Kind.getKind() == InitializationKind::IK_Direct ||
4535 Kind.getKind() == InitializationKind::IK_Value)) {
4536 // An explicitly-constructed temporary, e.g., X(1, 2).
4537 unsigned NumExprs = ConstructorArgs.size();
4538 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004539 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004540 S.DiagnoseUseOfDecl(Constructor, Loc);
4541
4542 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4543 if (!TSInfo)
4544 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4545
4546 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4547 Constructor,
4548 TSInfo,
4549 Exprs,
4550 NumExprs,
4551 Kind.getParenRange(),
4552 HadMultipleCandidates,
4553 ConstructorInitRequiresZeroInit));
4554 } else {
4555 CXXConstructExpr::ConstructionKind ConstructKind =
4556 CXXConstructExpr::CK_Complete;
4557
4558 if (Entity.getKind() == InitializedEntity::EK_Base) {
4559 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4560 CXXConstructExpr::CK_VirtualBase :
4561 CXXConstructExpr::CK_NonVirtualBase;
4562 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4563 ConstructKind = CXXConstructExpr::CK_Delegating;
4564 }
4565
4566 // Only get the parenthesis range if it is a direct construction.
4567 SourceRange parenRange =
4568 Kind.getKind() == InitializationKind::IK_Direct ?
4569 Kind.getParenRange() : SourceRange();
4570
4571 // If the entity allows NRVO, mark the construction as elidable
4572 // unconditionally.
4573 if (Entity.allowsNRVO())
4574 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4575 Constructor, /*Elidable=*/true,
4576 move_arg(ConstructorArgs),
4577 HadMultipleCandidates,
4578 ConstructorInitRequiresZeroInit,
4579 ConstructKind,
4580 parenRange);
4581 else
4582 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4583 Constructor,
4584 move_arg(ConstructorArgs),
4585 HadMultipleCandidates,
4586 ConstructorInitRequiresZeroInit,
4587 ConstructKind,
4588 parenRange);
4589 }
4590 if (CurInit.isInvalid())
4591 return ExprError();
4592
4593 // Only check access if all of that succeeded.
4594 S.CheckConstructorAccess(Loc, Constructor, Entity,
4595 Step.Function.FoundDecl.getAccess());
4596 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4597
4598 if (shouldBindAsTemporary(Entity))
4599 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4600
4601 return move(CurInit);
4602}
4603
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004605InitializationSequence::Perform(Sema &S,
4606 const InitializedEntity &Entity,
4607 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004608 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004609 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004610 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004611 unsigned NumArgs = Args.size();
4612 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004613 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615
Sebastian Redld201edf2011-06-05 13:59:11 +00004616 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004617 // If the declaration is a non-dependent, incomplete array type
4618 // that has an initializer, then its type will be completed once
4619 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004620 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004621 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004622 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004623 if (const IncompleteArrayType *ArrayT
4624 = S.Context.getAsIncompleteArrayType(DeclType)) {
4625 // FIXME: We don't currently have the ability to accurately
4626 // compute the length of an initializer list without
4627 // performing full type-checking of the initializer list
4628 // (since we have to determine where braces are implicitly
4629 // introduced and such). So, we fall back to making the array
4630 // type a dependently-sized array type with no specified
4631 // bound.
4632 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4633 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004634
Douglas Gregor51e77d52009-12-10 17:56:55 +00004635 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004636 if (DeclaratorDecl *DD = Entity.getDecl()) {
4637 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4638 TypeLoc TL = TInfo->getTypeLoc();
4639 if (IncompleteArrayTypeLoc *ArrayLoc
4640 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4641 Brackets = ArrayLoc->getBracketsRange();
4642 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004643 }
4644
4645 *ResultType
4646 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4647 /*NumElts=*/0,
4648 ArrayT->getSizeModifier(),
4649 ArrayT->getIndexTypeCVRQualifiers(),
4650 Brackets);
4651 }
4652
4653 }
4654 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004655 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4656 Kind.isExplicitCast());
4657 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658 }
4659
Sebastian Redld201edf2011-06-05 13:59:11 +00004660 // No steps means no initialization.
4661 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004662 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Douglas Gregor1b303932009-12-22 15:35:07 +00004664 QualType DestType = Entity.getType().getNonReferenceType();
4665 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004666 // the same as Entity.getDecl()->getType() in cases involving type merging,
4667 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004668 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004669 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004670 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004671
John McCalldadc5752010-08-24 06:29:42 +00004672 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004675 // grab the only argument out the Args and place it into the "current"
4676 // initializer.
4677 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004678 case SK_ResolveAddressOfOverloadedFunction:
4679 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004680 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004681 case SK_CastDerivedToBaseLValue:
4682 case SK_BindReference:
4683 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004684 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004685 case SK_UserConversion:
4686 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004687 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004688 case SK_QualificationConversionRValue:
4689 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004690 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004691 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004692 case SK_UnwrapInitList:
4693 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004694 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004695 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004696 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004697 case SK_ArrayInit:
4698 case SK_PassByIndirectCopyRestore:
4699 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004700 case SK_ProduceObjCObject:
4701 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004702 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004703 CurInit = Args.get()[0];
4704 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004705 break;
John McCall34376a62010-12-04 03:47:34 +00004706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregore1314a62009-12-18 05:02:21 +00004708 case SK_ConstructorInitialization:
4709 case SK_ZeroInitialization:
4710 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
4713 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004714 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004715 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004716 for (step_iterator Step = step_begin(), StepEnd = step_end();
4717 Step != StepEnd; ++Step) {
4718 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004719 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720
John Wiegley01296292011-04-08 18:41:53 +00004721 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004723 switch (Step->Kind) {
4724 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004726 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004727 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004728 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004729 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004730 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004731 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004734 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004735 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004736 case SK_CastDerivedToBaseLValue: {
4737 // We have a derived-to-base cast that produces either an rvalue or an
4738 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
John McCallcf142162010-08-07 06:22:56 +00004740 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004741
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004742 // Casts to inaccessible base classes are allowed with C-style casts.
4743 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4744 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004745 CurInit.get()->getLocStart(),
4746 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004747 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749
Douglas Gregor88d292c2010-05-13 16:44:06 +00004750 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4751 QualType T = SourceType;
4752 if (const PointerType *Pointer = T->getAs<PointerType>())
4753 T = Pointer->getPointeeType();
4754 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004755 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004756 cast<CXXRecordDecl>(RecordTy->getDecl()));
4757 }
4758
John McCall2536c6d2010-08-25 10:28:54 +00004759 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004760 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004761 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004762 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004763 VK_XValue :
4764 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004765 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4766 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004767 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004768 CurInit.get(),
4769 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004770 break;
4771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004773 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004774 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004775 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4776 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004777 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004778 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004779 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004780 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004781 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004782 }
Anders Carlssona91be642010-01-29 02:47:33 +00004783
John Wiegley01296292011-04-08 18:41:53 +00004784 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004785 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004786 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4787 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004788 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004789 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004790 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004793 // Reference binding does not have any corresponding ASTs.
4794
4795 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004796 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004797 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004798
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004799 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004800
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004801 case SK_BindReferenceToTemporary:
4802 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004803 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004804 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004805
Douglas Gregorfe314812011-06-21 17:03:29 +00004806 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004807 CurInit = new (S.Context) MaterializeTemporaryExpr(
4808 Entity.getType().getNonReferenceType(),
4809 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004810 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004811
4812 // If we're binding to an Objective-C object that has lifetime, we
4813 // need cleanups.
4814 if (S.getLangOptions().ObjCAutoRefCount &&
4815 CurInit.get()->getType()->isObjCLifetimeType())
4816 S.ExprNeedsCleanups = true;
4817
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004818 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004820 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004822 /*IsExtraneousCopy=*/true);
4823 break;
4824
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004825 case SK_UserConversion: {
4826 // We have a user-defined conversion that invokes either a constructor
4827 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004828 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004829 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004830 FunctionDecl *Fn = Step->Function.Function;
4831 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004832 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004833 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004834 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004836 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004837 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004838 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 // Determine the arguments required to actually perform the constructor
4841 // call.
John Wiegley01296292011-04-08 18:41:53 +00004842 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004843 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004844 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004845 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004846 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004848 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004850 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004851 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004852 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004853 CXXConstructExpr::CK_Complete,
4854 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004855 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004856 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004857
Anders Carlssona01874b2010-04-21 18:47:17 +00004858 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004859 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004860 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861
John McCalle3027922010-08-25 11:45:40 +00004862 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004863 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4864 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4865 S.IsDerivedFrom(SourceType, Class))
4866 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867
Douglas Gregor95562572010-04-24 23:45:46 +00004868 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004869 } else {
4870 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004871 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004872 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004873 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004874 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004875
4876 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004877 // derived-to-base conversion? I believe the answer is "no", because
4878 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004879 ExprResult CurInitExprRes =
4880 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4881 FoundFn, Conversion);
4882 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004883 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004884 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004886 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004887 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4888 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004889 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004890 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
John McCalle3027922010-08-25 11:45:40 +00004892 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893
Douglas Gregor95562572010-04-24 23:45:46 +00004894 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Sebastian Redl112aa822011-07-14 19:07:55 +00004897 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004898 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4899
4900 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004901 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004902 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004904 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004905 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004906 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004907 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00004908 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004909 }
4910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
John McCallcf142162010-08-07 06:22:56 +00004912 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004913 CurInit.get()->getType(),
4914 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004915 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004916 if (MaybeBindToTemp)
4917 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004918 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004919 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4920 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004921 break;
4922 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004923
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004924 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004925 case SK_QualificationConversionXValue:
4926 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004927 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004928 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004929 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004930 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004931 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004932 VK_XValue :
4933 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004934 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004935 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004936 }
4937
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004938 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004939 Sema::CheckedConversionKind CCK
4940 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4941 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00004942 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00004943 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004944 ExprResult CurInitExprRes =
4945 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004946 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004947 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004948 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004949 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004950 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952
Douglas Gregor51e77d52009-12-10 17:56:55 +00004953 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004954 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00004955 // Hack: We must pass *ResultType if available in order to set the type
4956 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
4957 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
4958 // temporary, not a reference, so we should pass Ty.
4959 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
4960 // Since this step is never used for a reference directly, we explicitly
4961 // unwrap references here and rewrap them afterwards.
4962 // We also need to create a InitializeTemporary entity for this.
4963 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
4964 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
4965 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
4966 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
4967 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00004968 Kind.getKind() != InitializationKind::IK_Direct ||
4969 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004970 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004971 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004972
Sebastian Redl29526f02011-11-27 16:50:07 +00004973 if (ResultType) {
4974 if ((*ResultType)->isRValueReferenceType())
4975 Ty = S.Context.getRValueReferenceType(Ty);
4976 else if ((*ResultType)->isLValueReferenceType())
4977 Ty = S.Context.getLValueReferenceType(Ty,
4978 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
4979 *ResultType = Ty;
4980 }
4981
4982 InitListExpr *StructuredInitList =
4983 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004984 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00004985 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004986 break;
4987 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004988
Sebastian Redled2e5322011-12-22 14:44:04 +00004989 case SK_ListConstructorCall: {
4990 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
4991 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
4992 CurInit = PerformConstructorInitialization(S, Entity, Kind,
4993 move(Arg), *Step,
4994 ConstructorInitRequiresZeroInit);
4995 break;
4996 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004997
Sebastian Redl29526f02011-11-27 16:50:07 +00004998 case SK_UnwrapInitList:
4999 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5000 break;
5001
5002 case SK_RewrapInitList: {
5003 Expr *E = CurInit.take();
5004 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5005 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5006 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5007 ILE->setSyntacticForm(Syntactic);
5008 ILE->setType(E->getType());
5009 ILE->setValueKind(E->getValueKind());
5010 CurInit = S.Owned(ILE);
5011 break;
5012 }
5013
Sebastian Redled2e5322011-12-22 14:44:04 +00005014 case SK_ConstructorInitialization:
5015 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5016 *Step,
5017 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005018 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005020 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005021 step_iterator NextStep = Step;
5022 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005024 NextStep->Kind == SK_ConstructorInitialization) {
5025 // The need for zero-initialization is recorded directly into
5026 // the call to the object's constructor within the next step.
5027 ConstructorInitRequiresZeroInit = true;
5028 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5029 S.getLangOptions().CPlusPlus &&
5030 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005031 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5032 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005034 Kind.getRange().getBegin());
5035
5036 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5037 TSInfo->getType().getNonLValueExprType(S.Context),
5038 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005039 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005040 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005041 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005042 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005043 break;
5044 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005045
5046 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005047 QualType SourceType = CurInit.get()->getType();
5048 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005049 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005050 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5051 if (Result.isInvalid())
5052 return ExprError();
5053 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005054
5055 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005056 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005057 if (ConvTy != Sema::Compatible &&
5058 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005059 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005060 == Sema::Compatible)
5061 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005062 if (CurInitExprRes.isInvalid())
5063 return ExprError();
5064 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005065
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005066 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005067 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5068 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005069 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005070 getAssignmentAction(Entity),
5071 &Complained)) {
5072 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005073 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005074 } else if (Complained)
5075 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005076 break;
5077 }
Eli Friedman78275202009-12-19 08:11:05 +00005078
5079 case SK_StringInit: {
5080 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005081 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005082 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005083 break;
5084 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005085
5086 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005087 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005088 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005089 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005090 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005091
5092 case SK_ArrayInit:
5093 // Okay: we checked everything before creating this step. Note that
5094 // this is a GNU extension.
5095 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005096 << Step->Type << CurInit.get()->getType()
5097 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005098
5099 // If the destination type is an incomplete array type, update the
5100 // type accordingly.
5101 if (ResultType) {
5102 if (const IncompleteArrayType *IncompleteDest
5103 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5104 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005105 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005106 *ResultType = S.Context.getConstantArrayType(
5107 IncompleteDest->getElementType(),
5108 ConstantSource->getSize(),
5109 ArrayType::Normal, 0);
5110 }
5111 }
5112 }
John McCall31168b02011-06-15 23:02:42 +00005113 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005114
John McCall31168b02011-06-15 23:02:42 +00005115 case SK_PassByIndirectCopyRestore:
5116 case SK_PassByIndirectRestore:
5117 checkIndirectCopyRestoreSource(S, CurInit.get());
5118 CurInit = S.Owned(new (S.Context)
5119 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5120 Step->Kind == SK_PassByIndirectCopyRestore));
5121 break;
5122
5123 case SK_ProduceObjCObject:
5124 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005125 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005126 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005127 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005128
5129 case SK_StdInitializerList: {
5130 QualType Dest = Step->Type;
5131 QualType E;
5132 bool Success = S.isStdInitializerList(Dest, &E);
5133 (void)Success;
5134 assert(Success && "Destination type changed?");
5135 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5136 unsigned NumInits = ILE->getNumInits();
5137 SmallVector<Expr*, 16> Converted(NumInits);
5138 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5139 S.Context.getConstantArrayType(E,
5140 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5141 NumInits),
5142 ArrayType::Normal, 0));
5143 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5144 0, HiddenArray);
5145 for (unsigned i = 0; i < NumInits; ++i) {
5146 Element.setElementIndex(i);
5147 ExprResult Init = S.Owned(ILE->getInit(i));
5148 ExprResult Res = S.PerformCopyInitialization(Element,
5149 Init.get()->getExprLoc(),
5150 Init);
5151 assert(!Res.isInvalid() && "Result changed since try phase.");
5152 Converted[i] = Res.take();
5153 }
5154 InitListExpr *Semantic = new (S.Context)
5155 InitListExpr(S.Context, ILE->getLBraceLoc(),
5156 Converted.data(), NumInits, ILE->getRBraceLoc());
5157 Semantic->setSyntacticForm(ILE);
5158 Semantic->setType(Dest);
5159 CurInit = S.Owned(Semantic);
5160 break;
5161 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005162 }
5163 }
John McCall1f425642010-11-11 03:21:53 +00005164
5165 // Diagnose non-fatal problems with the completed initialization.
5166 if (Entity.getKind() == InitializedEntity::EK_Member &&
5167 cast<FieldDecl>(Entity.getDecl())->isBitField())
5168 S.CheckBitFieldInitialization(Kind.getLocation(),
5169 cast<FieldDecl>(Entity.getDecl()),
5170 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005172 return move(CurInit);
5173}
5174
5175//===----------------------------------------------------------------------===//
5176// Diagnose initialization failures
5177//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005179 const InitializedEntity &Entity,
5180 const InitializationKind &Kind,
5181 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005182 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005183 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005184
Douglas Gregor1b303932009-12-22 15:35:07 +00005185 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005186 switch (Failure) {
5187 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005188 // FIXME: Customize for the initialized entity?
5189 if (NumArgs == 0)
5190 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5191 << DestType.getNonReferenceType();
5192 else // FIXME: diagnostic below could be better!
5193 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5194 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005195 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005197 case FK_ArrayNeedsInitList:
5198 case FK_ArrayNeedsInitListOrStringLiteral:
5199 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5200 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5201 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202
Douglas Gregore2f943b2011-02-22 18:29:51 +00005203 case FK_ArrayTypeMismatch:
5204 case FK_NonConstantArrayInit:
5205 S.Diag(Kind.getLocation(),
5206 (Failure == FK_ArrayTypeMismatch
5207 ? diag::err_array_init_different_type
5208 : diag::err_array_init_non_constant_array))
5209 << DestType.getNonReferenceType()
5210 << Args[0]->getType()
5211 << Args[0]->getSourceRange();
5212 break;
5213
John McCalla59dc2f2012-01-05 00:13:19 +00005214 case FK_VariableLengthArrayHasInitializer:
5215 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5216 << Args[0]->getSourceRange();
5217 break;
5218
John McCall16df1e52010-03-30 21:47:33 +00005219 case FK_AddressOfOverloadFailed: {
5220 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005221 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005222 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005223 true,
5224 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005225 break;
John McCall16df1e52010-03-30 21:47:33 +00005226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005228 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005229 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005230 switch (FailedOverloadResult) {
5231 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005232 if (Failure == FK_UserConversionOverloadFailed)
5233 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5234 << Args[0]->getType() << DestType
5235 << Args[0]->getSourceRange();
5236 else
5237 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5238 << DestType << Args[0]->getType()
5239 << Args[0]->getSourceRange();
5240
John McCall5c32be02010-08-24 20:38:10 +00005241 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005242 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005244 case OR_No_Viable_Function:
5245 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5246 << Args[0]->getType() << DestType.getNonReferenceType()
5247 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005248 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005249 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005251 case OR_Deleted: {
5252 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5253 << Args[0]->getType() << DestType.getNonReferenceType()
5254 << Args[0]->getSourceRange();
5255 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005256 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005257 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5258 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005259 if (Ovl == OR_Deleted) {
5260 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005261 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005262 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005263 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005264 }
5265 break;
5266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005268 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005269 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 }
5271 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005274 if (isa<InitListExpr>(Args[0])) {
5275 S.Diag(Kind.getLocation(),
5276 diag::err_lvalue_reference_bind_to_initlist)
5277 << DestType.getNonReferenceType().isVolatileQualified()
5278 << DestType.getNonReferenceType()
5279 << Args[0]->getSourceRange();
5280 break;
5281 }
5282 // Intentional fallthrough
5283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005286 Failure == FK_NonConstLValueReferenceBindingToTemporary
5287 ? diag::err_lvalue_reference_bind_to_temporary
5288 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005289 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005290 << DestType.getNonReferenceType()
5291 << Args[0]->getType()
5292 << Args[0]->getSourceRange();
5293 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005294
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005295 case FK_RValueReferenceBindingToLValue:
5296 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005297 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298 << Args[0]->getSourceRange();
5299 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005301 case FK_ReferenceInitDropsQualifiers:
5302 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5303 << DestType.getNonReferenceType()
5304 << Args[0]->getType()
5305 << Args[0]->getSourceRange();
5306 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005308 case FK_ReferenceInitFailed:
5309 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5310 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005311 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 << Args[0]->getType()
5313 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005314 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5315 Args[0]->getType()->isObjCObjectPointerType())
5316 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005318
Douglas Gregorb491ed32011-02-19 21:32:49 +00005319 case FK_ConversionFailed: {
5320 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005321 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005322 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 << DestType
John McCall086a4642010-11-24 05:12:34 +00005324 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005325 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005326 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005327 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5328 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005329 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5330 Args[0]->getType()->isObjCObjectPointerType())
5331 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005332 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005333 }
John Wiegley01296292011-04-08 18:41:53 +00005334
5335 case FK_ConversionFromPropertyFailed:
5336 // No-op. This error has already been reported.
5337 break;
5338
Douglas Gregor51e77d52009-12-10 17:56:55 +00005339 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005340 SourceRange R;
5341
5342 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005343 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005344 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005346 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005347
Douglas Gregor8ec51732010-09-08 21:40:08 +00005348 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5349 if (Kind.isCStyleOrFunctionalCast())
5350 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5351 << R;
5352 else
5353 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5354 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005355 break;
5356 }
5357
5358 case FK_ReferenceBindingToInitList:
5359 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5360 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5361 break;
5362
5363 case FK_InitListBadDestinationType:
5364 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5365 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5366 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005368 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005369 case FK_ConstructorOverloadFailed: {
5370 SourceRange ArgsRange;
5371 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005373 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005375 if (Failure == FK_ListConstructorOverloadFailed) {
5376 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5377 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5378 Args = InitList->getInits();
5379 NumArgs = InitList->getNumInits();
5380 }
5381
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005382 // FIXME: Using "DestType" for the entity we're printing is probably
5383 // bad.
5384 switch (FailedOverloadResult) {
5385 case OR_Ambiguous:
5386 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5387 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005388 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5389 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005392 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005393 if (Kind.getKind() == InitializationKind::IK_Default &&
5394 (Entity.getKind() == InitializedEntity::EK_Base ||
5395 Entity.getKind() == InitializedEntity::EK_Member) &&
5396 isa<CXXConstructorDecl>(S.CurContext)) {
5397 // This is implicit default initialization of a member or
5398 // base within a constructor. If no viable function was
5399 // found, notify the user that she needs to explicitly
5400 // initialize this base/member.
5401 CXXConstructorDecl *Constructor
5402 = cast<CXXConstructorDecl>(S.CurContext);
5403 if (Entity.getKind() == InitializedEntity::EK_Base) {
5404 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5405 << Constructor->isImplicit()
5406 << S.Context.getTypeDeclType(Constructor->getParent())
5407 << /*base=*/0
5408 << Entity.getType();
5409
5410 RecordDecl *BaseDecl
5411 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5412 ->getDecl();
5413 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5414 << S.Context.getTagDeclType(BaseDecl);
5415 } else {
5416 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5417 << Constructor->isImplicit()
5418 << S.Context.getTypeDeclType(Constructor->getParent())
5419 << /*member=*/1
5420 << Entity.getName();
5421 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5422
5423 if (const RecordType *Record
5424 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005426 diag::note_previous_decl)
5427 << S.Context.getTagDeclType(Record->getDecl());
5428 }
5429 break;
5430 }
5431
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005432 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5433 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005434 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005435 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005437 case OR_Deleted: {
5438 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5439 << true << DestType << ArgsRange;
5440 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005441 OverloadingResult Ovl
5442 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005443 if (Ovl == OR_Deleted) {
5444 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005445 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005446 } else {
5447 llvm_unreachable("Inconsistent overload resolution?");
5448 }
5449 break;
5450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005451
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005452 case OR_Success:
5453 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005454 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005455 }
David Blaikie60deeee2012-01-17 08:24:58 +00005456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005457
Douglas Gregor85dabae2009-12-16 01:38:02 +00005458 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005459 if (Entity.getKind() == InitializedEntity::EK_Member &&
5460 isa<CXXConstructorDecl>(S.CurContext)) {
5461 // This is implicit default-initialization of a const member in
5462 // a constructor. Complain that it needs to be explicitly
5463 // initialized.
5464 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5465 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5466 << Constructor->isImplicit()
5467 << S.Context.getTypeDeclType(Constructor->getParent())
5468 << /*const=*/1
5469 << Entity.getName();
5470 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5471 << Entity.getName();
5472 } else {
5473 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5474 << DestType << (bool)DestType->getAs<RecordType>();
5475 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005476 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005478 case FK_Incomplete:
5479 S.RequireCompleteType(Kind.getLocation(), DestType,
5480 diag::err_init_incomplete_type);
5481 break;
5482
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005483 case FK_ListInitializationFailed: {
5484 // Run the init list checker again to emit diagnostics.
5485 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5486 QualType DestType = Entity.getType();
5487 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005488 DestType, /*VerifyOnly=*/false,
5489 Kind.getKind() != InitializationKind::IK_Direct ||
5490 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005491 assert(DiagnoseInitList.HadError() &&
5492 "Inconsistent init list check result.");
5493 break;
5494 }
John McCall4124c492011-10-17 18:40:02 +00005495
5496 case FK_PlaceholderType: {
5497 // FIXME: Already diagnosed!
5498 break;
5499 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005500
5501 case FK_InitListElementCopyFailure: {
5502 // Try to perform all copies again.
5503 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5504 unsigned NumInits = InitList->getNumInits();
5505 QualType DestType = Entity.getType();
5506 QualType E;
5507 bool Success = S.isStdInitializerList(DestType, &E);
5508 (void)Success;
5509 assert(Success && "Where did the std::initializer_list go?");
5510 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5511 S.Context.getConstantArrayType(E,
5512 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5513 NumInits),
5514 ArrayType::Normal, 0));
5515 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5516 0, HiddenArray);
5517 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5518 // where the init list type is wrong, e.g.
5519 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5520 // FIXME: Emit a note if we hit the limit?
5521 int ErrorCount = 0;
5522 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5523 Element.setElementIndex(i);
5524 ExprResult Init = S.Owned(InitList->getInit(i));
5525 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5526 .isInvalid())
5527 ++ErrorCount;
5528 }
5529 break;
5530 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005533 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005534 return true;
5535}
Douglas Gregore1314a62009-12-18 05:02:21 +00005536
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005537void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005538 switch (SequenceKind) {
5539 case FailedSequence: {
5540 OS << "Failed sequence: ";
5541 switch (Failure) {
5542 case FK_TooManyInitsForReference:
5543 OS << "too many initializers for reference";
5544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005546 case FK_ArrayNeedsInitList:
5547 OS << "array requires initializer list";
5548 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005550 case FK_ArrayNeedsInitListOrStringLiteral:
5551 OS << "array requires initializer list or string literal";
5552 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553
Douglas Gregore2f943b2011-02-22 18:29:51 +00005554 case FK_ArrayTypeMismatch:
5555 OS << "array type mismatch";
5556 break;
5557
5558 case FK_NonConstantArrayInit:
5559 OS << "non-constant array initializer";
5560 break;
5561
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005562 case FK_AddressOfOverloadFailed:
5563 OS << "address of overloaded function failed";
5564 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005565
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005566 case FK_ReferenceInitOverloadFailed:
5567 OS << "overload resolution for reference initialization failed";
5568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005570 case FK_NonConstLValueReferenceBindingToTemporary:
5571 OS << "non-const lvalue reference bound to temporary";
5572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005574 case FK_NonConstLValueReferenceBindingToUnrelated:
5575 OS << "non-const lvalue reference bound to unrelated type";
5576 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005578 case FK_RValueReferenceBindingToLValue:
5579 OS << "rvalue reference bound to an lvalue";
5580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005582 case FK_ReferenceInitDropsQualifiers:
5583 OS << "reference initialization drops qualifiers";
5584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005586 case FK_ReferenceInitFailed:
5587 OS << "reference initialization failed";
5588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005590 case FK_ConversionFailed:
5591 OS << "conversion failed";
5592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
John Wiegley01296292011-04-08 18:41:53 +00005594 case FK_ConversionFromPropertyFailed:
5595 OS << "conversion from property failed";
5596 break;
5597
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005598 case FK_TooManyInitsForScalar:
5599 OS << "too many initializers for scalar";
5600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005602 case FK_ReferenceBindingToInitList:
5603 OS << "referencing binding to initializer list";
5604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005606 case FK_InitListBadDestinationType:
5607 OS << "initializer list for non-aggregate, non-scalar type";
5608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005610 case FK_UserConversionOverloadFailed:
5611 OS << "overloading failed for user-defined conversion";
5612 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005614 case FK_ConstructorOverloadFailed:
5615 OS << "constructor overloading failed";
5616 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005618 case FK_DefaultInitOfConst:
5619 OS << "default initialization of a const variable";
5620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005622 case FK_Incomplete:
5623 OS << "initialization of incomplete type";
5624 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005625
5626 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005627 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005628 break;
5629
John McCalla59dc2f2012-01-05 00:13:19 +00005630 case FK_VariableLengthArrayHasInitializer:
5631 OS << "variable length array has an initializer";
5632 break;
5633
John McCall4124c492011-10-17 18:40:02 +00005634 case FK_PlaceholderType:
5635 OS << "initializer expression isn't contextually valid";
5636 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005637
5638 case FK_ListConstructorOverloadFailed:
5639 OS << "list constructor overloading failed";
5640 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005641
5642 case FK_InitListElementCopyFailure:
5643 OS << "copy construction of initializer list element failed";
5644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005646 OS << '\n';
5647 return;
5648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005650 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005651 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005652 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653
Sebastian Redld201edf2011-06-05 13:59:11 +00005654 case NormalSequence:
5655 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005656 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005659 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5660 if (S != step_begin()) {
5661 OS << " -> ";
5662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005664 switch (S->Kind) {
5665 case SK_ResolveAddressOfOverloadedFunction:
5666 OS << "resolve address of overloaded function";
5667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005668
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005669 case SK_CastDerivedToBaseRValue:
5670 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5671 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005673 case SK_CastDerivedToBaseXValue:
5674 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5675 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005677 case SK_CastDerivedToBaseLValue:
5678 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5679 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005681 case SK_BindReference:
5682 OS << "bind reference to lvalue";
5683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005685 case SK_BindReferenceToTemporary:
5686 OS << "bind reference to a temporary";
5687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005689 case SK_ExtraneousCopyToTemporary:
5690 OS << "extraneous C++03 copy to temporary";
5691 break;
5692
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005693 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005694 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005695 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005696
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005697 case SK_QualificationConversionRValue:
5698 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005699 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005700
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005701 case SK_QualificationConversionXValue:
5702 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005703 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005704
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005705 case SK_QualificationConversionLValue:
5706 OS << "qualification conversion (lvalue)";
5707 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005709 case SK_ConversionSequence:
5710 OS << "implicit conversion sequence (";
5711 S->ICS->DebugPrint(); // FIXME: use OS
5712 OS << ")";
5713 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005715 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005716 OS << "list aggregate initialization";
5717 break;
5718
5719 case SK_ListConstructorCall:
5720 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005721 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722
Sebastian Redl29526f02011-11-27 16:50:07 +00005723 case SK_UnwrapInitList:
5724 OS << "unwrap reference initializer list";
5725 break;
5726
5727 case SK_RewrapInitList:
5728 OS << "rewrap reference initializer list";
5729 break;
5730
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005731 case SK_ConstructorInitialization:
5732 OS << "constructor initialization";
5733 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005735 case SK_ZeroInitialization:
5736 OS << "zero initialization";
5737 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005739 case SK_CAssignment:
5740 OS << "C assignment";
5741 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005743 case SK_StringInit:
5744 OS << "string initialization";
5745 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005746
5747 case SK_ObjCObjectConversion:
5748 OS << "Objective-C object conversion";
5749 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005750
5751 case SK_ArrayInit:
5752 OS << "array initialization";
5753 break;
John McCall31168b02011-06-15 23:02:42 +00005754
5755 case SK_PassByIndirectCopyRestore:
5756 OS << "pass by indirect copy and restore";
5757 break;
5758
5759 case SK_PassByIndirectRestore:
5760 OS << "pass by indirect restore";
5761 break;
5762
5763 case SK_ProduceObjCObject:
5764 OS << "Objective-C object retension";
5765 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005766
5767 case SK_StdInitializerList:
5768 OS << "std::initializer_list from initializer list";
5769 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005770 }
5771 }
5772}
5773
5774void InitializationSequence::dump() const {
5775 dump(llvm::errs());
5776}
5777
Richard Smith66e05fe2012-01-18 05:21:49 +00005778static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5779 QualType EntityType,
5780 const Expr *PreInit,
5781 const Expr *PostInit) {
5782 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5783 return;
5784
5785 // A narrowing conversion can only appear as the final implicit conversion in
5786 // an initialization sequence.
5787 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5788 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5789 return;
5790
5791 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5792 const StandardConversionSequence *SCS = 0;
5793 switch (ICS.getKind()) {
5794 case ImplicitConversionSequence::StandardConversion:
5795 SCS = &ICS.Standard;
5796 break;
5797 case ImplicitConversionSequence::UserDefinedConversion:
5798 SCS = &ICS.UserDefined.After;
5799 break;
5800 case ImplicitConversionSequence::AmbiguousConversion:
5801 case ImplicitConversionSequence::EllipsisConversion:
5802 case ImplicitConversionSequence::BadConversion:
5803 return;
5804 }
5805
5806 // Determine the type prior to the narrowing conversion. If a conversion
5807 // operator was used, this may be different from both the type of the entity
5808 // and of the pre-initialization expression.
5809 QualType PreNarrowingType = PreInit->getType();
5810 if (Seq.step_begin() + 1 != Seq.step_end())
5811 PreNarrowingType = Seq.step_end()[-2].Type;
5812
5813 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5814 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005815 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005816 case NK_Not_Narrowing:
5817 // No narrowing occurred.
5818 return;
5819
5820 case NK_Type_Narrowing:
5821 // This was a floating-to-integer conversion, which is always considered a
5822 // narrowing conversion even if the value is a constant and can be
5823 // represented exactly as an integer.
5824 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005825 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5826 diag::warn_init_list_type_narrowing
5827 : S.isSFINAEContext()?
5828 diag::err_init_list_type_narrowing_sfinae
5829 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005830 << PostInit->getSourceRange()
5831 << PreNarrowingType.getLocalUnqualifiedType()
5832 << EntityType.getLocalUnqualifiedType();
5833 break;
5834
5835 case NK_Constant_Narrowing:
5836 // A constant value was narrowed.
5837 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005838 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5839 diag::warn_init_list_constant_narrowing
5840 : S.isSFINAEContext()?
5841 diag::err_init_list_constant_narrowing_sfinae
5842 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005843 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005844 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005845 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005846 break;
5847
5848 case NK_Variable_Narrowing:
5849 // A variable's value may have been narrowed.
5850 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005851 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5852 diag::warn_init_list_variable_narrowing
5853 : S.isSFINAEContext()?
5854 diag::err_init_list_variable_narrowing_sfinae
5855 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005856 << PostInit->getSourceRange()
5857 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005858 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005859 break;
5860 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005861
5862 llvm::SmallString<128> StaticCast;
5863 llvm::raw_svector_ostream OS(StaticCast);
5864 OS << "static_cast<";
5865 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5866 // It's important to use the typedef's name if there is one so that the
5867 // fixit doesn't break code using types like int64_t.
5868 //
5869 // FIXME: This will break if the typedef requires qualification. But
5870 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005871 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005872 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5873 OS << BT->getName(S.getLangOptions());
5874 else {
5875 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5876 // with a broken cast.
5877 return;
5878 }
5879 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005880 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5881 << PostInit->getSourceRange()
5882 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005883 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005884 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005885}
5886
Douglas Gregore1314a62009-12-18 05:02:21 +00005887//===----------------------------------------------------------------------===//
5888// Initialization helper functions
5889//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005890bool
5891Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5892 ExprResult Init) {
5893 if (Init.isInvalid())
5894 return false;
5895
5896 Expr *InitE = Init.get();
5897 assert(InitE && "No initialization expression");
5898
5899 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5900 SourceLocation());
5901 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005902 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005903}
5904
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005906Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5907 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005908 ExprResult Init,
5909 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005910 if (Init.isInvalid())
5911 return ExprError();
5912
John McCall1f425642010-11-11 03:21:53 +00005913 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005914 assert(InitE && "No initialization expression?");
5915
5916 if (EqualLoc.isInvalid())
5917 EqualLoc = InitE->getLocStart();
5918
5919 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5920 EqualLoc);
5921 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5922 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005923
Richard Smith66e05fe2012-01-18 05:21:49 +00005924 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5925
5926 if (!Result.isInvalid() && TopLevelOfInitList)
5927 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5928 InitE, Result.get());
5929
5930 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00005931}