blob: 28b99f9e4c3fdb2e9237948210bcd0de39205453 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner9ececce2009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000275
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor2bb07652009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCalldadc5752010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000346}
347
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351void
Douglas Gregor723796a2009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump11289f42009-09-09 15:08:12 +0000391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000409 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCalldadc5752010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redld201edf2011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000471
Douglas Gregor723796a2009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000477
Eli Friedman23a9e312008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000485
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Anders Carlsson6cabf312010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000533 else
David Blaikie83d382b2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000535
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000552
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000565
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000589 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000590 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000591}
592
Anders Carlsson6cabf312010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613
Eli Friedman85f54972008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000632 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman425038c2009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000655
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 }
659 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000660
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 } else if (DeclType->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000731 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000732 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000736 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson6cabf312010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000758 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000766
John McCall5decec92011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
John McCall5decec92011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000778 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 }
John McCall5decec92011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000801
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 }
John McCall5decec92011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley01296292011-04-08 18:41:53 +0000836 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCall5decec92011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000863}
864
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000917 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 }
John McCall643169b2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCall643169b2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
John McCall643169b2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001027}
1028
Anders Carlsson6cabf312010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001038
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall6a16b2f2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
John McCall6a16b2f2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001073 }
1074 }
John McCall6a16b2f2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
John McCall6a16b2f2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001092 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
John McCall6a16b2f2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
John McCall6a16b2f2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
John McCall6a16b2f2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall6a16b2f2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
1143
Anders Carlsson6cabf312010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCall66884dd2011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCall66884dd2011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001233 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001270}
1271
Eli Friedman3fa64df2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson6cabf312010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001321
Eli Friedman23a9e312008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump11289f42009-09-09 15:08:12 +00001327 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001363
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregora9add4e2009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregora9add4e2009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor51695702009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001396 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001397 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001398
Douglas Gregora82064c2011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001418
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001425 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001426
John McCalle40b58e2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 return;
1457
Eli Friedman3fa64df2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474}
Steve Narofff8ecff22008-05-01 22:18:59 +00001475
Douglas Gregord5846a12009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregord5846a12009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506}
Mike Stump11289f42009-09-09 15:08:12 +00001507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001514 while (IndirectFieldDecl *IF =
1515 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001516 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1517 return IF;
1518 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001519 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001520 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001521}
1522
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001523static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1524 DesignatedInitExpr *DIE) {
1525 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1526 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1527 for (unsigned I = 0; I < NumIndexExprs; ++I)
1528 IndexExprs[I] = DIE->getSubExpr(I + 1);
1529 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1530 DIE->size(), IndexExprs.data(),
1531 NumIndexExprs, DIE->getEqualOrColonLoc(),
1532 DIE->usesGNUSyntax(), DIE->getInit());
1533}
1534
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001535namespace {
1536
1537// Callback to only accept typo corrections that are for field members of
1538// the given struct or union.
1539class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1540 public:
1541 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1542 : Record(RD) {}
1543
1544 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1545 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1546 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1547 }
1548
1549 private:
1550 RecordDecl *Record;
1551};
1552
1553}
1554
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001555/// @brief Check the well-formedness of a C99 designated initializer.
1556///
1557/// Determines whether the designated initializer @p DIE, which
1558/// resides at the given @p Index within the initializer list @p
1559/// IList, is well-formed for a current object of type @p DeclType
1560/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001561/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001562/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001563///
1564/// @param IList The initializer list in which this designated
1565/// initializer occurs.
1566///
Douglas Gregora5324162009-04-15 04:56:10 +00001567/// @param DIE The designated initializer expression.
1568///
1569/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001570///
1571/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1572/// into which the designation in @p DIE should refer.
1573///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574/// @param NextField If non-NULL and the first designator in @p DIE is
1575/// a field, this will be set to the field declaration corresponding
1576/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001577///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578/// @param NextElementIndex If non-NULL and the first designator in @p
1579/// DIE is an array designator or GNU array-range designator, this
1580/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001581///
1582/// @param Index Index into @p IList where the designated initializer
1583/// @p DIE occurs.
1584///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001585/// @param StructuredList The initializer list expression that
1586/// describes all of the subobject initializers in the order they'll
1587/// actually be initialized.
1588///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001589/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001590bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001592 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001593 DesignatedInitExpr *DIE,
1594 unsigned DesigIdx,
1595 QualType &CurrentObjectType,
1596 RecordDecl::field_iterator *NextField,
1597 llvm::APSInt *NextElementIndex,
1598 unsigned &Index,
1599 InitListExpr *StructuredList,
1600 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001601 bool FinishSubobjectInit,
1602 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001603 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604 // Check the actual initialization for the designated object type.
1605 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001606
1607 // Temporarily remove the designator expression from the
1608 // initializer list that the child calls see, so that we don't try
1609 // to re-process the designator.
1610 unsigned OldIndex = Index;
1611 IList->setInit(OldIndex, DIE->getInit());
1612
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001613 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001614 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001615
1616 // Restore the designated initializer expression in the syntactic
1617 // form of the initializer list.
1618 if (IList->getInit(OldIndex) != DIE->getInit())
1619 DIE->setInit(IList->getInit(OldIndex));
1620 IList->setInit(OldIndex, DIE);
1621
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001623 }
1624
Douglas Gregora5324162009-04-15 04:56:10 +00001625 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001626 bool IsFirstDesignator = (DesigIdx == 0);
1627 if (!VerifyOnly) {
1628 assert((IsFirstDesignator || StructuredList) &&
1629 "Need a non-designated initializer list to start from");
1630
1631 // Determine the structural initializer list that corresponds to the
1632 // current subobject.
1633 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1634 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1635 StructuredList, StructuredIndex,
1636 SourceRange(D->getStartLocation(),
1637 DIE->getSourceRange().getEnd()));
1638 assert(StructuredList && "Expected a structured initializer list");
1639 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001640
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001641 if (D->isFieldDesignator()) {
1642 // C99 6.7.8p7:
1643 //
1644 // If a designator has the form
1645 //
1646 // . identifier
1647 //
1648 // then the current object (defined below) shall have
1649 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001650 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001651 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 if (!RT) {
1653 SourceLocation Loc = D->getDotLoc();
1654 if (Loc.isInvalid())
1655 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001656 if (!VerifyOnly)
1657 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1658 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001659 ++Index;
1660 return true;
1661 }
1662
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 // Note: we perform a linear search of the fields here, despite
1664 // the fact that we have a faster lookup method, because we always
1665 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001666 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001669 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001670 Field = RT->getDecl()->field_begin(),
1671 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001672 for (; Field != FieldEnd; ++Field) {
1673 if (Field->isUnnamedBitfield())
1674 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001676 // If we find a field representing an anonymous field, look in the
1677 // IndirectFieldDecl that follow for the designated initializer.
1678 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1679 if (IndirectFieldDecl *IF =
1680 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001681 // In verify mode, don't modify the original.
1682 if (VerifyOnly)
1683 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001684 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1685 D = DIE->getDesignator(DesigIdx);
1686 break;
1687 }
1688 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001689 if (KnownField && KnownField == *Field)
1690 break;
1691 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001692 break;
1693
1694 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001695 }
1696
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001697 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001698 if (VerifyOnly) {
1699 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001700 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001701 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702
Douglas Gregord5846a12009-04-15 06:41:24 +00001703 // There was no normal field in the struct with the designated
1704 // name. Perform another lookup for this name, which may find
1705 // something that we can't designate (e.g., a member function),
1706 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001707 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001708 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001709 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001711 // Name lookup didn't find anything. Determine whether this
1712 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001713 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001714 TypoCorrection Corrected = SemaRef.CorrectTypo(
1715 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001716 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001717 RT->getDecl());
1718 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001719 std::string CorrectedStr(
1720 Corrected.getAsString(SemaRef.getLangOptions()));
1721 std::string CorrectedQuotedStr(
1722 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001723 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001724 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001725 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001726 << FieldName << CurrentObjectType << CorrectedQuotedStr
1727 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001729 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001730 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001731 } else {
1732 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1733 << FieldName << CurrentObjectType;
1734 ++Index;
1735 return true;
1736 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001739 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001741 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001742 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001743 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001745 ++Index;
1746 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001747 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001748
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001749 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001750 // The replacement field comes from typo correction; find it
1751 // in the list of fields.
1752 FieldIndex = 0;
1753 Field = RT->getDecl()->field_begin();
1754 for (; Field != FieldEnd; ++Field) {
1755 if (Field->isUnnamedBitfield())
1756 continue;
1757
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001759 Field->getIdentifier() == ReplacementField->getIdentifier())
1760 break;
1761
1762 ++FieldIndex;
1763 }
1764 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001765 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001766
1767 // All of the fields of a union are located at the same place in
1768 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001769 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001770 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001771 if (!VerifyOnly)
1772 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001773 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001774
Douglas Gregora82064c2011-06-29 21:51:31 +00001775 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001776 bool InvalidUse;
1777 if (VerifyOnly)
1778 InvalidUse = !SemaRef.CanUseDecl(*Field);
1779 else
1780 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1781 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001782 ++Index;
1783 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001784 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001785
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001786 if (!VerifyOnly) {
1787 // Update the designator with the field declaration.
1788 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001790 // Make sure that our non-designated initializer list has space
1791 // for a subobject corresponding to this field.
1792 if (FieldIndex >= StructuredList->getNumInits())
1793 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1794 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001796 // This designator names a flexible array member.
1797 if (Field->getType()->isIncompleteArrayType()) {
1798 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001799 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001800 // We can't designate an object within the flexible array
1801 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001802 if (!VerifyOnly) {
1803 DesignatedInitExpr::Designator *NextD
1804 = DIE->getDesignator(DesigIdx + 1);
1805 SemaRef.Diag(NextD->getStartLocation(),
1806 diag::err_designator_into_flexible_array_member)
1807 << SourceRange(NextD->getStartLocation(),
1808 DIE->getSourceRange().getEnd());
1809 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1810 << *Field;
1811 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001812 Invalid = true;
1813 }
1814
Chris Lattner001b29c2010-10-10 17:49:49 +00001815 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1816 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001817 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001818 if (!VerifyOnly) {
1819 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1820 diag::err_flexible_array_init_needs_braces)
1821 << DIE->getInit()->getSourceRange();
1822 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1823 << *Field;
1824 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001825 Invalid = true;
1826 }
1827
Eli Friedman3fa64df2011-08-23 22:24:57 +00001828 // Check GNU flexible array initializer.
1829 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1830 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001832
1833 if (Invalid) {
1834 ++Index;
1835 return true;
1836 }
1837
1838 // Initialize the array.
1839 bool prevHadError = hadError;
1840 unsigned newStructuredIndex = FieldIndex;
1841 unsigned OldIndex = Index;
1842 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001843
1844 InitializedEntity MemberEntity =
1845 InitializedEntity::InitializeMember(*Field, &Entity);
1846 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001847 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001848
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001849 IList->setInit(OldIndex, DIE);
1850 if (hadError && !prevHadError) {
1851 ++Field;
1852 ++FieldIndex;
1853 if (NextField)
1854 *NextField = Field;
1855 StructuredIndex = FieldIndex;
1856 return true;
1857 }
1858 } else {
1859 // Recurse to check later designated subobjects.
1860 QualType FieldType = (*Field)->getType();
1861 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001863 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001864 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1866 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001867 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001868 true, false))
1869 return true;
1870 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871
1872 // Find the position of the next field to be initialized in this
1873 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001875 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001876
1877 // If this the first designator, our caller will continue checking
1878 // the rest of this struct/class/union subobject.
1879 if (IsFirstDesignator) {
1880 if (NextField)
1881 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001882 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001883 return false;
1884 }
1885
Douglas Gregor17bd0942009-01-28 23:36:17 +00001886 if (!FinishSubobjectInit)
1887 return false;
1888
Douglas Gregord5846a12009-04-15 06:41:24 +00001889 // We've already initialized something in the union; we're done.
1890 if (RT->getDecl()->isUnion())
1891 return hadError;
1892
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001893 // Check the remaining fields within this class/struct/union subobject.
1894 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Anders Carlsson6cabf312010-01-23 23:23:01 +00001896 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001897 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001898 return hadError && !prevHadError;
1899 }
1900
1901 // C99 6.7.8p6:
1902 //
1903 // If a designator has the form
1904 //
1905 // [ constant-expression ]
1906 //
1907 // then the current object (defined below) shall have array
1908 // type and the expression shall be an integer constant
1909 // expression. If the array is of unknown size, any
1910 // nonnegative value is valid.
1911 //
1912 // Additionally, cope with the GNU extension that permits
1913 // designators of the form
1914 //
1915 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001916 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001917 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001918 if (!VerifyOnly)
1919 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1920 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001921 ++Index;
1922 return true;
1923 }
1924
1925 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001926 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1927 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001928 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001929 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001930 DesignatedEndIndex = DesignatedStartIndex;
1931 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001932 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001933
Mike Stump11289f42009-09-09 15:08:12 +00001934 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001935 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001936 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001937 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001938 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001939
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001940 // Codegen can't handle evaluating array range designators that have side
1941 // effects, because we replicate the AST value for each initialized element.
1942 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1943 // elements with something that has a side effect, so codegen can emit an
1944 // "error unsupported" error instead of miscompiling the app.
1945 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001946 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001947 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001948 }
1949
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001950 if (isa<ConstantArrayType>(AT)) {
1951 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001952 DesignatedStartIndex
1953 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001955 DesignatedEndIndex
1956 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001957 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1958 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001959 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001960 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1961 diag::err_array_designator_too_large)
1962 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1963 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001964 ++Index;
1965 return true;
1966 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001967 } else {
1968 // Make sure the bit-widths and signedness match.
1969 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001970 DesignatedEndIndex
1971 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001972 else if (DesignatedStartIndex.getBitWidth() <
1973 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001974 DesignatedStartIndex
1975 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001976 DesignatedStartIndex.setIsUnsigned(true);
1977 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001978 }
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001980 // Make sure that our non-designated initializer list has space
1981 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001982 if (!VerifyOnly &&
1983 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001984 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001985 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001986
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 // Repeatedly perform subobject initializations in the range
1988 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001989
Douglas Gregor17bd0942009-01-28 23:36:17 +00001990 // Move to the next designator
1991 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1992 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001994 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001995 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001996
Douglas Gregor17bd0942009-01-28 23:36:17 +00001997 while (DesignatedStartIndex <= DesignatedEndIndex) {
1998 // Recurse to check later designated subobjects.
1999 QualType ElementType = AT->getElementType();
2000 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002002 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2004 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002005 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002006 (DesignatedStartIndex == DesignatedEndIndex),
2007 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002008 return true;
2009
2010 // Move to the next index in the array that we'll be initializing.
2011 ++DesignatedStartIndex;
2012 ElementIndex = DesignatedStartIndex.getZExtValue();
2013 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002014
2015 // If this the first designator, our caller will continue checking
2016 // the rest of this array subobject.
2017 if (IsFirstDesignator) {
2018 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002019 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002021 return false;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregor17bd0942009-01-28 23:36:17 +00002024 if (!FinishSubobjectInit)
2025 return false;
2026
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002027 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002028 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002030 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002031 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002032 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002033}
2034
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002035// Get the structured initializer list for a subobject of type
2036// @p CurrentObjectType.
2037InitListExpr *
2038InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2039 QualType CurrentObjectType,
2040 InitListExpr *StructuredList,
2041 unsigned StructuredIndex,
2042 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002043 if (VerifyOnly)
2044 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002045 Expr *ExistingInit = 0;
2046 if (!StructuredList)
2047 ExistingInit = SyntacticToSemantic[IList];
2048 else if (StructuredIndex < StructuredList->getNumInits())
2049 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002051 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2052 return Result;
2053
2054 if (ExistingInit) {
2055 // We are creating an initializer list that initializes the
2056 // subobjects of the current object, but there was already an
2057 // initialization that completely initialized the current
2058 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002059 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060 // struct X { int a, b; };
2061 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002062 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002063 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2064 // designated initializer re-initializes the whole
2065 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002066 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002067 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002068 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002069 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002071 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002072 << ExistingInit->getSourceRange();
2073 }
2074
Mike Stump11289f42009-09-09 15:08:12 +00002075 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002076 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2077 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002078 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002079
Douglas Gregora8a089b2010-07-13 18:40:04 +00002080 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002081
Douglas Gregor6d00c992009-03-20 23:58:33 +00002082 // Pre-allocate storage for the structured initializer list.
2083 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002084 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002085 bool GotNumInits = false;
2086 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002087 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002088 GotNumInits = true;
2089 } else if (Index < IList->getNumInits()) {
2090 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002091 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002092 GotNumInits = true;
2093 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002094 }
2095
Mike Stump11289f42009-09-09 15:08:12 +00002096 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002097 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2098 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2099 NumElements = CAType->getSize().getZExtValue();
2100 // Simple heuristic so that we don't allocate a very large
2101 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002102 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002103 NumElements = 0;
2104 }
John McCall9dd450b2009-09-21 23:43:11 +00002105 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002106 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002108 RecordDecl *RDecl = RType->getDecl();
2109 if (RDecl->isUnion())
2110 NumElements = 1;
2111 else
Mike Stump11289f42009-09-09 15:08:12 +00002112 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002113 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002114 }
2115
Ted Kremenekac034612010-04-13 23:39:13 +00002116 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002117
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002118 // Link this new initializer list into the structured initializer
2119 // lists.
2120 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002121 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002122 else {
2123 Result->setSyntacticForm(IList);
2124 SyntacticToSemantic[IList] = Result;
2125 }
2126
2127 return Result;
2128}
2129
2130/// Update the initializer at index @p StructuredIndex within the
2131/// structured initializer list to the value @p expr.
2132void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2133 unsigned &StructuredIndex,
2134 Expr *expr) {
2135 // No structured initializer list to update
2136 if (!StructuredList)
2137 return;
2138
Ted Kremenekac034612010-04-13 23:39:13 +00002139 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2140 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002141 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002142 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 diag::warn_initializer_overrides)
2144 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002145 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002146 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002147 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002148 << PrevInit->getSourceRange();
2149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002151 ++StructuredIndex;
2152}
2153
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002154/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002155/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002156/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002157/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002158/// failure. Returns the index expression, possibly with an implicit cast
2159/// added, on success. If everything went okay, Value will receive the
2160/// value of the constant expression.
2161static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002162CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002163 SourceLocation Loc = Index->getSourceRange().getBegin();
2164
2165 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002166 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2167 if (Result.isInvalid())
2168 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002169
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002170 if (Value.isSigned() && Value.isNegative())
2171 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002172 << Value.toString(10) << Index->getSourceRange();
2173
Douglas Gregor51650d32009-01-23 21:04:18 +00002174 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002175 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002176}
2177
John McCalldadc5752010-08-24 06:29:42 +00002178ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002179 SourceLocation Loc,
2180 bool GNUSyntax,
2181 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002182 typedef DesignatedInitExpr::Designator ASTDesignator;
2183
2184 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002185 SmallVector<ASTDesignator, 32> Designators;
2186 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002187
2188 // Build designators and check array designator expressions.
2189 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2190 const Designator &D = Desig.getDesignator(Idx);
2191 switch (D.getKind()) {
2192 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002193 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002194 D.getFieldLoc()));
2195 break;
2196
2197 case Designator::ArrayDesignator: {
2198 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2199 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002200 if (!Index->isTypeDependent() && !Index->isValueDependent())
2201 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2202 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002203 Invalid = true;
2204 else {
2205 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002206 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002207 D.getRBracketLoc()));
2208 InitExpressions.push_back(Index);
2209 }
2210 break;
2211 }
2212
2213 case Designator::ArrayRangeDesignator: {
2214 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2215 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2216 llvm::APSInt StartValue;
2217 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002218 bool StartDependent = StartIndex->isTypeDependent() ||
2219 StartIndex->isValueDependent();
2220 bool EndDependent = EndIndex->isTypeDependent() ||
2221 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002222 if (!StartDependent)
2223 StartIndex =
2224 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2225 if (!EndDependent)
2226 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2227
2228 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002229 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002230 else {
2231 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002232 if (StartDependent || EndDependent) {
2233 // Nothing to compute.
2234 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002235 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002236 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002237 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002238
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002239 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002240 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002241 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002242 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2243 Invalid = true;
2244 } else {
2245 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002246 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002247 D.getEllipsisLoc(),
2248 D.getRBracketLoc()));
2249 InitExpressions.push_back(StartIndex);
2250 InitExpressions.push_back(EndIndex);
2251 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002252 }
2253 break;
2254 }
2255 }
2256 }
2257
2258 if (Invalid || Init.isInvalid())
2259 return ExprError();
2260
2261 // Clear out the expressions within the designation.
2262 Desig.ClearExprs(*this);
2263
2264 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002265 = DesignatedInitExpr::Create(Context,
2266 Designators.data(), Designators.size(),
2267 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002268 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269
Richard Smithe4345902011-12-29 21:57:33 +00002270 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002271 Diag(DIE->getLocStart(), diag::ext_designated_init)
2272 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002273
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002274 return Owned(DIE);
2275}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002277//===----------------------------------------------------------------------===//
2278// Initialization entity
2279//===----------------------------------------------------------------------===//
2280
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002282 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002284{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002285 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2286 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002287 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002288 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002289 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002290 Type = VT->getElementType();
2291 } else {
2292 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2293 assert(CT && "Unexpected type");
2294 Kind = EK_ComplexElement;
2295 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002296 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002297}
2298
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002300 CXXBaseSpecifier *Base,
2301 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002302{
2303 InitializedEntity Result;
2304 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002305 Result.Base = reinterpret_cast<uintptr_t>(Base);
2306 if (IsInheritedVirtualBase)
2307 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
Douglas Gregor1b303932009-12-22 15:35:07 +00002309 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310 return Result;
2311}
2312
Douglas Gregor85dabae2009-12-16 01:38:02 +00002313DeclarationName InitializedEntity::getName() const {
2314 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002315 case EK_Parameter: {
2316 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2317 return (D ? D->getDeclName() : DeclarationName());
2318 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002319
2320 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002321 case EK_Member:
2322 return VariableOrMember->getDeclName();
2323
Douglas Gregor19666fb2012-02-15 16:57:26 +00002324 case EK_LambdaCapture:
2325 return Capture.Var->getDeclName();
2326
Douglas Gregor85dabae2009-12-16 01:38:02 +00002327 case EK_Result:
2328 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002329 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002330 case EK_Temporary:
2331 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002332 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002333 case EK_ArrayElement:
2334 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002335 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002336 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337 return DeclarationName();
2338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002339
David Blaikie8a40f702012-01-17 06:56:22 +00002340 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002341}
2342
Douglas Gregora4b592a2009-12-19 03:01:41 +00002343DeclaratorDecl *InitializedEntity::getDecl() const {
2344 switch (getKind()) {
2345 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002346 case EK_Member:
2347 return VariableOrMember;
2348
John McCall31168b02011-06-15 23:02:42 +00002349 case EK_Parameter:
2350 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2351
Douglas Gregora4b592a2009-12-19 03:01:41 +00002352 case EK_Result:
2353 case EK_Exception:
2354 case EK_New:
2355 case EK_Temporary:
2356 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002357 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002358 case EK_ArrayElement:
2359 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002360 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002361 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002362 case EK_LambdaCapture:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002363 return 0;
2364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
David Blaikie8a40f702012-01-17 06:56:22 +00002366 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002367}
2368
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002369bool InitializedEntity::allowsNRVO() const {
2370 switch (getKind()) {
2371 case EK_Result:
2372 case EK_Exception:
2373 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002375 case EK_Variable:
2376 case EK_Parameter:
2377 case EK_Member:
2378 case EK_New:
2379 case EK_Temporary:
2380 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002381 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002382 case EK_ArrayElement:
2383 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002384 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002385 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002386 case EK_LambdaCapture:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002387 break;
2388 }
2389
2390 return false;
2391}
2392
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002393//===----------------------------------------------------------------------===//
2394// Initialization sequence
2395//===----------------------------------------------------------------------===//
2396
2397void InitializationSequence::Step::Destroy() {
2398 switch (Kind) {
2399 case SK_ResolveAddressOfOverloadedFunction:
2400 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002401 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 case SK_CastDerivedToBaseLValue:
2403 case SK_BindReference:
2404 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002405 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 case SK_UserConversion:
2407 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002408 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002409 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002410 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002411 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002412 case SK_UnwrapInitList:
2413 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002414 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002415 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002416 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002417 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002418 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002419 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002420 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002421 case SK_PassByIndirectCopyRestore:
2422 case SK_PassByIndirectRestore:
2423 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002424 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002427 case SK_ConversionSequence:
2428 delete ICS;
2429 }
2430}
2431
Douglas Gregor838fcc32010-03-26 20:14:36 +00002432bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002433 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002434}
2435
2436bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002437 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002438 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002439
Douglas Gregor838fcc32010-03-26 20:14:36 +00002440 switch (getFailureKind()) {
2441 case FK_TooManyInitsForReference:
2442 case FK_ArrayNeedsInitList:
2443 case FK_ArrayNeedsInitListOrStringLiteral:
2444 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2445 case FK_NonConstLValueReferenceBindingToTemporary:
2446 case FK_NonConstLValueReferenceBindingToUnrelated:
2447 case FK_RValueReferenceBindingToLValue:
2448 case FK_ReferenceInitDropsQualifiers:
2449 case FK_ReferenceInitFailed:
2450 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002451 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002452 case FK_TooManyInitsForScalar:
2453 case FK_ReferenceBindingToInitList:
2454 case FK_InitListBadDestinationType:
2455 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002456 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002457 case FK_ArrayTypeMismatch:
2458 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002459 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002460 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002461 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002462 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002463 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
Douglas Gregor838fcc32010-03-26 20:14:36 +00002465 case FK_ReferenceInitOverloadFailed:
2466 case FK_UserConversionOverloadFailed:
2467 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002468 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002469 return FailedOverloadResult == OR_Ambiguous;
2470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471
David Blaikie8a40f702012-01-17 06:56:22 +00002472 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002473}
2474
Douglas Gregorb33eed02010-04-16 22:09:46 +00002475bool InitializationSequence::isConstructorInitialization() const {
2476 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2477}
2478
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002479void
2480InitializationSequence
2481::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2482 DeclAccessPair Found,
2483 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002484 Step S;
2485 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2486 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002487 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002488 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002489 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002490 Steps.push_back(S);
2491}
2492
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002493void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002494 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002495 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002496 switch (VK) {
2497 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2498 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2499 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002500 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002501 S.Type = BaseType;
2502 Steps.push_back(S);
2503}
2504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002506 bool BindingTemporary) {
2507 Step S;
2508 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002513void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2514 Step S;
2515 S.Kind = SK_ExtraneousCopyToTemporary;
2516 S.Type = T;
2517 Steps.push_back(S);
2518}
2519
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002520void
2521InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2522 DeclAccessPair FoundDecl,
2523 QualType T,
2524 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 Step S;
2526 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002527 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002528 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002529 S.Function.Function = Function;
2530 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 Steps.push_back(S);
2532}
2533
2534void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002535 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002536 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002537 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002538 switch (VK) {
2539 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002540 S.Kind = SK_QualificationConversionRValue;
2541 break;
John McCall2536c6d2010-08-25 10:28:54 +00002542 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002543 S.Kind = SK_QualificationConversionXValue;
2544 break;
John McCall2536c6d2010-08-25 10:28:54 +00002545 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002546 S.Kind = SK_QualificationConversionLValue;
2547 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002548 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002549 S.Type = Ty;
2550 Steps.push_back(S);
2551}
2552
2553void InitializationSequence::AddConversionSequenceStep(
2554 const ImplicitConversionSequence &ICS,
2555 QualType T) {
2556 Step S;
2557 S.Kind = SK_ConversionSequence;
2558 S.Type = T;
2559 S.ICS = new ImplicitConversionSequence(ICS);
2560 Steps.push_back(S);
2561}
2562
Douglas Gregor51e77d52009-12-10 17:56:55 +00002563void InitializationSequence::AddListInitializationStep(QualType T) {
2564 Step S;
2565 S.Kind = SK_ListInitialization;
2566 S.Type = T;
2567 Steps.push_back(S);
2568}
2569
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002571InitializationSequence
2572::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2573 AccessSpecifier Access,
2574 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002575 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002576 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002577 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002578 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2579 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002580 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002581 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002582 S.Function.Function = Constructor;
2583 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002584 Steps.push_back(S);
2585}
2586
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002587void InitializationSequence::AddZeroInitializationStep(QualType T) {
2588 Step S;
2589 S.Kind = SK_ZeroInitialization;
2590 S.Type = T;
2591 Steps.push_back(S);
2592}
2593
Douglas Gregore1314a62009-12-18 05:02:21 +00002594void InitializationSequence::AddCAssignmentStep(QualType T) {
2595 Step S;
2596 S.Kind = SK_CAssignment;
2597 S.Type = T;
2598 Steps.push_back(S);
2599}
2600
Eli Friedman78275202009-12-19 08:11:05 +00002601void InitializationSequence::AddStringInitStep(QualType T) {
2602 Step S;
2603 S.Kind = SK_StringInit;
2604 S.Type = T;
2605 Steps.push_back(S);
2606}
2607
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002608void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2609 Step S;
2610 S.Kind = SK_ObjCObjectConversion;
2611 S.Type = T;
2612 Steps.push_back(S);
2613}
2614
Douglas Gregore2f943b2011-02-22 18:29:51 +00002615void InitializationSequence::AddArrayInitStep(QualType T) {
2616 Step S;
2617 S.Kind = SK_ArrayInit;
2618 S.Type = T;
2619 Steps.push_back(S);
2620}
2621
Richard Smithebeed412012-02-15 22:38:09 +00002622void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2623 Step S;
2624 S.Kind = SK_ParenthesizedArrayInit;
2625 S.Type = T;
2626 Steps.push_back(S);
2627}
2628
John McCall31168b02011-06-15 23:02:42 +00002629void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2630 bool shouldCopy) {
2631 Step s;
2632 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2633 : SK_PassByIndirectRestore);
2634 s.Type = type;
2635 Steps.push_back(s);
2636}
2637
2638void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2639 Step S;
2640 S.Kind = SK_ProduceObjCObject;
2641 S.Type = T;
2642 Steps.push_back(S);
2643}
2644
Sebastian Redlc1839b12012-01-17 22:49:42 +00002645void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2646 Step S;
2647 S.Kind = SK_StdInitializerList;
2648 S.Type = T;
2649 Steps.push_back(S);
2650}
2651
Sebastian Redl29526f02011-11-27 16:50:07 +00002652void InitializationSequence::RewrapReferenceInitList(QualType T,
2653 InitListExpr *Syntactic) {
2654 assert(Syntactic->getNumInits() == 1 &&
2655 "Can only rewrap trivial init lists.");
2656 Step S;
2657 S.Kind = SK_UnwrapInitList;
2658 S.Type = Syntactic->getInit(0)->getType();
2659 Steps.insert(Steps.begin(), S);
2660
2661 S.Kind = SK_RewrapInitList;
2662 S.Type = T;
2663 S.WrappingSyntacticList = Syntactic;
2664 Steps.push_back(S);
2665}
2666
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002668 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002669 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 this->Failure = Failure;
2671 this->FailedOverloadResult = Result;
2672}
2673
2674//===----------------------------------------------------------------------===//
2675// Attempt initialization
2676//===----------------------------------------------------------------------===//
2677
John McCall31168b02011-06-15 23:02:42 +00002678static void MaybeProduceObjCObject(Sema &S,
2679 InitializationSequence &Sequence,
2680 const InitializedEntity &Entity) {
2681 if (!S.getLangOptions().ObjCAutoRefCount) return;
2682
2683 /// When initializing a parameter, produce the value if it's marked
2684 /// __attribute__((ns_consumed)).
2685 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2686 if (!Entity.isParameterConsumed())
2687 return;
2688
2689 assert(Entity.getType()->isObjCRetainableType() &&
2690 "consuming an object of unretainable type?");
2691 Sequence.AddProduceObjCObjectStep(Entity.getType());
2692
2693 /// When initializing a return value, if the return type is a
2694 /// retainable type, then returns need to immediately retain the
2695 /// object. If an autorelease is required, it will be done at the
2696 /// last instant.
2697 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2698 if (!Entity.getType()->isObjCRetainableType())
2699 return;
2700
2701 Sequence.AddProduceObjCObjectStep(Entity.getType());
2702 }
2703}
2704
Sebastian Redled2e5322011-12-22 14:44:04 +00002705/// \brief When initializing from init list via constructor, deal with the
2706/// empty init list and std::initializer_list special cases.
2707///
2708/// \return True if this was a special case, false otherwise.
2709static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002710 InitListExpr *List,
Sebastian Redled2e5322011-12-22 14:44:04 +00002711 CXXRecordDecl *DestRecordDecl,
2712 QualType DestType,
2713 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002714 // C++11 [dcl.init.list]p3:
Richard Smith1bfe0682012-02-14 21:14:13 +00002715 // List-initialization of an object or reference of type T is defined as
2716 // follows:
2717 // - If T is an aggregate, aggregate initialization is performed.
2718 if (DestType->isAggregateType())
2719 return false;
2720
2721 // - Otherwise, if the initializer list has no elements and T is a class
2722 // type with a default constructor, the object is value-initialized.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002723 if (List->getNumInits() == 0) {
Sebastian Redled2e5322011-12-22 14:44:04 +00002724 if (CXXConstructorDecl *DefaultConstructor =
2725 S.LookupDefaultConstructor(DestRecordDecl)) {
2726 if (DefaultConstructor->isDeleted() ||
2727 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2728 // Fake an overload resolution failure.
2729 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2730 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2731 DefaultConstructor->getAccess());
2732 if (FunctionTemplateDecl *ConstructorTmpl =
2733 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2734 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2735 /*ExplicitArgs*/ 0,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002736 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002737 /*SuppressUserConversions*/ false);
2738 else
2739 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002740 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002741 /*SuppressUserConversions*/ false);
2742 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002743 InitializationSequence::FK_ListConstructorOverloadFailed,
2744 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002745 } else
2746 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2747 DefaultConstructor->getAccess(),
2748 DestType,
2749 /*MultipleCandidates=*/false,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002750 /*FromInitList=*/true,
2751 /*AsInitList=*/false);
Sebastian Redled2e5322011-12-22 14:44:04 +00002752 return true;
2753 }
2754 }
2755
2756 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002757 QualType E;
2758 if (S.isStdInitializerList(DestType, &E)) {
2759 // Check that each individual element can be copy-constructed. But since we
2760 // have no place to store further information, we'll recalculate everything
2761 // later.
2762 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2763 S.Context.getConstantArrayType(E,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002764 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2765 List->getNumInits()),
Sebastian Redlc1839b12012-01-17 22:49:42 +00002766 ArrayType::Normal, 0));
2767 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2768 0, HiddenArray);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002769 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002770 Element.setElementIndex(i);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002771 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002772 Sequence.SetFailed(
2773 InitializationSequence::FK_InitListElementCopyFailure);
2774 return true;
2775 }
2776 }
2777 Sequence.AddStdInitializerListConstructionStep(DestType);
2778 return true;
2779 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002780
2781 // Not a special case.
2782 return false;
2783}
2784
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002785static OverloadingResult
2786ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2787 Expr **Args, unsigned NumArgs,
2788 OverloadCandidateSet &CandidateSet,
2789 DeclContext::lookup_iterator Con,
2790 DeclContext::lookup_iterator ConEnd,
2791 OverloadCandidateSet::iterator &Best,
2792 bool CopyInitializing, bool AllowExplicit,
2793 bool OnlyListConstructors) {
2794 CandidateSet.clear();
2795
2796 for (; Con != ConEnd; ++Con) {
2797 NamedDecl *D = *Con;
2798 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2799 bool SuppressUserConversions = false;
2800
2801 // Find the constructor (which may be a template).
2802 CXXConstructorDecl *Constructor = 0;
2803 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2804 if (ConstructorTmpl)
2805 Constructor = cast<CXXConstructorDecl>(
2806 ConstructorTmpl->getTemplatedDecl());
2807 else {
2808 Constructor = cast<CXXConstructorDecl>(D);
2809
2810 // If we're performing copy initialization using a copy constructor, we
2811 // suppress user-defined conversions on the arguments.
2812 // FIXME: Move constructors?
2813 if (CopyInitializing && Constructor->isCopyConstructor())
2814 SuppressUserConversions = true;
2815 }
2816
2817 if (!Constructor->isInvalidDecl() &&
2818 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002819 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002820 if (ConstructorTmpl)
2821 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2822 /*ExplicitArgs*/ 0,
2823 Args, NumArgs, CandidateSet,
2824 SuppressUserConversions);
2825 else
2826 S.AddOverloadCandidate(Constructor, FoundDecl,
2827 Args, NumArgs, CandidateSet,
2828 SuppressUserConversions);
2829 }
2830 }
2831
2832 // Perform overload resolution and return the result.
2833 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2834}
2835
Sebastian Redled2e5322011-12-22 14:44:04 +00002836/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2837/// enumerates the constructors of the initialized entity and performs overload
2838/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002839/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002840/// class type.
2841static void TryConstructorInitialization(Sema &S,
2842 const InitializedEntity &Entity,
2843 const InitializationKind &Kind,
2844 Expr **Args, unsigned NumArgs,
2845 QualType DestType,
2846 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002847 bool InitListSyntax = false) {
2848 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2849 "InitListSyntax must come with a single initializer list argument.");
2850
Sebastian Redled2e5322011-12-22 14:44:04 +00002851 // Check constructor arguments for self reference.
2852 if (DeclaratorDecl *DD = Entity.getDecl())
2853 // Parameters arguments are occassionially constructed with itself,
2854 // for instance, in recursive functions. Skip them.
2855 if (!isa<ParmVarDecl>(DD))
2856 for (unsigned i = 0; i < NumArgs; ++i)
2857 S.CheckSelfReference(DD, Args[i]);
2858
Sebastian Redled2e5322011-12-22 14:44:04 +00002859 // The type we're constructing needs to be complete.
2860 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2861 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002862 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00002863 }
2864
2865 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2866 assert(DestRecordType && "Constructor initialization requires record type");
2867 CXXRecordDecl *DestRecordDecl
2868 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2869
Sebastian Redl88e4d492012-02-04 21:27:33 +00002870 if (InitListSyntax &&
2871 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2872 DestRecordDecl, DestType, Sequence))
Sebastian Redled2e5322011-12-22 14:44:04 +00002873 return;
2874
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002875 // Build the candidate set directly in the initialization sequence
2876 // structure, so that it will persist if we fail.
2877 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2878
2879 // Determine whether we are allowed to call explicit constructors or
2880 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00002881 bool AllowExplicit = Kind.AllowExplicit();
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002882 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00002883
Sebastian Redled2e5322011-12-22 14:44:04 +00002884 // - Otherwise, if T is a class type, constructors are considered. The
2885 // applicable constructors are enumerated, and the best one is chosen
2886 // through overload resolution.
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002887 DeclContext::lookup_iterator ConStart, ConEnd;
2888 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00002889
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002890 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00002891 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002892 bool AsInitializerList = false;
2893
2894 // C++11 [over.match.list]p1:
2895 // When objects of non-aggregate type T are list-initialized, overload
2896 // resolution selects the constructor in two phases:
2897 // - Initially, the candidate functions are the initializer-list
2898 // constructors of the class T and the argument list consists of the
2899 // initializer list as a single argument.
2900 if (InitListSyntax) {
2901 AsInitializerList = true;
2902 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2903 CandidateSet, ConStart, ConEnd, Best,
2904 CopyInitialization, AllowExplicit,
2905 /*OnlyListConstructor=*/true);
2906
2907 // Time to unwrap the init list.
2908 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2909 Args = ILE->getInits();
2910 NumArgs = ILE->getNumInits();
2911 }
2912
2913 // C++11 [over.match.list]p1:
2914 // - If no viable initializer-list constructor is found, overload resolution
2915 // is performed again, where the candidate functions are all the
2916 // constructors of the class T nad the argument list consists of the
2917 // elements of the initializer list.
2918 if (Result == OR_No_Viable_Function) {
2919 AsInitializerList = false;
2920 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2921 CandidateSet, ConStart, ConEnd, Best,
2922 CopyInitialization, AllowExplicit,
2923 /*OnlyListConstructors=*/false);
2924 }
2925 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002926 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002927 InitializationSequence::FK_ListConstructorOverloadFailed :
2928 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002929 Result);
2930 return;
2931 }
2932
2933 // C++0x [dcl.init]p6:
2934 // If a program calls for the default initialization of an object
2935 // of a const-qualified type T, T shall be a class type with a
2936 // user-provided default constructor.
2937 if (Kind.getKind() == InitializationKind::IK_Default &&
2938 Entity.getType().isConstQualified() &&
2939 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2940 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2941 return;
2942 }
2943
2944 // Add the constructor initialization step. Any cv-qualification conversion is
2945 // subsumed by the initialization.
2946 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2947 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2948 Sequence.AddConstructorInitializationStep(CtorDecl,
2949 Best->FoundDecl.getAccess(),
2950 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002951 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00002952}
2953
Sebastian Redl29526f02011-11-27 16:50:07 +00002954static bool
2955ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2956 Expr *Initializer,
2957 QualType &SourceType,
2958 QualType &UnqualifiedSourceType,
2959 QualType UnqualifiedTargetType,
2960 InitializationSequence &Sequence) {
2961 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2962 S.Context.OverloadTy) {
2963 DeclAccessPair Found;
2964 bool HadMultipleCandidates = false;
2965 if (FunctionDecl *Fn
2966 = S.ResolveAddressOfOverloadedFunction(Initializer,
2967 UnqualifiedTargetType,
2968 false, Found,
2969 &HadMultipleCandidates)) {
2970 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2971 HadMultipleCandidates);
2972 SourceType = Fn->getType();
2973 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2974 } else if (!UnqualifiedTargetType->isRecordType()) {
2975 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2976 return true;
2977 }
2978 }
2979 return false;
2980}
2981
2982static void TryReferenceInitializationCore(Sema &S,
2983 const InitializedEntity &Entity,
2984 const InitializationKind &Kind,
2985 Expr *Initializer,
2986 QualType cv1T1, QualType T1,
2987 Qualifiers T1Quals,
2988 QualType cv2T2, QualType T2,
2989 Qualifiers T2Quals,
2990 InitializationSequence &Sequence);
2991
2992static void TryListInitialization(Sema &S,
2993 const InitializedEntity &Entity,
2994 const InitializationKind &Kind,
2995 InitListExpr *InitList,
2996 InitializationSequence &Sequence);
2997
2998/// \brief Attempt list initialization of a reference.
2999static void TryReferenceListInitialization(Sema &S,
3000 const InitializedEntity &Entity,
3001 const InitializationKind &Kind,
3002 InitListExpr *InitList,
3003 InitializationSequence &Sequence)
3004{
3005 // First, catch C++03 where this isn't possible.
3006 if (!S.getLangOptions().CPlusPlus0x) {
3007 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3008 return;
3009 }
3010
3011 QualType DestType = Entity.getType();
3012 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3013 Qualifiers T1Quals;
3014 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3015
3016 // Reference initialization via an initializer list works thus:
3017 // If the initializer list consists of a single element that is
3018 // reference-related to the referenced type, bind directly to that element
3019 // (possibly creating temporaries).
3020 // Otherwise, initialize a temporary with the initializer list and
3021 // bind to that.
3022 if (InitList->getNumInits() == 1) {
3023 Expr *Initializer = InitList->getInit(0);
3024 QualType cv2T2 = Initializer->getType();
3025 Qualifiers T2Quals;
3026 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3027
3028 // If this fails, creating a temporary wouldn't work either.
3029 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3030 T1, Sequence))
3031 return;
3032
3033 SourceLocation DeclLoc = Initializer->getLocStart();
3034 bool dummy1, dummy2, dummy3;
3035 Sema::ReferenceCompareResult RefRelationship
3036 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3037 dummy2, dummy3);
3038 if (RefRelationship >= Sema::Ref_Related) {
3039 // Try to bind the reference here.
3040 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3041 T1Quals, cv2T2, T2, T2Quals, Sequence);
3042 if (Sequence)
3043 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3044 return;
3045 }
3046 }
3047
3048 // Not reference-related. Create a temporary and bind to that.
3049 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3050
3051 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3052 if (Sequence) {
3053 if (DestType->isRValueReferenceType() ||
3054 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3055 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3056 else
3057 Sequence.SetFailed(
3058 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3059 }
3060}
3061
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003062/// \brief Attempt list initialization (C++0x [dcl.init.list])
3063static void TryListInitialization(Sema &S,
3064 const InitializedEntity &Entity,
3065 const InitializationKind &Kind,
3066 InitListExpr *InitList,
3067 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003068 QualType DestType = Entity.getType();
3069
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003070 // C++ doesn't allow scalar initialization with more than one argument.
3071 // But C99 complex numbers are scalars and it makes sense there.
3072 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3073 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3074 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3075 return;
3076 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003077 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003078 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003079 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003080 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003081 if (DestType->isRecordType()) {
3082 if (S.RequireCompleteType(InitList->getLocStart(), DestType, S.PDiag())) {
3083 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
3084 return;
3085 }
3086
3087 if (!DestType->isAggregateType()) {
3088 if (S.getLangOptions().CPlusPlus0x) {
3089 Expr *Arg = InitList;
3090 // A direct-initializer is not list-syntax, i.e. there's no special
3091 // treatment of "A a({1, 2});".
3092 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3093 Sequence,
3094 Kind.getKind() != InitializationKind::IK_Direct);
3095 } else
3096 Sequence.SetFailed(
3097 InitializationSequence::FK_InitListBadDestinationType);
3098 return;
3099 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003100 }
3101
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003102 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003103 DestType, /*VerifyOnly=*/true,
Sebastian Redl5a41f682012-02-12 16:37:24 +00003104 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003105 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003106 if (CheckInitList.HadError()) {
3107 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3108 return;
3109 }
3110
3111 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003112 Sequence.AddListInitializationStep(DestType);
3113}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003114
3115/// \brief Try a reference initialization that involves calling a conversion
3116/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003117static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3118 const InitializedEntity &Entity,
3119 const InitializationKind &Kind,
3120 Expr *Initializer,
3121 bool AllowRValues,
3122 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003123 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3125 QualType T1 = cv1T1.getUnqualifiedType();
3126 QualType cv2T2 = Initializer->getType();
3127 QualType T2 = cv2T2.getUnqualifiedType();
3128
3129 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003130 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003131 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003133 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003134 ObjCConversion,
3135 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003136 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003137 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003138 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003139 (void)ObjCLifetimeConversion;
3140
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003141 // Build the candidate set directly in the initialization sequence
3142 // structure, so that it will persist if we fail.
3143 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3144 CandidateSet.clear();
3145
3146 // Determine whether we are allowed to call explicit constructors or
3147 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003148 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003150 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003151 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3152 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153 // The type we're converting to is a class type. Enumerate its constructors
3154 // to see if there is a suitable conversion.
3155 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003156
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003158 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003160 NamedDecl *D = *Con;
3161 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3162
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003163 // Find the constructor (which may be a template).
3164 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003165 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 if (ConstructorTmpl)
3167 Constructor = cast<CXXConstructorDecl>(
3168 ConstructorTmpl->getTemplatedDecl());
3169 else
John McCalla0296f72010-03-19 07:35:19 +00003170 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 if (!Constructor->isInvalidDecl() &&
3173 Constructor->isConvertingConstructor(AllowExplicit)) {
3174 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003175 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003176 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003177 &Initializer, 1, CandidateSet,
3178 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 else
John McCalla0296f72010-03-19 07:35:19 +00003180 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003181 &Initializer, 1, CandidateSet,
3182 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003185 }
John McCall3696dcb2010-08-17 07:23:57 +00003186 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3187 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
Douglas Gregor496e8b342010-05-07 19:42:26 +00003189 const RecordType *T2RecordType = 0;
3190 if ((T2RecordType = T2->getAs<RecordType>()) &&
3191 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 // The type we're converting from is a class type, enumerate its conversion
3193 // functions.
3194 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3195
John McCallad371252010-01-20 00:46:10 +00003196 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003198 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3199 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 NamedDecl *D = *I;
3201 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3202 if (isa<UsingShadowDecl>(D))
3203 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003205 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3206 CXXConversionDecl *Conv;
3207 if (ConvTemplate)
3208 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3209 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003210 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003211
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003212 // If the conversion function doesn't return a reference type,
3213 // it can't be considered for this conversion unless we're allowed to
3214 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215 // FIXME: Do we need to make sure that we only consider conversion
3216 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003217 // break recursion.
3218 if ((AllowExplicit || !Conv->isExplicit()) &&
3219 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3220 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003221 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003222 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003223 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 else
John McCalla0296f72010-03-19 07:35:19 +00003225 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003226 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003227 }
3228 }
3229 }
John McCall3696dcb2010-08-17 07:23:57 +00003230 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3231 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 SourceLocation DeclLoc = Initializer->getLocStart();
3234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003236 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003238 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003239 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003240
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003241 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003242
Chandler Carruth30141632011-02-25 19:41:05 +00003243 // This is the overload that will actually be used for the initialization, so
3244 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003245 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003246
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003247 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003248 if (isa<CXXConversionDecl>(Function))
3249 T2 = Function->getResultType();
3250 else
3251 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003252
3253 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003254 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003255 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003256 T2.getNonLValueExprType(S.Context),
3257 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003258
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003260 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003261 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003262 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003263 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003264 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003265 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003268 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003269 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003272 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003273 NewDerivedToBase, NewObjCConversion,
3274 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003275 if (NewRefRelationship == Sema::Ref_Incompatible) {
3276 // If the type we've converted to is not reference-related to the
3277 // type we're looking for, then there is another conversion step
3278 // we need to perform to produce a temporary of the right type
3279 // that we'll be binding to.
3280 ImplicitConversionSequence ICS;
3281 ICS.setStandard();
3282 ICS.Standard = Best->FinalConversion;
3283 T2 = ICS.Standard.getToType(2);
3284 Sequence.AddConversionSequenceStep(ICS, T2);
3285 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003286 Sequence.AddDerivedToBaseCastStep(
3287 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003289 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003290 else if (NewObjCConversion)
3291 Sequence.AddObjCObjectConversionStep(
3292 S.Context.getQualifiedType(T1,
3293 T2.getNonReferenceType().getQualifiers()));
3294
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003295 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003296 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003298 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3299 return OR_Success;
3300}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301
Richard Smithc620f552011-10-19 16:55:56 +00003302static void CheckCXX98CompatAccessibleCopy(Sema &S,
3303 const InitializedEntity &Entity,
3304 Expr *CurInitExpr);
3305
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3307static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003308 const InitializedEntity &Entity,
3309 const InitializationKind &Kind,
3310 Expr *Initializer,
3311 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003312 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003313 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003314 Qualifiers T1Quals;
3315 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003316 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003317 Qualifiers T2Quals;
3318 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003319
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003320 // If the initializer is the address of an overloaded function, try
3321 // to resolve the overloaded function. If all goes well, T2 is the
3322 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003323 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3324 T1, Sequence))
3325 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003326
Sebastian Redl29526f02011-11-27 16:50:07 +00003327 // Delegate everything else to a subfunction.
3328 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3329 T1Quals, cv2T2, T2, T2Quals, Sequence);
3330}
3331
3332/// \brief Reference initialization without resolving overloaded functions.
3333static void TryReferenceInitializationCore(Sema &S,
3334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 Expr *Initializer,
3337 QualType cv1T1, QualType T1,
3338 Qualifiers T1Quals,
3339 QualType cv2T2, QualType T2,
3340 Qualifiers T2Quals,
3341 InitializationSequence &Sequence) {
3342 QualType DestType = Entity.getType();
3343 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003344 // Compute some basic properties of the types and the initializer.
3345 bool isLValueRef = DestType->isLValueReferenceType();
3346 bool isRValueRef = !isLValueRef;
3347 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003348 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003349 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003350 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003351 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003352 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003353 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003354
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003357 // "cv2 T2" as follows:
3358 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003360 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003361 // Note the analogous bullet points for rvlaue refs to functions. Because
3362 // there are no function rvalues in C++, rvalue refs to functions are treated
3363 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003364 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003365 bool T1Function = T1->isFunctionType();
3366 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003368 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003370 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003372 // reference-compatible with "cv2 T2," or
3373 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003375 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003376 // can occur. However, we do pay attention to whether it is a bit-field
3377 // to decide whether we're actually binding to a temporary created from
3378 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003379 if (DerivedToBase)
3380 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003382 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003383 else if (ObjCConversion)
3384 Sequence.AddObjCObjectConversionStep(
3385 S.Context.getQualifiedType(T1, T2Quals));
3386
Chandler Carruth04bdce62010-01-12 20:32:25 +00003387 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003388 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003389 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003390 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003391 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003392 return;
3393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
3395 // - has a class type (i.e., T2 is a class type), where T1 is not
3396 // reference-related to T2, and can be implicitly converted to an
3397 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3398 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003399 // applicable conversion functions (13.3.1.6) and choosing the best
3400 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003401 // If we have an rvalue ref to function type here, the rhs must be
3402 // an rvalue.
3403 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3404 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003406 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003407 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003408 Sequence);
3409 if (ConvOvlResult == OR_Success)
3410 return;
John McCall0d1da222010-01-12 00:44:57 +00003411 if (ConvOvlResult != OR_No_Viable_Function) {
3412 Sequence.SetOverloadFailure(
3413 InitializationSequence::FK_ReferenceInitOverloadFailed,
3414 ConvOvlResult);
3415 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 }
3417 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003418
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003420 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003421 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003422 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003423 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3424 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3425 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003426 Sequence.SetOverloadFailure(
3427 InitializationSequence::FK_ReferenceInitOverloadFailed,
3428 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003429 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003430 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003431 ? (RefRelationship == Sema::Ref_Related
3432 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3433 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3434 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003435
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003436 return;
3437 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003438
Douglas Gregor92e460e2011-01-20 16:44:54 +00003439 // - If the initializer expression
3440 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3441 // "cv1 T1" is reference-compatible with "cv2 T2"
3442 // Note: functions are handled below.
3443 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003444 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003446 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003447 (InitCategory.isXValue() ||
3448 (InitCategory.isPRValue() && T2->isRecordType()) ||
3449 (InitCategory.isPRValue() && T2->isArrayType()))) {
3450 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3451 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003452 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3453 // compiler the freedom to perform a copy here or bind to the
3454 // object, while C++0x requires that we bind directly to the
3455 // object. Hence, we always bind to the object without making an
3456 // extra copy. However, in C++03 requires that we check for the
3457 // presence of a suitable copy constructor:
3458 //
3459 // The constructor that would be used to make the copy shall
3460 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003461 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003462 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003463 else if (S.getLangOptions().CPlusPlus0x)
3464 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregor92e460e2011-01-20 16:44:54 +00003467 if (DerivedToBase)
3468 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3469 ValueKind);
3470 else if (ObjCConversion)
3471 Sequence.AddObjCObjectConversionStep(
3472 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Douglas Gregor92e460e2011-01-20 16:44:54 +00003474 if (T1Quals != T2Quals)
3475 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003477 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
3481 // - has a class type (i.e., T2 is a class type), where T1 is not
3482 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003483 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3484 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003485 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003486 if (RefRelationship == Sema::Ref_Incompatible) {
3487 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3488 Kind, Initializer,
3489 /*AllowRValues=*/true,
3490 Sequence);
3491 if (ConvOvlResult)
3492 Sequence.SetOverloadFailure(
3493 InitializationSequence::FK_ReferenceInitOverloadFailed,
3494 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003496 return;
3497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003499 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3500 return;
3501 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003502
3503 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003504 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003507
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003508 // Determine whether we are allowed to call explicit constructors or
3509 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003510 bool AllowExplicit = Kind.AllowExplicit();
John McCallec6f4e92010-06-04 02:29:22 +00003511
3512 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3513
John McCall31168b02011-06-15 23:02:42 +00003514 ImplicitConversionSequence ICS
3515 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003516 /*SuppressUserConversions*/ false,
3517 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003518 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003519 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3520 /*AllowObjCWritebackConversion=*/false);
3521
3522 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003523 // FIXME: Use the conversion function set stored in ICS to turn
3524 // this into an overloading ambiguity diagnostic. However, we need
3525 // to keep that set as an OverloadCandidateSet rather than as some
3526 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003527 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3528 Sequence.SetOverloadFailure(
3529 InitializationSequence::FK_ReferenceInitOverloadFailed,
3530 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003531 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3532 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003533 else
3534 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003535 return;
John McCall31168b02011-06-15 23:02:42 +00003536 } else {
3537 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538 }
3539
3540 // [...] If T1 is reference-related to T2, cv1 must be the
3541 // same cv-qualification as, or greater cv-qualification
3542 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003543 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3544 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003546 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3548 return;
3549 }
3550
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003552 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003554 InitCategory.isLValue()) {
3555 Sequence.SetFailed(
3556 InitializationSequence::FK_RValueReferenceBindingToLValue);
3557 return;
3558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3561 return;
3562}
3563
3564/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565/// (C++ [dcl.init.string], C99 6.7.8).
3566static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003567 const InitializedEntity &Entity,
3568 const InitializationKind &Kind,
3569 Expr *Initializer,
3570 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003571 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003572}
3573
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003574/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003576 const InitializedEntity &Entity,
3577 const InitializationKind &Kind,
3578 InitializationSequence &Sequence) {
Richard Smith1bfe0682012-02-14 21:14:13 +00003579 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003580 //
3581 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003582 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003584 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003585 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003587 if (const RecordType *RT = T->getAs<RecordType>()) {
3588 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smith1bfe0682012-02-14 21:14:13 +00003589 // C++98:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003590 // -- if T is a class type (clause 9) with a user-declared
3591 // constructor (12.1), then the default constructor for T is
3592 // called (and the initialization is ill-formed if T has no
3593 // accessible default constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003594 if (!S.getLangOptions().CPlusPlus0x) {
3595 if (ClassDecl->hasUserDeclaredConstructor())
3596 // FIXME: we really want to refer to a single subobject of the array,
3597 // but Entity doesn't have a way to capture that (yet).
3598 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3599 T, Sequence);
3600 } else {
3601 // C++11:
3602 // -- if T is a class type (clause 9) with either no default constructor
3603 // (12.1 [class.ctor]) or a default constructor that is user-provided
3604 // or deleted, then the object is default-initialized;
3605 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3606 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3607 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3608 T, Sequence);
3609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610
Richard Smith1bfe0682012-02-14 21:14:13 +00003611 // -- if T is a (possibly cv-qualified) non-union class type without a
3612 // user-provided or deleted default constructor, then the object is
3613 // zero-initialized and, if T has a non-trivial default constructor,
3614 // default-initialized;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003615 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003616 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003617 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003619 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003620 }
3621 }
3622
Douglas Gregor1b303932009-12-22 15:35:07 +00003623 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003624}
3625
Douglas Gregor85dabae2009-12-16 01:38:02 +00003626/// \brief Attempt default initialization (C++ [dcl.init]p6).
3627static void TryDefaultInitialization(Sema &S,
3628 const InitializedEntity &Entity,
3629 const InitializationKind &Kind,
3630 InitializationSequence &Sequence) {
3631 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
Douglas Gregor85dabae2009-12-16 01:38:02 +00003633 // C++ [dcl.init]p6:
3634 // To default-initialize an object of type T means:
3635 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003636 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3637
Douglas Gregor85dabae2009-12-16 01:38:02 +00003638 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3639 // constructor for T is called (and the initialization is ill-formed if
3640 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003641 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003642 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3643 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor85dabae2009-12-16 01:38:02 +00003646 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor85dabae2009-12-16 01:38:02 +00003648 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003650 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003651 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003652 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003653 return;
3654 }
3655
3656 // If the destination type has a lifetime property, zero-initialize it.
3657 if (DestType.getQualifiers().hasObjCLifetime()) {
3658 Sequence.AddZeroInitializationStep(Entity.getType());
3659 return;
3660 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003661}
3662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3664/// which enumerates all conversion functions and performs overload resolution
3665/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003667 const InitializedEntity &Entity,
3668 const InitializationKind &Kind,
3669 Expr *Initializer,
3670 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003671 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003672 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3673 QualType SourceType = Initializer->getType();
3674 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3675 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregor540c3b02009-12-14 17:27:33 +00003677 // Build the candidate set directly in the initialization sequence
3678 // structure, so that it will persist if we fail.
3679 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3680 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681
Douglas Gregor540c3b02009-12-14 17:27:33 +00003682 // Determine whether we are allowed to call explicit constructors or
3683 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003684 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685
Douglas Gregor540c3b02009-12-14 17:27:33 +00003686 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3687 // The type we're converting to is a class type. Enumerate its constructors
3688 // to see if there is a suitable conversion.
3689 CXXRecordDecl *DestRecordDecl
3690 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregord9848152010-04-26 14:36:57 +00003692 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003694 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003695 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003696 Con != ConEnd; ++Con) {
3697 NamedDecl *D = *Con;
3698 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699
Douglas Gregord9848152010-04-26 14:36:57 +00003700 // Find the constructor (which may be a template).
3701 CXXConstructorDecl *Constructor = 0;
3702 FunctionTemplateDecl *ConstructorTmpl
3703 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003704 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003705 Constructor = cast<CXXConstructorDecl>(
3706 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003707 else
Douglas Gregord9848152010-04-26 14:36:57 +00003708 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709
Douglas Gregord9848152010-04-26 14:36:57 +00003710 if (!Constructor->isInvalidDecl() &&
3711 Constructor->isConvertingConstructor(AllowExplicit)) {
3712 if (ConstructorTmpl)
3713 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3714 /*ExplicitArgs*/ 0,
3715 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003716 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003717 else
3718 S.AddOverloadCandidate(Constructor, FoundDecl,
3719 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003720 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722 }
Douglas Gregord9848152010-04-26 14:36:57 +00003723 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003724 }
Eli Friedman78275202009-12-19 08:11:05 +00003725
3726 SourceLocation DeclLoc = Initializer->getLocStart();
3727
Douglas Gregor540c3b02009-12-14 17:27:33 +00003728 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3729 // The type we're converting from is a class type, enumerate its conversion
3730 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003731
Eli Friedman4afe9a32009-12-20 22:12:03 +00003732 // We can only enumerate the conversion functions for a complete type; if
3733 // the type isn't complete, simply skip this step.
3734 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3735 CXXRecordDecl *SourceRecordDecl
3736 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
John McCallad371252010-01-20 00:46:10 +00003738 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003739 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003740 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003742 I != E; ++I) {
3743 NamedDecl *D = *I;
3744 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3745 if (isa<UsingShadowDecl>(D))
3746 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747
Eli Friedman4afe9a32009-12-20 22:12:03 +00003748 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3749 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003750 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003751 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003752 else
John McCallda4458e2010-03-31 01:36:47 +00003753 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
Eli Friedman4afe9a32009-12-20 22:12:03 +00003755 if (AllowExplicit || !Conv->isExplicit()) {
3756 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003757 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003758 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003759 CandidateSet);
3760 else
John McCalla0296f72010-03-19 07:35:19 +00003761 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003762 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003763 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003764 }
3765 }
3766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
3768 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003769 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003770 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003771 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003772 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003774 Result);
3775 return;
3776 }
John McCall0d1da222010-01-12 00:44:57 +00003777
Douglas Gregor540c3b02009-12-14 17:27:33 +00003778 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003779 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003780 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781
Douglas Gregor540c3b02009-12-14 17:27:33 +00003782 if (isa<CXXConstructorDecl>(Function)) {
3783 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00003784 // subsumed by the initialization. Per DR5, the created temporary is of the
3785 // cv-unqualified type of the destination.
3786 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3787 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003788 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003789 return;
3790 }
3791
3792 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003793 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003794 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00003795 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00003796 // the resulting temporary object (possible to create an object of
3797 // a base class type). That copy is not a separate conversion, so
3798 // we just make a note of the actual destination type (possibly a
3799 // base class of the type returned by the conversion function) and
3800 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003801 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3802 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003803 return;
3804 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003805
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003806 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3807 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Douglas Gregor5ab11652010-04-17 22:01:05 +00003809 // If the conversion following the call to the conversion function
3810 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003811 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3812 Best->FinalConversion.Third) {
3813 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003814 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003815 ICS.Standard = Best->FinalConversion;
3816 Sequence.AddConversionSequenceStep(ICS, DestType);
3817 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003818}
3819
John McCall31168b02011-06-15 23:02:42 +00003820/// The non-zero enum values here are indexes into diagnostic alternatives.
3821enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3822
3823/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003824static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3825 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003826 // Skip parens.
3827 e = e->IgnoreParens();
3828
3829 // Skip address-of nodes.
3830 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3831 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003832 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003833
3834 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003835 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3836 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003837 case CK_Dependent:
3838 case CK_BitCast:
3839 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003840 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003841 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003842
3843 case CK_ArrayToPointerDecay:
3844 return IIK_nonscalar;
3845
3846 case CK_NullToPointer:
3847 return IIK_okay;
3848
3849 default:
3850 break;
3851 }
3852
3853 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003854 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3855 if (!isAddressOf) return IIK_nonlocal;
3856
3857 VarDecl *var;
3858 if (isa<DeclRefExpr>(e)) {
3859 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3860 if (!var) return IIK_nonlocal;
3861 } else {
3862 var = cast<BlockDeclRefExpr>(e)->getDecl();
3863 }
3864
3865 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003866
3867 // If we have a conditional operator, check both sides.
3868 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003869 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003870 return iik;
3871
John McCall63f84442011-06-27 23:59:58 +00003872 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003873
3874 // These are never scalar.
3875 } else if (isa<ArraySubscriptExpr>(e)) {
3876 return IIK_nonscalar;
3877
3878 // Otherwise, it needs to be a null pointer constant.
3879 } else {
3880 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3881 ? IIK_okay : IIK_nonlocal);
3882 }
3883
3884 return IIK_nonlocal;
3885}
3886
3887/// Check whether the given expression is a valid operand for an
3888/// indirect copy/restore.
3889static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3890 assert(src->isRValue());
3891
John McCall63f84442011-06-27 23:59:58 +00003892 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003893 if (iik == IIK_okay) return;
3894
3895 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3896 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3897 << src->getSourceRange();
3898}
3899
Douglas Gregore2f943b2011-02-22 18:29:51 +00003900/// \brief Determine whether we have compatible array types for the
3901/// purposes of GNU by-copy array initialization.
3902static bool hasCompatibleArrayTypes(ASTContext &Context,
3903 const ArrayType *Dest,
3904 const ArrayType *Source) {
3905 // If the source and destination array types are equivalent, we're
3906 // done.
3907 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3908 return true;
3909
3910 // Make sure that the element types are the same.
3911 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3912 return false;
3913
3914 // The only mismatch we allow is when the destination is an
3915 // incomplete array type and the source is a constant array type.
3916 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3917}
3918
John McCall31168b02011-06-15 23:02:42 +00003919static bool tryObjCWritebackConversion(Sema &S,
3920 InitializationSequence &Sequence,
3921 const InitializedEntity &Entity,
3922 Expr *Initializer) {
3923 bool ArrayDecay = false;
3924 QualType ArgType = Initializer->getType();
3925 QualType ArgPointee;
3926 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3927 ArrayDecay = true;
3928 ArgPointee = ArgArrayType->getElementType();
3929 ArgType = S.Context.getPointerType(ArgPointee);
3930 }
3931
3932 // Handle write-back conversion.
3933 QualType ConvertedArgType;
3934 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3935 ConvertedArgType))
3936 return false;
3937
3938 // We should copy unless we're passing to an argument explicitly
3939 // marked 'out'.
3940 bool ShouldCopy = true;
3941 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3942 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3943
3944 // Do we need an lvalue conversion?
3945 if (ArrayDecay || Initializer->isGLValue()) {
3946 ImplicitConversionSequence ICS;
3947 ICS.setStandard();
3948 ICS.Standard.setAsIdentityConversion();
3949
3950 QualType ResultType;
3951 if (ArrayDecay) {
3952 ICS.Standard.First = ICK_Array_To_Pointer;
3953 ResultType = S.Context.getPointerType(ArgPointee);
3954 } else {
3955 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3956 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3957 }
3958
3959 Sequence.AddConversionSequenceStep(ICS, ResultType);
3960 }
3961
3962 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3963 return true;
3964}
3965
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003966InitializationSequence::InitializationSequence(Sema &S,
3967 const InitializedEntity &Entity,
3968 const InitializationKind &Kind,
3969 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003970 unsigned NumArgs)
3971 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003972 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003974 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975 // The semantics of initializers are as follows. The destination type is
3976 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003977 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003980 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003981
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003982 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003983 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3984 SequenceKind = DependentSequence;
3985 return;
3986 }
3987
Sebastian Redld201edf2011-06-05 13:59:11 +00003988 // Almost everything is a normal sequence.
3989 setSequenceKind(NormalSequence);
3990
John McCalled75c092010-12-07 22:54:16 +00003991 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003992 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003993 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003994 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3995 if (result.isInvalid()) {
3996 SetFailed(FK_PlaceholderType);
3997 return;
John McCall4124c492011-10-17 18:40:02 +00003998 }
John McCalld5c98ae2011-11-15 01:35:18 +00003999 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004000 }
John McCalled75c092010-12-07 22:54:16 +00004001
John McCall4124c492011-10-17 18:40:02 +00004002
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 QualType SourceType;
4004 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004005 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004006 Initializer = Args[0];
4007 if (!isa<InitListExpr>(Initializer))
4008 SourceType = Initializer->getType();
4009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
Sebastian Redl0501c632012-02-12 16:37:36 +00004011 // - If the initializer is a (non-parenthesized) braced-init-list, the
4012 // object is list-initialized (8.5.4).
4013 if (Kind.getKind() != InitializationKind::IK_Direct) {
4014 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4015 TryListInitialization(S, Entity, Kind, InitList, *this);
4016 return;
4017 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020 // - If the destination type is a reference type, see 8.5.3.
4021 if (DestType->isReferenceType()) {
4022 // C++0x [dcl.init.ref]p1:
4023 // A variable declared to be a T& or T&&, that is, "reference to type T"
4024 // (8.3.2), shall be initialized by an object, or function, of type T or
4025 // by an object that can be converted into a T.
4026 // (Therefore, multiple arguments are not permitted.)
4027 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004028 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004029 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004030 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004031 return;
4032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004035 if (Kind.getKind() == InitializationKind::IK_Value ||
4036 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004037 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004038 return;
4039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
Douglas Gregor85dabae2009-12-16 01:38:02 +00004041 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004042 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004043 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004044 return;
4045 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004046
John McCall66884dd2011-02-21 07:22:22 +00004047 // - If the destination type is an array of characters, an array of
4048 // char16_t, an array of char32_t, or an array of wchar_t, and the
4049 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004051 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004052 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004053 if (Initializer && isa<VariableArrayType>(DestAT)) {
4054 SetFailed(FK_VariableLengthArrayHasInitializer);
4055 return;
4056 }
4057
Douglas Gregore2f943b2011-02-22 18:29:51 +00004058 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004059 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004060 return;
4061 }
4062
Douglas Gregore2f943b2011-02-22 18:29:51 +00004063 // Note: as an GNU C extension, we allow initialization of an
4064 // array from a compound literal that creates an array of the same
4065 // type, so long as the initializer has no side effects.
4066 if (!S.getLangOptions().CPlusPlus && Initializer &&
4067 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4068 Initializer->getType()->isArrayType()) {
4069 const ArrayType *SourceAT
4070 = Context.getAsArrayType(Initializer->getType());
4071 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004072 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004073 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004074 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004075 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004076 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004077 }
Richard Smithebeed412012-02-15 22:38:09 +00004078 }
4079 // Note: as a GNU C++ extension, we allow initialization of a
4080 // class member from a parenthesized initializer list.
4081 else if (S.getLangOptions().CPlusPlus &&
4082 Entity.getKind() == InitializedEntity::EK_Member &&
4083 Initializer && isa<InitListExpr>(Initializer)) {
4084 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4085 *this);
4086 AddParenthesizedArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004087 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004088 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004089 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004090 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004092 return;
4093 }
Eli Friedman78275202009-12-19 08:11:05 +00004094
John McCall31168b02011-06-15 23:02:42 +00004095 // Determine whether we should consider writeback conversions for
4096 // Objective-C ARC.
4097 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4098 Entity.getKind() == InitializedEntity::EK_Parameter;
4099
4100 // We're at the end of the line for C: it's either a write-back conversion
4101 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004102 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004103 // If allowed, check whether this is an Objective-C writeback conversion.
4104 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004105 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004106 return;
4107 }
4108
4109 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004110 AddCAssignmentStep(DestType);
4111 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004112 return;
4113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114
John McCall31168b02011-06-15 23:02:42 +00004115 assert(S.getLangOptions().CPlusPlus);
4116
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004117 // - If the destination type is a (possibly cv-qualified) class type:
4118 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 // - If the initialization is direct-initialization, or if it is
4120 // copy-initialization where the cv-unqualified version of the
4121 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004122 // class of the destination, constructors are considered. [...]
4123 if (Kind.getKind() == InitializationKind::IK_Direct ||
4124 (Kind.getKind() == InitializationKind::IK_Copy &&
4125 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4126 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004128 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004130 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004132 // used) to a derived class thereof are enumerated as described in
4133 // 13.3.1.4, and the best one is chosen through overload resolution
4134 // (13.3).
4135 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004136 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004137 return;
4138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Douglas Gregor85dabae2009-12-16 01:38:02 +00004140 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004141 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004142 return;
4143 }
4144 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
4146 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004147 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004148 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004149 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4150 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004151 return;
4152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004153
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004154 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004155 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004159
4160 ImplicitConversionSequence ICS
4161 = S.TryImplicitConversion(Initializer, Entity.getType(),
4162 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004163 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004164 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004165 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4166 allowObjCWritebackConversion);
4167
4168 if (ICS.isStandard() &&
4169 ICS.Standard.Second == ICK_Writeback_Conversion) {
4170 // Objective-C ARC writeback conversion.
4171
4172 // We should copy unless we're passing to an argument explicitly
4173 // marked 'out'.
4174 bool ShouldCopy = true;
4175 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4176 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4177
4178 // If there was an lvalue adjustment, add it as a separate conversion.
4179 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4180 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4181 ImplicitConversionSequence LvalueICS;
4182 LvalueICS.setStandard();
4183 LvalueICS.Standard.setAsIdentityConversion();
4184 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4185 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004186 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004187 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004188
4189 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004190 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004191 DeclAccessPair dap;
4192 if (Initializer->getType() == Context.OverloadTy &&
4193 !S.ResolveAddressOfOverloadedFunction(Initializer
4194 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004195 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004196 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004197 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004198 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004199 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004200
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004201 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004202 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004203}
4204
4205InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004206 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004207 StepEnd = Steps.end();
4208 Step != StepEnd; ++Step)
4209 Step->Destroy();
4210}
4211
4212//===----------------------------------------------------------------------===//
4213// Perform initialization
4214//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004216getAssignmentAction(const InitializedEntity &Entity) {
4217 switch(Entity.getKind()) {
4218 case InitializedEntity::EK_Variable:
4219 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004220 case InitializedEntity::EK_Exception:
4221 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004222 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004223 return Sema::AA_Initializing;
4224
4225 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004227 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4228 return Sema::AA_Sending;
4229
Douglas Gregore1314a62009-12-18 05:02:21 +00004230 return Sema::AA_Passing;
4231
4232 case InitializedEntity::EK_Result:
4233 return Sema::AA_Returning;
4234
Douglas Gregore1314a62009-12-18 05:02:21 +00004235 case InitializedEntity::EK_Temporary:
4236 // FIXME: Can we tell apart casting vs. converting?
4237 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Douglas Gregore1314a62009-12-18 05:02:21 +00004239 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004240 case InitializedEntity::EK_ArrayElement:
4241 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004242 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004243 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004244 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004245 return Sema::AA_Initializing;
4246 }
4247
David Blaikie8a40f702012-01-17 06:56:22 +00004248 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004249}
4250
Douglas Gregor95562572010-04-24 23:45:46 +00004251/// \brief Whether we should binding a created object as a temporary when
4252/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004253static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004254 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004255 case InitializedEntity::EK_ArrayElement:
4256 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004257 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004258 case InitializedEntity::EK_New:
4259 case InitializedEntity::EK_Variable:
4260 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004261 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004262 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004263 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004264 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004265 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004266 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004267 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregore1314a62009-12-18 05:02:21 +00004269 case InitializedEntity::EK_Parameter:
4270 case InitializedEntity::EK_Temporary:
4271 return true;
4272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregore1314a62009-12-18 05:02:21 +00004274 llvm_unreachable("missed an InitializedEntity kind?");
4275}
4276
Douglas Gregor95562572010-04-24 23:45:46 +00004277/// \brief Whether the given entity, when initialized with an object
4278/// created for that initialization, requires destruction.
4279static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4280 switch (Entity.getKind()) {
4281 case InitializedEntity::EK_Member:
4282 case InitializedEntity::EK_Result:
4283 case InitializedEntity::EK_New:
4284 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004285 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004286 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004287 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004288 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004289 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004290 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregor95562572010-04-24 23:45:46 +00004292 case InitializedEntity::EK_Variable:
4293 case InitializedEntity::EK_Parameter:
4294 case InitializedEntity::EK_Temporary:
4295 case InitializedEntity::EK_ArrayElement:
4296 case InitializedEntity::EK_Exception:
4297 return true;
4298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
4300 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004301}
4302
Richard Smithc620f552011-10-19 16:55:56 +00004303/// \brief Look for copy and move constructors and constructor templates, for
4304/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4305static void LookupCopyAndMoveConstructors(Sema &S,
4306 OverloadCandidateSet &CandidateSet,
4307 CXXRecordDecl *Class,
4308 Expr *CurInitExpr) {
4309 DeclContext::lookup_iterator Con, ConEnd;
4310 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4311 Con != ConEnd; ++Con) {
4312 CXXConstructorDecl *Constructor = 0;
4313
4314 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4315 // Handle copy/moveconstructors, only.
4316 if (!Constructor || Constructor->isInvalidDecl() ||
4317 !Constructor->isCopyOrMoveConstructor() ||
4318 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4319 continue;
4320
4321 DeclAccessPair FoundDecl
4322 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4323 S.AddOverloadCandidate(Constructor, FoundDecl,
4324 &CurInitExpr, 1, CandidateSet);
4325 continue;
4326 }
4327
4328 // Handle constructor templates.
4329 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4330 if (ConstructorTmpl->isInvalidDecl())
4331 continue;
4332
4333 Constructor = cast<CXXConstructorDecl>(
4334 ConstructorTmpl->getTemplatedDecl());
4335 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4336 continue;
4337
4338 // FIXME: Do we need to limit this to copy-constructor-like
4339 // candidates?
4340 DeclAccessPair FoundDecl
4341 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4342 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4343 &CurInitExpr, 1, CandidateSet, true);
4344 }
4345}
4346
4347/// \brief Get the location at which initialization diagnostics should appear.
4348static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4349 Expr *Initializer) {
4350 switch (Entity.getKind()) {
4351 case InitializedEntity::EK_Result:
4352 return Entity.getReturnLoc();
4353
4354 case InitializedEntity::EK_Exception:
4355 return Entity.getThrowLoc();
4356
4357 case InitializedEntity::EK_Variable:
4358 return Entity.getDecl()->getLocation();
4359
Douglas Gregor19666fb2012-02-15 16:57:26 +00004360 case InitializedEntity::EK_LambdaCapture:
4361 return Entity.getCaptureLoc();
4362
Richard Smithc620f552011-10-19 16:55:56 +00004363 case InitializedEntity::EK_ArrayElement:
4364 case InitializedEntity::EK_Member:
4365 case InitializedEntity::EK_Parameter:
4366 case InitializedEntity::EK_Temporary:
4367 case InitializedEntity::EK_New:
4368 case InitializedEntity::EK_Base:
4369 case InitializedEntity::EK_Delegating:
4370 case InitializedEntity::EK_VectorElement:
4371 case InitializedEntity::EK_ComplexElement:
4372 case InitializedEntity::EK_BlockElement:
4373 return Initializer->getLocStart();
4374 }
4375 llvm_unreachable("missed an InitializedEntity kind?");
4376}
4377
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004378/// \brief Make a (potentially elidable) temporary copy of the object
4379/// provided by the given initializer by calling the appropriate copy
4380/// constructor.
4381///
4382/// \param S The Sema object used for type-checking.
4383///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004384/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004385/// the type of the initializer expression or a superclass thereof.
4386///
4387/// \param Enter The entity being initialized.
4388///
4389/// \param CurInit The initializer expression.
4390///
4391/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4392/// is permitted in C++03 (but not C++0x) when binding a reference to
4393/// an rvalue.
4394///
4395/// \returns An expression that copies the initializer expression into
4396/// a temporary object, or an error expression if a copy could not be
4397/// created.
John McCalldadc5752010-08-24 06:29:42 +00004398static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004399 QualType T,
4400 const InitializedEntity &Entity,
4401 ExprResult CurInit,
4402 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004403 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004404 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004406 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004407 Class = cast<CXXRecordDecl>(Record->getDecl());
4408 if (!Class)
4409 return move(CurInit);
4410
Douglas Gregor5d369002011-01-21 18:05:27 +00004411 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004412 // When certain criteria are met, an implementation is allowed to
4413 // omit the copy/move construction of a class object, even if the
4414 // copy/move constructor and/or destructor for the object have
4415 // side effects. [...]
4416 // - when a temporary class object that has not been bound to a
4417 // reference (12.2) would be copied/moved to a class object
4418 // with the same cv-unqualified type, the copy/move operation
4419 // can be omitted by constructing the temporary object
4420 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004422 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004423 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004425 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004426 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004427 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004430 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4431 return move(CurInit);
4432
Douglas Gregorf282a762011-01-21 19:38:21 +00004433 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004434 // Only consider constructors and constructor templates. Per
4435 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4436 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004437 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004438 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004440 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4441
Douglas Gregore1314a62009-12-18 05:02:21 +00004442 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004443 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004444 case OR_Success:
4445 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Douglas Gregore1314a62009-12-18 05:02:21 +00004447 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004448 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4449 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4450 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004451 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004452 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004453 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004454 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004455 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004456 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregore1314a62009-12-18 05:02:21 +00004458 case OR_Ambiguous:
4459 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004460 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004461 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004462 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004463 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
Douglas Gregore1314a62009-12-18 05:02:21 +00004465 case OR_Deleted:
4466 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004467 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004468 << CurInitExpr->getSourceRange();
4469 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004470 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004471 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004472 }
4473
Douglas Gregor5ab11652010-04-17 22:01:05 +00004474 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004475 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004476 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004477
Anders Carlssona01874b2010-04-21 18:47:17 +00004478 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004479 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004480
4481 if (IsExtraneousCopy) {
4482 // If this is a totally extraneous copy for C++03 reference
4483 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004484 // expression. We don't generate an (elided) copy operation here
4485 // because doing so would require us to pass down a flag to avoid
4486 // infinite recursion, where each step adds another extraneous,
4487 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004488
Douglas Gregor30b52772010-04-18 07:57:34 +00004489 // Instantiate the default arguments of any extra parameters in
4490 // the selected copy constructor, as if we were going to create a
4491 // proper call to the copy constructor.
4492 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4493 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4494 if (S.RequireCompleteType(Loc, Parm->getType(),
4495 S.PDiag(diag::err_call_incomplete_argument)))
4496 break;
4497
4498 // Build the default argument expression; we don't actually care
4499 // if this succeeds or not, because this routine will complain
4500 // if there was a problem.
4501 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4502 }
4503
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004504 return S.Owned(CurInitExpr);
4505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Eli Friedmanfa0df832012-02-02 03:46:19 +00004507 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004508
Douglas Gregor5ab11652010-04-17 22:01:05 +00004509 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004510 // constructor call (we might have derived-to-base conversions, or
4511 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004512 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004513 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004514 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004515
Douglas Gregord0ace022010-04-25 00:55:24 +00004516 // Actually perform the constructor call.
4517 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004518 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004519 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004520 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004521 CXXConstructExpr::CK_Complete,
4522 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
Douglas Gregord0ace022010-04-25 00:55:24 +00004524 // If we're supposed to bind temporaries, do so.
4525 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4526 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4527 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004528}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004529
Richard Smithc620f552011-10-19 16:55:56 +00004530/// \brief Check whether elidable copy construction for binding a reference to
4531/// a temporary would have succeeded if we were building in C++98 mode, for
4532/// -Wc++98-compat.
4533static void CheckCXX98CompatAccessibleCopy(Sema &S,
4534 const InitializedEntity &Entity,
4535 Expr *CurInitExpr) {
4536 assert(S.getLangOptions().CPlusPlus0x);
4537
4538 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4539 if (!Record)
4540 return;
4541
4542 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4543 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4544 == DiagnosticsEngine::Ignored)
4545 return;
4546
4547 // Find constructors which would have been considered.
4548 OverloadCandidateSet CandidateSet(Loc);
4549 LookupCopyAndMoveConstructors(
4550 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4551
4552 // Perform overload resolution.
4553 OverloadCandidateSet::iterator Best;
4554 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4555
4556 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4557 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4558 << CurInitExpr->getSourceRange();
4559
4560 switch (OR) {
4561 case OR_Success:
4562 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4563 Best->FoundDecl.getAccess(), Diag);
4564 // FIXME: Check default arguments as far as that's possible.
4565 break;
4566
4567 case OR_No_Viable_Function:
4568 S.Diag(Loc, Diag);
4569 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4570 break;
4571
4572 case OR_Ambiguous:
4573 S.Diag(Loc, Diag);
4574 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4575 break;
4576
4577 case OR_Deleted:
4578 S.Diag(Loc, Diag);
4579 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4580 << 1 << Best->Function->isDeleted();
4581 break;
4582 }
4583}
4584
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004585void InitializationSequence::PrintInitLocationNote(Sema &S,
4586 const InitializedEntity &Entity) {
4587 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4588 if (Entity.getDecl()->getLocation().isInvalid())
4589 return;
4590
4591 if (Entity.getDecl()->getDeclName())
4592 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4593 << Entity.getDecl()->getDeclName();
4594 else
4595 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4596 }
4597}
4598
Sebastian Redl112aa822011-07-14 19:07:55 +00004599static bool isReferenceBinding(const InitializationSequence::Step &s) {
4600 return s.Kind == InitializationSequence::SK_BindReference ||
4601 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4602}
4603
Sebastian Redled2e5322011-12-22 14:44:04 +00004604static ExprResult
4605PerformConstructorInitialization(Sema &S,
4606 const InitializedEntity &Entity,
4607 const InitializationKind &Kind,
4608 MultiExprArg Args,
4609 const InitializationSequence::Step& Step,
4610 bool &ConstructorInitRequiresZeroInit) {
4611 unsigned NumArgs = Args.size();
4612 CXXConstructorDecl *Constructor
4613 = cast<CXXConstructorDecl>(Step.Function.Function);
4614 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4615
4616 // Build a call to the selected constructor.
4617 ASTOwningVector<Expr*> ConstructorArgs(S);
4618 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4619 ? Kind.getEqualLoc()
4620 : Kind.getLocation();
4621
4622 if (Kind.getKind() == InitializationKind::IK_Default) {
4623 // Force even a trivial, implicit default constructor to be
4624 // semantically checked. We do this explicitly because we don't build
4625 // the definition for completely trivial constructors.
4626 CXXRecordDecl *ClassDecl = Constructor->getParent();
4627 assert(ClassDecl && "No parent class for constructor.");
4628 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4629 ClassDecl->hasTrivialDefaultConstructor() &&
4630 !Constructor->isUsed(false))
4631 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4632 }
4633
4634 ExprResult CurInit = S.Owned((Expr *)0);
4635
4636 // Determine the arguments required to actually perform the constructor
4637 // call.
4638 if (S.CompleteConstructorCall(Constructor, move(Args),
4639 Loc, ConstructorArgs))
4640 return ExprError();
4641
4642
4643 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4644 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4645 (Kind.getKind() == InitializationKind::IK_Direct ||
4646 Kind.getKind() == InitializationKind::IK_Value)) {
4647 // An explicitly-constructed temporary, e.g., X(1, 2).
4648 unsigned NumExprs = ConstructorArgs.size();
4649 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004650 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004651 S.DiagnoseUseOfDecl(Constructor, Loc);
4652
4653 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4654 if (!TSInfo)
4655 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4656
4657 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4658 Constructor,
4659 TSInfo,
4660 Exprs,
4661 NumExprs,
4662 Kind.getParenRange(),
4663 HadMultipleCandidates,
4664 ConstructorInitRequiresZeroInit));
4665 } else {
4666 CXXConstructExpr::ConstructionKind ConstructKind =
4667 CXXConstructExpr::CK_Complete;
4668
4669 if (Entity.getKind() == InitializedEntity::EK_Base) {
4670 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4671 CXXConstructExpr::CK_VirtualBase :
4672 CXXConstructExpr::CK_NonVirtualBase;
4673 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4674 ConstructKind = CXXConstructExpr::CK_Delegating;
4675 }
4676
4677 // Only get the parenthesis range if it is a direct construction.
4678 SourceRange parenRange =
4679 Kind.getKind() == InitializationKind::IK_Direct ?
4680 Kind.getParenRange() : SourceRange();
4681
4682 // If the entity allows NRVO, mark the construction as elidable
4683 // unconditionally.
4684 if (Entity.allowsNRVO())
4685 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4686 Constructor, /*Elidable=*/true,
4687 move_arg(ConstructorArgs),
4688 HadMultipleCandidates,
4689 ConstructorInitRequiresZeroInit,
4690 ConstructKind,
4691 parenRange);
4692 else
4693 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4694 Constructor,
4695 move_arg(ConstructorArgs),
4696 HadMultipleCandidates,
4697 ConstructorInitRequiresZeroInit,
4698 ConstructKind,
4699 parenRange);
4700 }
4701 if (CurInit.isInvalid())
4702 return ExprError();
4703
4704 // Only check access if all of that succeeded.
4705 S.CheckConstructorAccess(Loc, Constructor, Entity,
4706 Step.Function.FoundDecl.getAccess());
4707 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4708
4709 if (shouldBindAsTemporary(Entity))
4710 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4711
4712 return move(CurInit);
4713}
4714
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004716InitializationSequence::Perform(Sema &S,
4717 const InitializedEntity &Entity,
4718 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004719 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004720 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004721 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004722 unsigned NumArgs = Args.size();
4723 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004724 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726
Sebastian Redld201edf2011-06-05 13:59:11 +00004727 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004728 // If the declaration is a non-dependent, incomplete array type
4729 // that has an initializer, then its type will be completed once
4730 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004731 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004732 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004733 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004734 if (const IncompleteArrayType *ArrayT
4735 = S.Context.getAsIncompleteArrayType(DeclType)) {
4736 // FIXME: We don't currently have the ability to accurately
4737 // compute the length of an initializer list without
4738 // performing full type-checking of the initializer list
4739 // (since we have to determine where braces are implicitly
4740 // introduced and such). So, we fall back to making the array
4741 // type a dependently-sized array type with no specified
4742 // bound.
4743 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4744 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004745
Douglas Gregor51e77d52009-12-10 17:56:55 +00004746 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004747 if (DeclaratorDecl *DD = Entity.getDecl()) {
4748 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4749 TypeLoc TL = TInfo->getTypeLoc();
4750 if (IncompleteArrayTypeLoc *ArrayLoc
4751 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4752 Brackets = ArrayLoc->getBracketsRange();
4753 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004754 }
4755
4756 *ResultType
4757 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4758 /*NumElts=*/0,
4759 ArrayT->getSizeModifier(),
4760 ArrayT->getIndexTypeCVRQualifiers(),
4761 Brackets);
4762 }
4763
4764 }
4765 }
Sebastian Redla9351792012-02-11 23:51:47 +00004766 if (Kind.getKind() == InitializationKind::IK_Direct &&
4767 !Kind.isExplicitCast()) {
4768 // Rebuild the ParenListExpr.
4769 SourceRange ParenRange = Kind.getParenRange();
4770 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4771 move(Args));
4772 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004773 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4774 Kind.isExplicitCast());
4775 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004776 }
4777
Sebastian Redld201edf2011-06-05 13:59:11 +00004778 // No steps means no initialization.
4779 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004780 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Douglas Gregor1b303932009-12-22 15:35:07 +00004782 QualType DestType = Entity.getType().getNonReferenceType();
4783 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004784 // the same as Entity.getDecl()->getType() in cases involving type merging,
4785 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004786 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004787 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004788 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004789
John McCalldadc5752010-08-24 06:29:42 +00004790 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004793 // grab the only argument out the Args and place it into the "current"
4794 // initializer.
4795 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004796 case SK_ResolveAddressOfOverloadedFunction:
4797 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004798 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004799 case SK_CastDerivedToBaseLValue:
4800 case SK_BindReference:
4801 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004802 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004803 case SK_UserConversion:
4804 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004805 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004806 case SK_QualificationConversionRValue:
4807 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004808 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004809 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004810 case SK_UnwrapInitList:
4811 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004812 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004813 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004814 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004815 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00004816 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00004817 case SK_PassByIndirectCopyRestore:
4818 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004819 case SK_ProduceObjCObject:
4820 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004821 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004822 CurInit = Args.get()[0];
4823 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004824 break;
John McCall34376a62010-12-04 03:47:34 +00004825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826
Douglas Gregore1314a62009-12-18 05:02:21 +00004827 case SK_ConstructorInitialization:
4828 case SK_ZeroInitialization:
4829 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
4832 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004833 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004834 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 for (step_iterator Step = step_begin(), StepEnd = step_end();
4836 Step != StepEnd; ++Step) {
4837 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004838 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
John Wiegley01296292011-04-08 18:41:53 +00004840 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 switch (Step->Kind) {
4843 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004845 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004846 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004847 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004848 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004849 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004850 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004854 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004855 case SK_CastDerivedToBaseLValue: {
4856 // We have a derived-to-base cast that produces either an rvalue or an
4857 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858
John McCallcf142162010-08-07 06:22:56 +00004859 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004860
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004861 // Casts to inaccessible base classes are allowed with C-style casts.
4862 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4863 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004864 CurInit.get()->getLocStart(),
4865 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004866 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004867 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Douglas Gregor88d292c2010-05-13 16:44:06 +00004869 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4870 QualType T = SourceType;
4871 if (const PointerType *Pointer = T->getAs<PointerType>())
4872 T = Pointer->getPointeeType();
4873 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004874 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004875 cast<CXXRecordDecl>(RecordTy->getDecl()));
4876 }
4877
John McCall2536c6d2010-08-25 10:28:54 +00004878 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004879 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004880 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004881 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004882 VK_XValue :
4883 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004884 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4885 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004886 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004887 CurInit.get(),
4888 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004889 break;
4890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004892 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004893 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004894 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4895 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004896 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004898 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004899 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004900 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004901 }
Anders Carlssona91be642010-01-29 02:47:33 +00004902
John Wiegley01296292011-04-08 18:41:53 +00004903 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004904 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004905 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4906 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004907 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004908 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004909 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004912 // Reference binding does not have any corresponding ASTs.
4913
4914 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004915 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004916 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004918 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004920 case SK_BindReferenceToTemporary:
4921 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004922 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004923 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004924
Douglas Gregorfe314812011-06-21 17:03:29 +00004925 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004926 CurInit = new (S.Context) MaterializeTemporaryExpr(
4927 Entity.getType().getNonReferenceType(),
4928 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004929 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004930
4931 // If we're binding to an Objective-C object that has lifetime, we
4932 // need cleanups.
4933 if (S.getLangOptions().ObjCAutoRefCount &&
4934 CurInit.get()->getType()->isObjCLifetimeType())
4935 S.ExprNeedsCleanups = true;
4936
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004937 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004939 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004941 /*IsExtraneousCopy=*/true);
4942 break;
4943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004944 case SK_UserConversion: {
4945 // We have a user-defined conversion that invokes either a constructor
4946 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004947 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004948 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004949 FunctionDecl *Fn = Step->Function.Function;
4950 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004951 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004952 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004953 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004954 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004955 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004956 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004957 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004958
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004959 // Determine the arguments required to actually perform the constructor
4960 // call.
John Wiegley01296292011-04-08 18:41:53 +00004961 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004962 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004963 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004965 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966
Richard Smithb24f0672012-02-11 19:22:50 +00004967 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004969 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004970 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004971 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004972 CXXConstructExpr::CK_Complete,
4973 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004974 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004975 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004976
Anders Carlssona01874b2010-04-21 18:47:17 +00004977 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004978 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004979 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
John McCalle3027922010-08-25 11:45:40 +00004981 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004982 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4983 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4984 S.IsDerivedFrom(SourceType, Class))
4985 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
Douglas Gregor95562572010-04-24 23:45:46 +00004987 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004988 } else {
4989 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004990 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004991 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004992 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004993 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994
4995 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004996 // derived-to-base conversion? I believe the answer is "no", because
4997 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004998 ExprResult CurInitExprRes =
4999 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5000 FoundFn, Conversion);
5001 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005002 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005003 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005005 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005006 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5007 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005008 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005009 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005010
John McCalle3027922010-08-25 11:45:40 +00005011 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Douglas Gregor95562572010-04-24 23:45:46 +00005013 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015
Sebastian Redl112aa822011-07-14 19:07:55 +00005016 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005017 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5018
5019 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005020 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005021 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005023 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005024 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005025 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005026 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00005027 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005028 }
5029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
John McCallcf142162010-08-07 06:22:56 +00005031 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005032 CurInit.get()->getType(),
5033 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005034 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005035 if (MaybeBindToTemp)
5036 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005037 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005038 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5039 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005040 break;
5041 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005042
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005043 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005044 case SK_QualificationConversionXValue:
5045 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005046 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005047 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005048 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005049 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005050 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005051 VK_XValue :
5052 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005053 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005054 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005055 }
5056
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005057 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005058 Sema::CheckedConversionKind CCK
5059 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5060 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005061 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005062 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005063 ExprResult CurInitExprRes =
5064 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005065 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005066 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005067 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005068 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005069 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071
Douglas Gregor51e77d52009-12-10 17:56:55 +00005072 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005073 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005074 // Hack: We must pass *ResultType if available in order to set the type
5075 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5076 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5077 // temporary, not a reference, so we should pass Ty.
5078 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5079 // Since this step is never used for a reference directly, we explicitly
5080 // unwrap references here and rewrap them afterwards.
5081 // We also need to create a InitializeTemporary entity for this.
5082 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5083 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5084 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5085 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5086 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005087 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005088 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005089 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005090 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005091
Sebastian Redl29526f02011-11-27 16:50:07 +00005092 if (ResultType) {
5093 if ((*ResultType)->isRValueReferenceType())
5094 Ty = S.Context.getRValueReferenceType(Ty);
5095 else if ((*ResultType)->isLValueReferenceType())
5096 Ty = S.Context.getLValueReferenceType(Ty,
5097 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5098 *ResultType = Ty;
5099 }
5100
5101 InitListExpr *StructuredInitList =
5102 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005103 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005104 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005105 break;
5106 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005107
Sebastian Redled2e5322011-12-22 14:44:04 +00005108 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005109 // When an initializer list is passed for a parameter of type "reference
5110 // to object", we don't get an EK_Temporary entity, but instead an
5111 // EK_Parameter entity with reference type.
5112 // FIXME: This is a hack. Why is this necessary here, but not in other
5113 // places where implicit temporaries are created?
5114 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5115 Entity.getType().getNonReferenceType());
5116 bool UseTemporary = Entity.getType()->isReferenceType();
Sebastian Redled2e5322011-12-22 14:44:04 +00005117 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5118 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00005119 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5120 Entity,
5121 Kind, move(Arg), *Step,
Sebastian Redled2e5322011-12-22 14:44:04 +00005122 ConstructorInitRequiresZeroInit);
5123 break;
5124 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005125
Sebastian Redl29526f02011-11-27 16:50:07 +00005126 case SK_UnwrapInitList:
5127 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5128 break;
5129
5130 case SK_RewrapInitList: {
5131 Expr *E = CurInit.take();
5132 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5133 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5134 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5135 ILE->setSyntacticForm(Syntactic);
5136 ILE->setType(E->getType());
5137 ILE->setValueKind(E->getValueKind());
5138 CurInit = S.Owned(ILE);
5139 break;
5140 }
5141
Sebastian Redled2e5322011-12-22 14:44:04 +00005142 case SK_ConstructorInitialization:
5143 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5144 *Step,
5145 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005148 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005149 step_iterator NextStep = Step;
5150 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005152 NextStep->Kind == SK_ConstructorInitialization) {
5153 // The need for zero-initialization is recorded directly into
5154 // the call to the object's constructor within the next step.
5155 ConstructorInitRequiresZeroInit = true;
5156 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5157 S.getLangOptions().CPlusPlus &&
5158 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005159 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5160 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005162 Kind.getRange().getBegin());
5163
5164 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5165 TSInfo->getType().getNonLValueExprType(S.Context),
5166 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005167 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005168 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005169 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005170 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005171 break;
5172 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005173
5174 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005175 QualType SourceType = CurInit.get()->getType();
5176 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005177 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005178 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5179 if (Result.isInvalid())
5180 return ExprError();
5181 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005182
5183 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005184 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005185 if (ConvTy != Sema::Compatible &&
5186 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005187 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005188 == Sema::Compatible)
5189 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005190 if (CurInitExprRes.isInvalid())
5191 return ExprError();
5192 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005193
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005194 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005195 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5196 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005197 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005198 getAssignmentAction(Entity),
5199 &Complained)) {
5200 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005201 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005202 } else if (Complained)
5203 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005204 break;
5205 }
Eli Friedman78275202009-12-19 08:11:05 +00005206
5207 case SK_StringInit: {
5208 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005209 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005210 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005211 break;
5212 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005213
5214 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005215 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005216 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005217 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005218 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005219
5220 case SK_ArrayInit:
5221 // Okay: we checked everything before creating this step. Note that
5222 // this is a GNU extension.
5223 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005224 << Step->Type << CurInit.get()->getType()
5225 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005226
5227 // If the destination type is an incomplete array type, update the
5228 // type accordingly.
5229 if (ResultType) {
5230 if (const IncompleteArrayType *IncompleteDest
5231 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5232 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005233 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005234 *ResultType = S.Context.getConstantArrayType(
5235 IncompleteDest->getElementType(),
5236 ConstantSource->getSize(),
5237 ArrayType::Normal, 0);
5238 }
5239 }
5240 }
John McCall31168b02011-06-15 23:02:42 +00005241 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005242
Richard Smithebeed412012-02-15 22:38:09 +00005243 case SK_ParenthesizedArrayInit:
5244 // Okay: we checked everything before creating this step. Note that
5245 // this is a GNU extension.
5246 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5247 << CurInit.get()->getSourceRange();
5248 break;
5249
John McCall31168b02011-06-15 23:02:42 +00005250 case SK_PassByIndirectCopyRestore:
5251 case SK_PassByIndirectRestore:
5252 checkIndirectCopyRestoreSource(S, CurInit.get());
5253 CurInit = S.Owned(new (S.Context)
5254 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5255 Step->Kind == SK_PassByIndirectCopyRestore));
5256 break;
5257
5258 case SK_ProduceObjCObject:
5259 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005260 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005261 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005262 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005263
5264 case SK_StdInitializerList: {
5265 QualType Dest = Step->Type;
5266 QualType E;
5267 bool Success = S.isStdInitializerList(Dest, &E);
5268 (void)Success;
5269 assert(Success && "Destination type changed?");
5270 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5271 unsigned NumInits = ILE->getNumInits();
5272 SmallVector<Expr*, 16> Converted(NumInits);
5273 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5274 S.Context.getConstantArrayType(E,
5275 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5276 NumInits),
5277 ArrayType::Normal, 0));
5278 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5279 0, HiddenArray);
5280 for (unsigned i = 0; i < NumInits; ++i) {
5281 Element.setElementIndex(i);
5282 ExprResult Init = S.Owned(ILE->getInit(i));
5283 ExprResult Res = S.PerformCopyInitialization(Element,
5284 Init.get()->getExprLoc(),
5285 Init);
5286 assert(!Res.isInvalid() && "Result changed since try phase.");
5287 Converted[i] = Res.take();
5288 }
5289 InitListExpr *Semantic = new (S.Context)
5290 InitListExpr(S.Context, ILE->getLBraceLoc(),
5291 Converted.data(), NumInits, ILE->getRBraceLoc());
5292 Semantic->setSyntacticForm(ILE);
5293 Semantic->setType(Dest);
Sebastian Redlc83ed822012-02-17 08:42:25 +00005294 Semantic->setInitializesStdInitializerList();
Sebastian Redlc1839b12012-01-17 22:49:42 +00005295 CurInit = S.Owned(Semantic);
5296 break;
5297 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298 }
5299 }
John McCall1f425642010-11-11 03:21:53 +00005300
5301 // Diagnose non-fatal problems with the completed initialization.
5302 if (Entity.getKind() == InitializedEntity::EK_Member &&
5303 cast<FieldDecl>(Entity.getDecl())->isBitField())
5304 S.CheckBitFieldInitialization(Kind.getLocation(),
5305 cast<FieldDecl>(Entity.getDecl()),
5306 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005308 return move(CurInit);
5309}
5310
Douglas Gregor74f7d502012-02-15 19:33:52 +00005311/// \brief Provide some notes that detail why a function was implicitly
5312/// deleted.
5313static void diagnoseImplicitlyDeletedFunction(Sema &S, CXXMethodDecl *Method) {
5314 // FIXME: This is a work in progress. It should dig deeper to figure out
5315 // why the function was deleted (e.g., because one of its members doesn't
5316 // have a copy constructor, for the copy-constructor case).
5317 if (!Method->isImplicit()) {
5318 S.Diag(Method->getLocation(), diag::note_callee_decl)
5319 << Method->getDeclName();
5320 }
5321
5322 if (Method->getParent()->isLambda()) {
5323 S.Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
5324 return;
5325 }
5326
5327 S.Diag(Method->getParent()->getLocation(), diag::note_defined_here)
5328 << Method->getParent();
5329}
5330
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331//===----------------------------------------------------------------------===//
5332// Diagnose initialization failures
5333//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005335 const InitializedEntity &Entity,
5336 const InitializationKind &Kind,
5337 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005338 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005339 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005340
Douglas Gregor1b303932009-12-22 15:35:07 +00005341 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005342 switch (Failure) {
5343 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005344 // FIXME: Customize for the initialized entity?
5345 if (NumArgs == 0)
5346 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5347 << DestType.getNonReferenceType();
5348 else // FIXME: diagnostic below could be better!
5349 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5350 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005351 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005353 case FK_ArrayNeedsInitList:
5354 case FK_ArrayNeedsInitListOrStringLiteral:
5355 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5356 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5357 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358
Douglas Gregore2f943b2011-02-22 18:29:51 +00005359 case FK_ArrayTypeMismatch:
5360 case FK_NonConstantArrayInit:
5361 S.Diag(Kind.getLocation(),
5362 (Failure == FK_ArrayTypeMismatch
5363 ? diag::err_array_init_different_type
5364 : diag::err_array_init_non_constant_array))
5365 << DestType.getNonReferenceType()
5366 << Args[0]->getType()
5367 << Args[0]->getSourceRange();
5368 break;
5369
John McCalla59dc2f2012-01-05 00:13:19 +00005370 case FK_VariableLengthArrayHasInitializer:
5371 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5372 << Args[0]->getSourceRange();
5373 break;
5374
John McCall16df1e52010-03-30 21:47:33 +00005375 case FK_AddressOfOverloadFailed: {
5376 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005377 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005378 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005379 true,
5380 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005381 break;
John McCall16df1e52010-03-30 21:47:33 +00005382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005384 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005385 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005386 switch (FailedOverloadResult) {
5387 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005388 if (Failure == FK_UserConversionOverloadFailed)
5389 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5390 << Args[0]->getType() << DestType
5391 << Args[0]->getSourceRange();
5392 else
5393 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5394 << DestType << Args[0]->getType()
5395 << Args[0]->getSourceRange();
5396
John McCall5c32be02010-08-24 20:38:10 +00005397 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005399
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005400 case OR_No_Viable_Function:
5401 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5402 << Args[0]->getType() << DestType.getNonReferenceType()
5403 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005404 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005405 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005406
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005407 case OR_Deleted: {
5408 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5409 << Args[0]->getType() << DestType.getNonReferenceType()
5410 << Args[0]->getSourceRange();
5411 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005412 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005413 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5414 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005415 if (Ovl == OR_Deleted) {
5416 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005417 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005418 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005419 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005420 }
5421 break;
5422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005424 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005425 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005426 }
5427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005429 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005430 if (isa<InitListExpr>(Args[0])) {
5431 S.Diag(Kind.getLocation(),
5432 diag::err_lvalue_reference_bind_to_initlist)
5433 << DestType.getNonReferenceType().isVolatileQualified()
5434 << DestType.getNonReferenceType()
5435 << Args[0]->getSourceRange();
5436 break;
5437 }
5438 // Intentional fallthrough
5439
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005440 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005441 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005442 Failure == FK_NonConstLValueReferenceBindingToTemporary
5443 ? diag::err_lvalue_reference_bind_to_temporary
5444 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005445 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005446 << DestType.getNonReferenceType()
5447 << Args[0]->getType()
5448 << Args[0]->getSourceRange();
5449 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005451 case FK_RValueReferenceBindingToLValue:
5452 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005453 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005454 << Args[0]->getSourceRange();
5455 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005457 case FK_ReferenceInitDropsQualifiers:
5458 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5459 << DestType.getNonReferenceType()
5460 << Args[0]->getType()
5461 << Args[0]->getSourceRange();
5462 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005464 case FK_ReferenceInitFailed:
5465 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5466 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005467 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005468 << Args[0]->getType()
5469 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005470 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5471 Args[0]->getType()->isObjCObjectPointerType())
5472 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005473 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474
Douglas Gregorb491ed32011-02-19 21:32:49 +00005475 case FK_ConversionFailed: {
5476 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005477 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005478 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005479 << DestType
John McCall086a4642010-11-24 05:12:34 +00005480 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005481 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005482 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005483 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5484 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005485 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5486 Args[0]->getType()->isObjCObjectPointerType())
5487 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005488 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005489 }
John Wiegley01296292011-04-08 18:41:53 +00005490
5491 case FK_ConversionFromPropertyFailed:
5492 // No-op. This error has already been reported.
5493 break;
5494
Douglas Gregor51e77d52009-12-10 17:56:55 +00005495 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005496 SourceRange R;
5497
5498 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005499 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005500 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005502 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005503
Douglas Gregor8ec51732010-09-08 21:40:08 +00005504 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5505 if (Kind.isCStyleOrFunctionalCast())
5506 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5507 << R;
5508 else
5509 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5510 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005511 break;
5512 }
5513
5514 case FK_ReferenceBindingToInitList:
5515 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5516 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5517 break;
5518
5519 case FK_InitListBadDestinationType:
5520 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5521 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5522 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005524 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005525 case FK_ConstructorOverloadFailed: {
5526 SourceRange ArgsRange;
5527 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005529 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005531 if (Failure == FK_ListConstructorOverloadFailed) {
5532 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5533 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5534 Args = InitList->getInits();
5535 NumArgs = InitList->getNumInits();
5536 }
5537
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005538 // FIXME: Using "DestType" for the entity we're printing is probably
5539 // bad.
5540 switch (FailedOverloadResult) {
5541 case OR_Ambiguous:
5542 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5543 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005544 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5545 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005546 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005547
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005548 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005549 if (Kind.getKind() == InitializationKind::IK_Default &&
5550 (Entity.getKind() == InitializedEntity::EK_Base ||
5551 Entity.getKind() == InitializedEntity::EK_Member) &&
5552 isa<CXXConstructorDecl>(S.CurContext)) {
5553 // This is implicit default initialization of a member or
5554 // base within a constructor. If no viable function was
5555 // found, notify the user that she needs to explicitly
5556 // initialize this base/member.
5557 CXXConstructorDecl *Constructor
5558 = cast<CXXConstructorDecl>(S.CurContext);
5559 if (Entity.getKind() == InitializedEntity::EK_Base) {
5560 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5561 << Constructor->isImplicit()
5562 << S.Context.getTypeDeclType(Constructor->getParent())
5563 << /*base=*/0
5564 << Entity.getType();
5565
5566 RecordDecl *BaseDecl
5567 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5568 ->getDecl();
5569 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5570 << S.Context.getTagDeclType(BaseDecl);
5571 } else {
5572 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5573 << Constructor->isImplicit()
5574 << S.Context.getTypeDeclType(Constructor->getParent())
5575 << /*member=*/1
5576 << Entity.getName();
5577 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5578
5579 if (const RecordType *Record
5580 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005582 diag::note_previous_decl)
5583 << S.Context.getTagDeclType(Record->getDecl());
5584 }
5585 break;
5586 }
5587
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005588 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5589 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005590 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005593 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005594 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005595 OverloadingResult Ovl
5596 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00005597 if (Ovl != OR_Deleted) {
5598 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5599 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005600 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00005601 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005602 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00005603
5604 // If this is a defaulted or implicitly-declared function, then
5605 // it was implicitly deleted. Make it clear that the deletion was
5606 // implicit.
5607 if (S.isImplicitlyDeleted(Best->Function)) {
5608 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
5609 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
5610 << DestType << ArgsRange;
5611
5612 diagnoseImplicitlyDeletedFunction(S,
5613 cast<CXXMethodDecl>(Best->Function));
5614 break;
5615 }
5616
5617 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5618 << true << DestType << ArgsRange;
5619 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5620 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005621 break;
5622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005624 case OR_Success:
5625 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005626 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005627 }
David Blaikie60deeee2012-01-17 08:24:58 +00005628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregor85dabae2009-12-16 01:38:02 +00005630 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005631 if (Entity.getKind() == InitializedEntity::EK_Member &&
5632 isa<CXXConstructorDecl>(S.CurContext)) {
5633 // This is implicit default-initialization of a const member in
5634 // a constructor. Complain that it needs to be explicitly
5635 // initialized.
5636 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5637 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5638 << Constructor->isImplicit()
5639 << S.Context.getTypeDeclType(Constructor->getParent())
5640 << /*const=*/1
5641 << Entity.getName();
5642 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5643 << Entity.getName();
5644 } else {
5645 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5646 << DestType << (bool)DestType->getAs<RecordType>();
5647 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005650 case FK_Incomplete:
5651 S.RequireCompleteType(Kind.getLocation(), DestType,
5652 diag::err_init_incomplete_type);
5653 break;
5654
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005655 case FK_ListInitializationFailed: {
5656 // Run the init list checker again to emit diagnostics.
5657 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5658 QualType DestType = Entity.getType();
5659 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005660 DestType, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005661 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005662 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005663 assert(DiagnoseInitList.HadError() &&
5664 "Inconsistent init list check result.");
5665 break;
5666 }
John McCall4124c492011-10-17 18:40:02 +00005667
5668 case FK_PlaceholderType: {
5669 // FIXME: Already diagnosed!
5670 break;
5671 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005672
5673 case FK_InitListElementCopyFailure: {
5674 // Try to perform all copies again.
5675 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5676 unsigned NumInits = InitList->getNumInits();
5677 QualType DestType = Entity.getType();
5678 QualType E;
5679 bool Success = S.isStdInitializerList(DestType, &E);
5680 (void)Success;
5681 assert(Success && "Where did the std::initializer_list go?");
5682 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5683 S.Context.getConstantArrayType(E,
5684 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5685 NumInits),
5686 ArrayType::Normal, 0));
5687 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5688 0, HiddenArray);
5689 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5690 // where the init list type is wrong, e.g.
5691 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5692 // FIXME: Emit a note if we hit the limit?
5693 int ErrorCount = 0;
5694 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5695 Element.setElementIndex(i);
5696 ExprResult Init = S.Owned(InitList->getInit(i));
5697 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5698 .isInvalid())
5699 ++ErrorCount;
5700 }
5701 break;
5702 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005705 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005706 return true;
5707}
Douglas Gregore1314a62009-12-18 05:02:21 +00005708
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005709void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005710 switch (SequenceKind) {
5711 case FailedSequence: {
5712 OS << "Failed sequence: ";
5713 switch (Failure) {
5714 case FK_TooManyInitsForReference:
5715 OS << "too many initializers for reference";
5716 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005718 case FK_ArrayNeedsInitList:
5719 OS << "array requires initializer list";
5720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005722 case FK_ArrayNeedsInitListOrStringLiteral:
5723 OS << "array requires initializer list or string literal";
5724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Douglas Gregore2f943b2011-02-22 18:29:51 +00005726 case FK_ArrayTypeMismatch:
5727 OS << "array type mismatch";
5728 break;
5729
5730 case FK_NonConstantArrayInit:
5731 OS << "non-constant array initializer";
5732 break;
5733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005734 case FK_AddressOfOverloadFailed:
5735 OS << "address of overloaded function failed";
5736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005738 case FK_ReferenceInitOverloadFailed:
5739 OS << "overload resolution for reference initialization failed";
5740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005742 case FK_NonConstLValueReferenceBindingToTemporary:
5743 OS << "non-const lvalue reference bound to temporary";
5744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005746 case FK_NonConstLValueReferenceBindingToUnrelated:
5747 OS << "non-const lvalue reference bound to unrelated type";
5748 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005750 case FK_RValueReferenceBindingToLValue:
5751 OS << "rvalue reference bound to an lvalue";
5752 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005754 case FK_ReferenceInitDropsQualifiers:
5755 OS << "reference initialization drops qualifiers";
5756 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005758 case FK_ReferenceInitFailed:
5759 OS << "reference initialization failed";
5760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005762 case FK_ConversionFailed:
5763 OS << "conversion failed";
5764 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
John Wiegley01296292011-04-08 18:41:53 +00005766 case FK_ConversionFromPropertyFailed:
5767 OS << "conversion from property failed";
5768 break;
5769
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005770 case FK_TooManyInitsForScalar:
5771 OS << "too many initializers for scalar";
5772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005774 case FK_ReferenceBindingToInitList:
5775 OS << "referencing binding to initializer list";
5776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005778 case FK_InitListBadDestinationType:
5779 OS << "initializer list for non-aggregate, non-scalar type";
5780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005782 case FK_UserConversionOverloadFailed:
5783 OS << "overloading failed for user-defined conversion";
5784 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005786 case FK_ConstructorOverloadFailed:
5787 OS << "constructor overloading failed";
5788 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005790 case FK_DefaultInitOfConst:
5791 OS << "default initialization of a const variable";
5792 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005793
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005794 case FK_Incomplete:
5795 OS << "initialization of incomplete type";
5796 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005797
5798 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005799 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005800 break;
5801
John McCalla59dc2f2012-01-05 00:13:19 +00005802 case FK_VariableLengthArrayHasInitializer:
5803 OS << "variable length array has an initializer";
5804 break;
5805
John McCall4124c492011-10-17 18:40:02 +00005806 case FK_PlaceholderType:
5807 OS << "initializer expression isn't contextually valid";
5808 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005809
5810 case FK_ListConstructorOverloadFailed:
5811 OS << "list constructor overloading failed";
5812 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005813
5814 case FK_InitListElementCopyFailure:
5815 OS << "copy construction of initializer list element failed";
5816 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005817 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005818 OS << '\n';
5819 return;
5820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005822 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005823 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005824 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005825
Sebastian Redld201edf2011-06-05 13:59:11 +00005826 case NormalSequence:
5827 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005828 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005831 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5832 if (S != step_begin()) {
5833 OS << " -> ";
5834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005835
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005836 switch (S->Kind) {
5837 case SK_ResolveAddressOfOverloadedFunction:
5838 OS << "resolve address of overloaded function";
5839 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005841 case SK_CastDerivedToBaseRValue:
5842 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5843 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005845 case SK_CastDerivedToBaseXValue:
5846 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5847 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005849 case SK_CastDerivedToBaseLValue:
5850 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005853 case SK_BindReference:
5854 OS << "bind reference to lvalue";
5855 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005857 case SK_BindReferenceToTemporary:
5858 OS << "bind reference to a temporary";
5859 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005860
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005861 case SK_ExtraneousCopyToTemporary:
5862 OS << "extraneous C++03 copy to temporary";
5863 break;
5864
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005865 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005866 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005867 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005868
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005869 case SK_QualificationConversionRValue:
5870 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005871 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005872
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005873 case SK_QualificationConversionXValue:
5874 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005875 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005876
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005877 case SK_QualificationConversionLValue:
5878 OS << "qualification conversion (lvalue)";
5879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005880
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005881 case SK_ConversionSequence:
5882 OS << "implicit conversion sequence (";
5883 S->ICS->DebugPrint(); // FIXME: use OS
5884 OS << ")";
5885 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005886
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005887 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005888 OS << "list aggregate initialization";
5889 break;
5890
5891 case SK_ListConstructorCall:
5892 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005893 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005894
Sebastian Redl29526f02011-11-27 16:50:07 +00005895 case SK_UnwrapInitList:
5896 OS << "unwrap reference initializer list";
5897 break;
5898
5899 case SK_RewrapInitList:
5900 OS << "rewrap reference initializer list";
5901 break;
5902
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005903 case SK_ConstructorInitialization:
5904 OS << "constructor initialization";
5905 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005907 case SK_ZeroInitialization:
5908 OS << "zero initialization";
5909 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005910
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005911 case SK_CAssignment:
5912 OS << "C assignment";
5913 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005914
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005915 case SK_StringInit:
5916 OS << "string initialization";
5917 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005918
5919 case SK_ObjCObjectConversion:
5920 OS << "Objective-C object conversion";
5921 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005922
5923 case SK_ArrayInit:
5924 OS << "array initialization";
5925 break;
John McCall31168b02011-06-15 23:02:42 +00005926
Richard Smithebeed412012-02-15 22:38:09 +00005927 case SK_ParenthesizedArrayInit:
5928 OS << "parenthesized array initialization";
5929 break;
5930
John McCall31168b02011-06-15 23:02:42 +00005931 case SK_PassByIndirectCopyRestore:
5932 OS << "pass by indirect copy and restore";
5933 break;
5934
5935 case SK_PassByIndirectRestore:
5936 OS << "pass by indirect restore";
5937 break;
5938
5939 case SK_ProduceObjCObject:
5940 OS << "Objective-C object retension";
5941 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005942
5943 case SK_StdInitializerList:
5944 OS << "std::initializer_list from initializer list";
5945 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005946 }
5947 }
5948}
5949
5950void InitializationSequence::dump() const {
5951 dump(llvm::errs());
5952}
5953
Richard Smith66e05fe2012-01-18 05:21:49 +00005954static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5955 QualType EntityType,
5956 const Expr *PreInit,
5957 const Expr *PostInit) {
5958 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5959 return;
5960
5961 // A narrowing conversion can only appear as the final implicit conversion in
5962 // an initialization sequence.
5963 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5964 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5965 return;
5966
5967 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5968 const StandardConversionSequence *SCS = 0;
5969 switch (ICS.getKind()) {
5970 case ImplicitConversionSequence::StandardConversion:
5971 SCS = &ICS.Standard;
5972 break;
5973 case ImplicitConversionSequence::UserDefinedConversion:
5974 SCS = &ICS.UserDefined.After;
5975 break;
5976 case ImplicitConversionSequence::AmbiguousConversion:
5977 case ImplicitConversionSequence::EllipsisConversion:
5978 case ImplicitConversionSequence::BadConversion:
5979 return;
5980 }
5981
5982 // Determine the type prior to the narrowing conversion. If a conversion
5983 // operator was used, this may be different from both the type of the entity
5984 // and of the pre-initialization expression.
5985 QualType PreNarrowingType = PreInit->getType();
5986 if (Seq.step_begin() + 1 != Seq.step_end())
5987 PreNarrowingType = Seq.step_end()[-2].Type;
5988
5989 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5990 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005991 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005992 case NK_Not_Narrowing:
5993 // No narrowing occurred.
5994 return;
5995
5996 case NK_Type_Narrowing:
5997 // This was a floating-to-integer conversion, which is always considered a
5998 // narrowing conversion even if the value is a constant and can be
5999 // represented exactly as an integer.
6000 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00006001 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
6002 diag::warn_init_list_type_narrowing
6003 : S.isSFINAEContext()?
6004 diag::err_init_list_type_narrowing_sfinae
6005 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006006 << PostInit->getSourceRange()
6007 << PreNarrowingType.getLocalUnqualifiedType()
6008 << EntityType.getLocalUnqualifiedType();
6009 break;
6010
6011 case NK_Constant_Narrowing:
6012 // A constant value was narrowed.
6013 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00006014 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
6015 diag::warn_init_list_constant_narrowing
6016 : S.isSFINAEContext()?
6017 diag::err_init_list_constant_narrowing_sfinae
6018 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006019 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00006020 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00006021 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00006022 break;
6023
6024 case NK_Variable_Narrowing:
6025 // A variable's value may have been narrowed.
6026 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00006027 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
6028 diag::warn_init_list_variable_narrowing
6029 : S.isSFINAEContext()?
6030 diag::err_init_list_variable_narrowing_sfinae
6031 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006032 << PostInit->getSourceRange()
6033 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00006034 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00006035 break;
6036 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006037
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006038 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006039 llvm::raw_svector_ostream OS(StaticCast);
6040 OS << "static_cast<";
6041 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6042 // It's important to use the typedef's name if there is one so that the
6043 // fixit doesn't break code using types like int64_t.
6044 //
6045 // FIXME: This will break if the typedef requires qualification. But
6046 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006047 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006048 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6049 OS << BT->getName(S.getLangOptions());
6050 else {
6051 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6052 // with a broken cast.
6053 return;
6054 }
6055 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00006056 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6057 << PostInit->getSourceRange()
6058 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006059 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00006060 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006061}
6062
Douglas Gregore1314a62009-12-18 05:02:21 +00006063//===----------------------------------------------------------------------===//
6064// Initialization helper functions
6065//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00006066bool
6067Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6068 ExprResult Init) {
6069 if (Init.isInvalid())
6070 return false;
6071
6072 Expr *InitE = Init.get();
6073 assert(InitE && "No initialization expression");
6074
6075 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6076 SourceLocation());
6077 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00006078 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00006079}
6080
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006081ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00006082Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6083 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006084 ExprResult Init,
6085 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006086 if (Init.isInvalid())
6087 return ExprError();
6088
John McCall1f425642010-11-11 03:21:53 +00006089 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00006090 assert(InitE && "No initialization expression?");
6091
6092 if (EqualLoc.isInvalid())
6093 EqualLoc = InitE->getLocStart();
6094
6095 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6096 EqualLoc);
6097 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6098 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006099
Richard Smith66e05fe2012-01-18 05:21:49 +00006100 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6101
6102 if (!Result.isInvalid() && TopLevelOfInitList)
6103 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6104 InitE, Result.get());
6105
6106 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00006107}