blob: 5caced9d69a215a9c4e7f36839d5415305d5f415 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner9ececce2009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000275
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor2bb07652009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCalldadc5752010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000346}
347
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351void
Douglas Gregor723796a2009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump11289f42009-09-09 15:08:12 +0000391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000409 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCalldadc5752010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redld201edf2011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000471
Douglas Gregor723796a2009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000477
Eli Friedman23a9e312008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000485
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Anders Carlsson6cabf312010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000533 else
David Blaikie83d382b2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000535
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000552
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000565
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000589 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000590 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000591}
592
Anders Carlsson6cabf312010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613
Eli Friedman85f54972008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000632 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman425038c2009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000655
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 }
659 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000660
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 } else if (DeclType->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000731 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000732 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000736 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson6cabf312010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000758 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000766
John McCall5decec92011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
John McCall5decec92011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000778 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 }
John McCall5decec92011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000801
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 }
John McCall5decec92011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley01296292011-04-08 18:41:53 +0000836 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCall5decec92011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000863}
864
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000917 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 }
John McCall643169b2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCall643169b2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
John McCall643169b2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001027}
1028
Anders Carlsson6cabf312010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001038
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall6a16b2f2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
John McCall6a16b2f2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001073 }
1074 }
John McCall6a16b2f2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
John McCall6a16b2f2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001092 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
John McCall6a16b2f2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
John McCall6a16b2f2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
John McCall6a16b2f2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall6a16b2f2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
1143
Anders Carlsson6cabf312010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCall66884dd2011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCall66884dd2011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001233 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001270}
1271
Eli Friedman3fa64df2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson6cabf312010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001321
Eli Friedman23a9e312008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump11289f42009-09-09 15:08:12 +00001327 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001363
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregora9add4e2009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregora9add4e2009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor51695702009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001396 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001397 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001398
Douglas Gregora82064c2011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001418
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001425 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001426
John McCalle40b58e2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 return;
1457
Eli Friedman3fa64df2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474}
Steve Narofff8ecff22008-05-01 22:18:59 +00001475
Douglas Gregord5846a12009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregord5846a12009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506}
Mike Stump11289f42009-09-09 15:08:12 +00001507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
1514 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1515 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1516 return IF;
1517 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001518 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001519 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001520}
1521
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1529 DIE->size(), IndexExprs.data(),
1530 NumIndexExprs, DIE->getEqualOrColonLoc(),
1531 DIE->usesGNUSyntax(), DIE->getInit());
1532}
1533
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001534namespace {
1535
1536// Callback to only accept typo corrections that are for field members of
1537// the given struct or union.
1538class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1539 public:
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1541 : Record(RD) {}
1542
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1546 }
1547
1548 private:
1549 RecordDecl *Record;
1550};
1551
1552}
1553
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001554/// @brief Check the well-formedness of a C99 designated initializer.
1555///
1556/// Determines whether the designated initializer @p DIE, which
1557/// resides at the given @p Index within the initializer list @p
1558/// IList, is well-formed for a current object of type @p DeclType
1559/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001560/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001562///
1563/// @param IList The initializer list in which this designated
1564/// initializer occurs.
1565///
Douglas Gregora5324162009-04-15 04:56:10 +00001566/// @param DIE The designated initializer expression.
1567///
1568/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001569///
1570/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1571/// into which the designation in @p DIE should refer.
1572///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573/// @param NextField If non-NULL and the first designator in @p DIE is
1574/// a field, this will be set to the field declaration corresponding
1575/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001576///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577/// @param NextElementIndex If non-NULL and the first designator in @p
1578/// DIE is an array designator or GNU array-range designator, this
1579/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001580///
1581/// @param Index Index into @p IList where the designated initializer
1582/// @p DIE occurs.
1583///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001584/// @param StructuredList The initializer list expression that
1585/// describes all of the subobject initializers in the order they'll
1586/// actually be initialized.
1587///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001588/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001589bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001590InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001591 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001592 DesignatedInitExpr *DIE,
1593 unsigned DesigIdx,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1597 unsigned &Index,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001602 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001605
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1611
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001614
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1620
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001622 }
1623
Douglas Gregora5324162009-04-15 04:56:10 +00001624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001625 bool IsFirstDesignator = (DesigIdx == 0);
1626 if (!VerifyOnly) {
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1629
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
1632 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1638 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 if (D->isFieldDesignator()) {
1641 // C99 6.7.8p7:
1642 //
1643 // If a designator has the form
1644 //
1645 // . identifier
1646 //
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001649 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651 if (!RT) {
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655 if (!VerifyOnly)
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1657 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 ++Index;
1659 return true;
1660 }
1661
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001665 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001668 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1673 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
1679 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001680 // In verify mode, don't modify the original.
1681 if (VerifyOnly)
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1685 break;
1686 }
1687 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001688 if (KnownField && KnownField == *Field)
1689 break;
1690 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 break;
1692
1693 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 }
1695
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001697 if (VerifyOnly) {
1698 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001700 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001701
Douglas Gregord5846a12009-04-15 06:41:24 +00001702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001706 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001712 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001716 RT->getDecl());
1717 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001718 std::string CorrectedStr(
1719 Corrected.getAsString(SemaRef.getLangOptions()));
1720 std::string CorrectedQuotedStr(
1721 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001724 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001728 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001729 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001730 } else {
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1733 ++Index;
1734 return true;
1735 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001738 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001744 ++Index;
1745 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001746 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001748 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1751 FieldIndex = 0;
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1755 continue;
1756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001758 Field->getIdentifier() == ReplacementField->getIdentifier())
1759 break;
1760
1761 ++FieldIndex;
1762 }
1763 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001764 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001768 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001770 if (!VerifyOnly)
1771 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001772 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773
Douglas Gregora82064c2011-06-29 21:51:31 +00001774 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001775 bool InvalidUse;
1776 if (VerifyOnly)
1777 InvalidUse = !SemaRef.CanUseDecl(*Field);
1778 else
1779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1780 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001781 ++Index;
1782 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001784
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001785 if (!VerifyOnly) {
1786 // Update the designator with the field declaration.
1787 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1793 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001798 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001801 if (!VerifyOnly) {
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1809 << *Field;
1810 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001811 Invalid = true;
1812 }
1813
Chris Lattner001b29c2010-10-10 17:49:49 +00001814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001816 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 if (!VerifyOnly) {
1818 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1822 << *Field;
1823 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001824 Invalid = true;
1825 }
1826
Eli Friedman3fa64df2011-08-23 22:24:57 +00001827 // Check GNU flexible array initializer.
1828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1829 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001830 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831
1832 if (Invalid) {
1833 ++Index;
1834 return true;
1835 }
1836
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842
1843 InitializedEntity MemberEntity =
1844 InitializedEntity::InitializeMember(*Field, &Entity);
1845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001847
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1850 ++Field;
1851 ++FieldIndex;
1852 if (NextField)
1853 *NextField = Field;
1854 StructuredIndex = FieldIndex;
1855 return true;
1856 }
1857 } else {
1858 // Recurse to check later designated subobjects.
1859 QualType FieldType = (*Field)->getType();
1860 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001862 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001863 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001866 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001867 true, false))
1868 return true;
1869 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001870
1871 // Find the position of the next field to be initialized in this
1872 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001875
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1879 if (NextField)
1880 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001882 return false;
1883 }
1884
Douglas Gregor17bd0942009-01-28 23:36:17 +00001885 if (!FinishSubobjectInit)
1886 return false;
1887
Douglas Gregord5846a12009-04-15 06:41:24 +00001888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1890 return hadError;
1891
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Anders Carlsson6cabf312010-01-23 23:23:01 +00001895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001897 return hadError && !prevHadError;
1898 }
1899
1900 // C99 6.7.8p6:
1901 //
1902 // If a designator has the form
1903 //
1904 // [ constant-expression ]
1905 //
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1910 //
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1913 //
1914 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001917 if (!VerifyOnly)
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001920 ++Index;
1921 return true;
1922 }
1923
1924 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001929 DesignatedEndIndex = DesignatedStartIndex;
1930 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001935 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001937 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001938
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001946 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 }
1948
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001954 DesignatedEndIndex
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001958 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001963 ++Index;
1964 return true;
1965 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 } else {
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001969 DesignatedEndIndex
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001981 if (!VerifyOnly &&
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001983 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001985
Douglas Gregor17bd0942009-01-28 23:36:17 +00001986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001988
Douglas Gregor17bd0942009-01-28 23:36:17 +00001989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001995
Douglas Gregor17bd0942009-01-28 23:36:17 +00001996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
1999 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002001 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002004 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002005 (DesignatedStartIndex == DesignatedEndIndex),
2006 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002007 return true;
2008
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2012 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002013
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002018 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002019 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002020 return false;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor17bd0942009-01-28 23:36:17 +00002023 if (!FinishSubobjectInit)
2024 return false;
2025
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002026 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002029 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002031 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002032}
2033
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002034// Get the structured initializer list for a subobject of type
2035// @p CurrentObjectType.
2036InitListExpr *
2037InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002042 if (VerifyOnly)
2043 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
2046 ExistingInit = SyntacticToSemantic[IList];
2047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2051 return Result;
2052
2053 if (ExistingInit) {
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002058 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002061 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002065 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002066 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002068 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002070 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002071 << ExistingInit->getSourceRange();
2072 }
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2076 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002077 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002078
Douglas Gregora8a089b2010-07-13 18:40:04 +00002079 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002080
Douglas Gregor6d00c992009-03-20 23:58:33 +00002081 // Pre-allocate storage for the structured initializer list.
2082 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002083 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002084 bool GotNumInits = false;
2085 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002086 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002087 GotNumInits = true;
2088 } else if (Index < IList->getNumInits()) {
2089 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002090 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002091 GotNumInits = true;
2092 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002093 }
2094
Mike Stump11289f42009-09-09 15:08:12 +00002095 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002096 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2097 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2098 NumElements = CAType->getSize().getZExtValue();
2099 // Simple heuristic so that we don't allocate a very large
2100 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002101 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002102 NumElements = 0;
2103 }
John McCall9dd450b2009-09-21 23:43:11 +00002104 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002106 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002107 RecordDecl *RDecl = RType->getDecl();
2108 if (RDecl->isUnion())
2109 NumElements = 1;
2110 else
Mike Stump11289f42009-09-09 15:08:12 +00002111 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002112 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002113 }
2114
Ted Kremenekac034612010-04-13 23:39:13 +00002115 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002116
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 // Link this new initializer list into the structured initializer
2118 // lists.
2119 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002120 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 else {
2122 Result->setSyntacticForm(IList);
2123 SyntacticToSemantic[IList] = Result;
2124 }
2125
2126 return Result;
2127}
2128
2129/// Update the initializer at index @p StructuredIndex within the
2130/// structured initializer list to the value @p expr.
2131void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2132 unsigned &StructuredIndex,
2133 Expr *expr) {
2134 // No structured initializer list to update
2135 if (!StructuredList)
2136 return;
2137
Ted Kremenekac034612010-04-13 23:39:13 +00002138 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2139 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002141 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002142 diag::warn_initializer_overrides)
2143 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002144 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002146 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002147 << PrevInit->getSourceRange();
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002150 ++StructuredIndex;
2151}
2152
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002153/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002154/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002155/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002156/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002157/// failure. Returns the index expression, possibly with an implicit cast
2158/// added, on success. If everything went okay, Value will receive the
2159/// value of the constant expression.
2160static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002161CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162 SourceLocation Loc = Index->getSourceRange().getBegin();
2163
2164 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002165 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2166 if (Result.isInvalid())
2167 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002169 if (Value.isSigned() && Value.isNegative())
2170 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 << Value.toString(10) << Index->getSourceRange();
2172
Douglas Gregor51650d32009-01-23 21:04:18 +00002173 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002174 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175}
2176
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002178 SourceLocation Loc,
2179 bool GNUSyntax,
2180 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181 typedef DesignatedInitExpr::Designator ASTDesignator;
2182
2183 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002184 SmallVector<ASTDesignator, 32> Designators;
2185 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002186
2187 // Build designators and check array designator expressions.
2188 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2189 const Designator &D = Desig.getDesignator(Idx);
2190 switch (D.getKind()) {
2191 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002192 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002193 D.getFieldLoc()));
2194 break;
2195
2196 case Designator::ArrayDesignator: {
2197 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2198 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002199 if (!Index->isTypeDependent() && !Index->isValueDependent())
2200 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2201 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202 Invalid = true;
2203 else {
2204 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002205 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002206 D.getRBracketLoc()));
2207 InitExpressions.push_back(Index);
2208 }
2209 break;
2210 }
2211
2212 case Designator::ArrayRangeDesignator: {
2213 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2214 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2215 llvm::APSInt StartValue;
2216 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002217 bool StartDependent = StartIndex->isTypeDependent() ||
2218 StartIndex->isValueDependent();
2219 bool EndDependent = EndIndex->isTypeDependent() ||
2220 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002221 if (!StartDependent)
2222 StartIndex =
2223 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2224 if (!EndDependent)
2225 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2226
2227 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002228 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else {
2230 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002231 if (StartDependent || EndDependent) {
2232 // Nothing to compute.
2233 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002234 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002236 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002237
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002238 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002239 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002240 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002241 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2242 Invalid = true;
2243 } else {
2244 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002245 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002246 D.getEllipsisLoc(),
2247 D.getRBracketLoc()));
2248 InitExpressions.push_back(StartIndex);
2249 InitExpressions.push_back(EndIndex);
2250 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002251 }
2252 break;
2253 }
2254 }
2255 }
2256
2257 if (Invalid || Init.isInvalid())
2258 return ExprError();
2259
2260 // Clear out the expressions within the designation.
2261 Desig.ClearExprs(*this);
2262
2263 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002264 = DesignatedInitExpr::Create(Context,
2265 Designators.data(), Designators.size(),
2266 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002267 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
Richard Smithe4345902011-12-29 21:57:33 +00002269 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002270 Diag(DIE->getLocStart(), diag::ext_designated_init)
2271 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002273 return Owned(DIE);
2274}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276//===----------------------------------------------------------------------===//
2277// Initialization entity
2278//===----------------------------------------------------------------------===//
2279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002281 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002283{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002284 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2285 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002286 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002287 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002288 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002289 Type = VT->getElementType();
2290 } else {
2291 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2292 assert(CT && "Unexpected type");
2293 Kind = EK_ComplexElement;
2294 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002295 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002296}
2297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002299 CXXBaseSpecifier *Base,
2300 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002301{
2302 InitializedEntity Result;
2303 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002304 Result.Base = reinterpret_cast<uintptr_t>(Base);
2305 if (IsInheritedVirtualBase)
2306 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor1b303932009-12-22 15:35:07 +00002308 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 return Result;
2310}
2311
Douglas Gregor85dabae2009-12-16 01:38:02 +00002312DeclarationName InitializedEntity::getName() const {
2313 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002314 case EK_Parameter: {
2315 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2316 return (D ? D->getDeclName() : DeclarationName());
2317 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002318
2319 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Member:
2321 return VariableOrMember->getDeclName();
2322
2323 case EK_Result:
2324 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002325 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002326 case EK_Temporary:
2327 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002328 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002329 case EK_ArrayElement:
2330 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002331 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002332 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002333 return DeclarationName();
2334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335
David Blaikie8a40f702012-01-17 06:56:22 +00002336 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337}
2338
Douglas Gregora4b592a2009-12-19 03:01:41 +00002339DeclaratorDecl *InitializedEntity::getDecl() const {
2340 switch (getKind()) {
2341 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002342 case EK_Member:
2343 return VariableOrMember;
2344
John McCall31168b02011-06-15 23:02:42 +00002345 case EK_Parameter:
2346 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2347
Douglas Gregora4b592a2009-12-19 03:01:41 +00002348 case EK_Result:
2349 case EK_Exception:
2350 case EK_New:
2351 case EK_Temporary:
2352 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002353 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002354 case EK_ArrayElement:
2355 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002356 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002357 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002358 return 0;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie8a40f702012-01-17 06:56:22 +00002361 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002362}
2363
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002364bool InitializedEntity::allowsNRVO() const {
2365 switch (getKind()) {
2366 case EK_Result:
2367 case EK_Exception:
2368 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002370 case EK_Variable:
2371 case EK_Parameter:
2372 case EK_Member:
2373 case EK_New:
2374 case EK_Temporary:
2375 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002376 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 case EK_ArrayElement:
2378 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002379 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002380 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002381 break;
2382 }
2383
2384 return false;
2385}
2386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002387//===----------------------------------------------------------------------===//
2388// Initialization sequence
2389//===----------------------------------------------------------------------===//
2390
2391void InitializationSequence::Step::Destroy() {
2392 switch (Kind) {
2393 case SK_ResolveAddressOfOverloadedFunction:
2394 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002395 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_CastDerivedToBaseLValue:
2397 case SK_BindReference:
2398 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002399 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 case SK_UserConversion:
2401 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002402 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002404 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002405 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002406 case SK_UnwrapInitList:
2407 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002408 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002409 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002410 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002411 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002412 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002413 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002414 case SK_PassByIndirectCopyRestore:
2415 case SK_PassByIndirectRestore:
2416 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002417 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 case SK_ConversionSequence:
2421 delete ICS;
2422 }
2423}
2424
Douglas Gregor838fcc32010-03-26 20:14:36 +00002425bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002426 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002427}
2428
2429bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002430 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433 switch (getFailureKind()) {
2434 case FK_TooManyInitsForReference:
2435 case FK_ArrayNeedsInitList:
2436 case FK_ArrayNeedsInitListOrStringLiteral:
2437 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2438 case FK_NonConstLValueReferenceBindingToTemporary:
2439 case FK_NonConstLValueReferenceBindingToUnrelated:
2440 case FK_RValueReferenceBindingToLValue:
2441 case FK_ReferenceInitDropsQualifiers:
2442 case FK_ReferenceInitFailed:
2443 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002444 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002445 case FK_TooManyInitsForScalar:
2446 case FK_ReferenceBindingToInitList:
2447 case FK_InitListBadDestinationType:
2448 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002449 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002450 case FK_ArrayTypeMismatch:
2451 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002452 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002453 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002454 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002455 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregor838fcc32010-03-26 20:14:36 +00002458 case FK_ReferenceInitOverloadFailed:
2459 case FK_UserConversionOverloadFailed:
2460 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002461 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002462 return FailedOverloadResult == OR_Ambiguous;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
David Blaikie8a40f702012-01-17 06:56:22 +00002465 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002466}
2467
Douglas Gregorb33eed02010-04-16 22:09:46 +00002468bool InitializationSequence::isConstructorInitialization() const {
2469 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2470}
2471
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002472void
2473InitializationSequence
2474::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2475 DeclAccessPair Found,
2476 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Step S;
2478 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2479 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002480 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002481 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002482 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 Steps.push_back(S);
2484}
2485
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002487 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002489 switch (VK) {
2490 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2491 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2492 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 S.Type = BaseType;
2495 Steps.push_back(S);
2496}
2497
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 bool BindingTemporary) {
2500 Step S;
2501 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2502 S.Type = T;
2503 Steps.push_back(S);
2504}
2505
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002506void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2507 Step S;
2508 S.Kind = SK_ExtraneousCopyToTemporary;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002513void
2514InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2515 DeclAccessPair FoundDecl,
2516 QualType T,
2517 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 Step S;
2519 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002520 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002521 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002522 S.Function.Function = Function;
2523 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 Steps.push_back(S);
2525}
2526
2527void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002528 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002530 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002531 switch (VK) {
2532 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002533 S.Kind = SK_QualificationConversionRValue;
2534 break;
John McCall2536c6d2010-08-25 10:28:54 +00002535 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002536 S.Kind = SK_QualificationConversionXValue;
2537 break;
John McCall2536c6d2010-08-25 10:28:54 +00002538 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 S.Kind = SK_QualificationConversionLValue;
2540 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 S.Type = Ty;
2543 Steps.push_back(S);
2544}
2545
2546void InitializationSequence::AddConversionSequenceStep(
2547 const ImplicitConversionSequence &ICS,
2548 QualType T) {
2549 Step S;
2550 S.Kind = SK_ConversionSequence;
2551 S.Type = T;
2552 S.ICS = new ImplicitConversionSequence(ICS);
2553 Steps.push_back(S);
2554}
2555
Douglas Gregor51e77d52009-12-10 17:56:55 +00002556void InitializationSequence::AddListInitializationStep(QualType T) {
2557 Step S;
2558 S.Kind = SK_ListInitialization;
2559 S.Type = T;
2560 Steps.push_back(S);
2561}
2562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002564InitializationSequence
2565::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2566 AccessSpecifier Access,
2567 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002568 bool HadMultipleCandidates,
2569 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002570 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002571 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002572 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002573 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002574 S.Function.Function = Constructor;
2575 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002576 Steps.push_back(S);
2577}
2578
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002579void InitializationSequence::AddZeroInitializationStep(QualType T) {
2580 Step S;
2581 S.Kind = SK_ZeroInitialization;
2582 S.Type = T;
2583 Steps.push_back(S);
2584}
2585
Douglas Gregore1314a62009-12-18 05:02:21 +00002586void InitializationSequence::AddCAssignmentStep(QualType T) {
2587 Step S;
2588 S.Kind = SK_CAssignment;
2589 S.Type = T;
2590 Steps.push_back(S);
2591}
2592
Eli Friedman78275202009-12-19 08:11:05 +00002593void InitializationSequence::AddStringInitStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_StringInit;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002600void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_ObjCObjectConversion;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Douglas Gregore2f943b2011-02-22 18:29:51 +00002607void InitializationSequence::AddArrayInitStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_ArrayInit;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
John McCall31168b02011-06-15 23:02:42 +00002614void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2615 bool shouldCopy) {
2616 Step s;
2617 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2618 : SK_PassByIndirectRestore);
2619 s.Type = type;
2620 Steps.push_back(s);
2621}
2622
2623void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2624 Step S;
2625 S.Kind = SK_ProduceObjCObject;
2626 S.Type = T;
2627 Steps.push_back(S);
2628}
2629
Sebastian Redlc1839b12012-01-17 22:49:42 +00002630void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2631 Step S;
2632 S.Kind = SK_StdInitializerList;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Sebastian Redl29526f02011-11-27 16:50:07 +00002637void InitializationSequence::RewrapReferenceInitList(QualType T,
2638 InitListExpr *Syntactic) {
2639 assert(Syntactic->getNumInits() == 1 &&
2640 "Can only rewrap trivial init lists.");
2641 Step S;
2642 S.Kind = SK_UnwrapInitList;
2643 S.Type = Syntactic->getInit(0)->getType();
2644 Steps.insert(Steps.begin(), S);
2645
2646 S.Kind = SK_RewrapInitList;
2647 S.Type = T;
2648 S.WrappingSyntacticList = Syntactic;
2649 Steps.push_back(S);
2650}
2651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002654 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002655 this->Failure = Failure;
2656 this->FailedOverloadResult = Result;
2657}
2658
2659//===----------------------------------------------------------------------===//
2660// Attempt initialization
2661//===----------------------------------------------------------------------===//
2662
John McCall31168b02011-06-15 23:02:42 +00002663static void MaybeProduceObjCObject(Sema &S,
2664 InitializationSequence &Sequence,
2665 const InitializedEntity &Entity) {
2666 if (!S.getLangOptions().ObjCAutoRefCount) return;
2667
2668 /// When initializing a parameter, produce the value if it's marked
2669 /// __attribute__((ns_consumed)).
2670 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2671 if (!Entity.isParameterConsumed())
2672 return;
2673
2674 assert(Entity.getType()->isObjCRetainableType() &&
2675 "consuming an object of unretainable type?");
2676 Sequence.AddProduceObjCObjectStep(Entity.getType());
2677
2678 /// When initializing a return value, if the return type is a
2679 /// retainable type, then returns need to immediately retain the
2680 /// object. If an autorelease is required, it will be done at the
2681 /// last instant.
2682 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2683 if (!Entity.getType()->isObjCRetainableType())
2684 return;
2685
2686 Sequence.AddProduceObjCObjectStep(Entity.getType());
2687 }
2688}
2689
Sebastian Redled2e5322011-12-22 14:44:04 +00002690/// \brief When initializing from init list via constructor, deal with the
2691/// empty init list and std::initializer_list special cases.
2692///
2693/// \return True if this was a special case, false otherwise.
2694static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002695 InitListExpr *List,
Sebastian Redled2e5322011-12-22 14:44:04 +00002696 CXXRecordDecl *DestRecordDecl,
2697 QualType DestType,
2698 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002699 // C++11 [dcl.init.list]p3:
Sebastian Redled2e5322011-12-22 14:44:04 +00002700 // List-initialization of an object of type T is defined as follows:
2701 // - If the initializer list has no elements and T is a class type with
2702 // a default constructor, the object is value-initialized.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002703 if (List->getNumInits() == 0) {
Sebastian Redled2e5322011-12-22 14:44:04 +00002704 if (CXXConstructorDecl *DefaultConstructor =
2705 S.LookupDefaultConstructor(DestRecordDecl)) {
2706 if (DefaultConstructor->isDeleted() ||
2707 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2708 // Fake an overload resolution failure.
2709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2710 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2711 DefaultConstructor->getAccess());
2712 if (FunctionTemplateDecl *ConstructorTmpl =
2713 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2714 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2715 /*ExplicitArgs*/ 0,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002716 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002717 /*SuppressUserConversions*/ false);
2718 else
2719 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002720 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002721 /*SuppressUserConversions*/ false);
2722 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002723 InitializationSequence::FK_ListConstructorOverloadFailed,
2724 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002725 } else
2726 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2727 DefaultConstructor->getAccess(),
2728 DestType,
2729 /*MultipleCandidates=*/false,
2730 /*FromInitList=*/true);
2731 return true;
2732 }
2733 }
2734
2735 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002736 QualType E;
2737 if (S.isStdInitializerList(DestType, &E)) {
2738 // Check that each individual element can be copy-constructed. But since we
2739 // have no place to store further information, we'll recalculate everything
2740 // later.
2741 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2742 S.Context.getConstantArrayType(E,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002743 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2744 List->getNumInits()),
Sebastian Redlc1839b12012-01-17 22:49:42 +00002745 ArrayType::Normal, 0));
2746 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2747 0, HiddenArray);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002748 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002749 Element.setElementIndex(i);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002750 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002751 Sequence.SetFailed(
2752 InitializationSequence::FK_InitListElementCopyFailure);
2753 return true;
2754 }
2755 }
2756 Sequence.AddStdInitializerListConstructionStep(DestType);
2757 return true;
2758 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002759
2760 // Not a special case.
2761 return false;
2762}
2763
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002764static OverloadingResult
2765ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2766 Expr **Args, unsigned NumArgs,
2767 OverloadCandidateSet &CandidateSet,
2768 DeclContext::lookup_iterator Con,
2769 DeclContext::lookup_iterator ConEnd,
2770 OverloadCandidateSet::iterator &Best,
2771 bool CopyInitializing, bool AllowExplicit,
2772 bool OnlyListConstructors) {
2773 CandidateSet.clear();
2774
2775 for (; Con != ConEnd; ++Con) {
2776 NamedDecl *D = *Con;
2777 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2778 bool SuppressUserConversions = false;
2779
2780 // Find the constructor (which may be a template).
2781 CXXConstructorDecl *Constructor = 0;
2782 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2783 if (ConstructorTmpl)
2784 Constructor = cast<CXXConstructorDecl>(
2785 ConstructorTmpl->getTemplatedDecl());
2786 else {
2787 Constructor = cast<CXXConstructorDecl>(D);
2788
2789 // If we're performing copy initialization using a copy constructor, we
2790 // suppress user-defined conversions on the arguments.
2791 // FIXME: Move constructors?
2792 if (CopyInitializing && Constructor->isCopyConstructor())
2793 SuppressUserConversions = true;
2794 }
2795
2796 if (!Constructor->isInvalidDecl() &&
2797 (AllowExplicit || !Constructor->isExplicit()) &&
2798 (!OnlyListConstructors || !S.isInitListConstructor(Constructor))) {
2799 if (ConstructorTmpl)
2800 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2801 /*ExplicitArgs*/ 0,
2802 Args, NumArgs, CandidateSet,
2803 SuppressUserConversions);
2804 else
2805 S.AddOverloadCandidate(Constructor, FoundDecl,
2806 Args, NumArgs, CandidateSet,
2807 SuppressUserConversions);
2808 }
2809 }
2810
2811 // Perform overload resolution and return the result.
2812 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2813}
2814
Sebastian Redled2e5322011-12-22 14:44:04 +00002815/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2816/// enumerates the constructors of the initialized entity and performs overload
2817/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002818/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002819/// class type.
2820static void TryConstructorInitialization(Sema &S,
2821 const InitializedEntity &Entity,
2822 const InitializationKind &Kind,
2823 Expr **Args, unsigned NumArgs,
2824 QualType DestType,
2825 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002826 bool InitListSyntax = false) {
2827 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2828 "InitListSyntax must come with a single initializer list argument.");
2829
Sebastian Redled2e5322011-12-22 14:44:04 +00002830 // Check constructor arguments for self reference.
2831 if (DeclaratorDecl *DD = Entity.getDecl())
2832 // Parameters arguments are occassionially constructed with itself,
2833 // for instance, in recursive functions. Skip them.
2834 if (!isa<ParmVarDecl>(DD))
2835 for (unsigned i = 0; i < NumArgs; ++i)
2836 S.CheckSelfReference(DD, Args[i]);
2837
Sebastian Redled2e5322011-12-22 14:44:04 +00002838 // The type we're constructing needs to be complete.
2839 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2840 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002841 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00002842 }
2843
2844 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2845 assert(DestRecordType && "Constructor initialization requires record type");
2846 CXXRecordDecl *DestRecordDecl
2847 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2848
Sebastian Redl88e4d492012-02-04 21:27:33 +00002849 if (InitListSyntax &&
2850 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2851 DestRecordDecl, DestType, Sequence))
Sebastian Redled2e5322011-12-22 14:44:04 +00002852 return;
2853
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002854 // Build the candidate set directly in the initialization sequence
2855 // structure, so that it will persist if we fail.
2856 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2857
2858 // Determine whether we are allowed to call explicit constructors or
2859 // explicit conversion operators.
2860 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2861 Kind.getKind() == InitializationKind::IK_Value ||
2862 Kind.getKind() == InitializationKind::IK_Default);
2863
Sebastian Redl88e4d492012-02-04 21:27:33 +00002864 if (InitListSyntax) {
2865 // Time to unwrap the init list.
2866 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2867 Args = ILE->getInits();
2868 NumArgs = ILE->getNumInits();
2869 }
2870
Sebastian Redled2e5322011-12-22 14:44:04 +00002871 // - Otherwise, if T is a class type, constructors are considered. The
2872 // applicable constructors are enumerated, and the best one is chosen
2873 // through overload resolution.
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002874 DeclContext::lookup_iterator ConStart, ConEnd;
2875 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00002876
Sebastian Redled2e5322011-12-22 14:44:04 +00002877 OverloadCandidateSet::iterator Best;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002878 if (OverloadingResult Result =
2879 ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2880 CandidateSet, ConStart, ConEnd, Best,
2881 Kind.getKind() == InitializationKind::IK_Copy,
2882 AllowExplicit,
2883 /*OnlyListConstructors=*/false)) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002884 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002885 InitializationSequence::FK_ListConstructorOverloadFailed :
2886 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002887 Result);
2888 return;
2889 }
2890
2891 // C++0x [dcl.init]p6:
2892 // If a program calls for the default initialization of an object
2893 // of a const-qualified type T, T shall be a class type with a
2894 // user-provided default constructor.
2895 if (Kind.getKind() == InitializationKind::IK_Default &&
2896 Entity.getType().isConstQualified() &&
2897 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2898 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2899 return;
2900 }
2901
2902 // Add the constructor initialization step. Any cv-qualification conversion is
2903 // subsumed by the initialization.
2904 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2905 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2906 Sequence.AddConstructorInitializationStep(CtorDecl,
2907 Best->FoundDecl.getAccess(),
2908 DestType, HadMultipleCandidates,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002909 InitListSyntax);
Sebastian Redled2e5322011-12-22 14:44:04 +00002910}
2911
Sebastian Redl29526f02011-11-27 16:50:07 +00002912static bool
2913ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2914 Expr *Initializer,
2915 QualType &SourceType,
2916 QualType &UnqualifiedSourceType,
2917 QualType UnqualifiedTargetType,
2918 InitializationSequence &Sequence) {
2919 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2920 S.Context.OverloadTy) {
2921 DeclAccessPair Found;
2922 bool HadMultipleCandidates = false;
2923 if (FunctionDecl *Fn
2924 = S.ResolveAddressOfOverloadedFunction(Initializer,
2925 UnqualifiedTargetType,
2926 false, Found,
2927 &HadMultipleCandidates)) {
2928 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2929 HadMultipleCandidates);
2930 SourceType = Fn->getType();
2931 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2932 } else if (!UnqualifiedTargetType->isRecordType()) {
2933 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2934 return true;
2935 }
2936 }
2937 return false;
2938}
2939
2940static void TryReferenceInitializationCore(Sema &S,
2941 const InitializedEntity &Entity,
2942 const InitializationKind &Kind,
2943 Expr *Initializer,
2944 QualType cv1T1, QualType T1,
2945 Qualifiers T1Quals,
2946 QualType cv2T2, QualType T2,
2947 Qualifiers T2Quals,
2948 InitializationSequence &Sequence);
2949
2950static void TryListInitialization(Sema &S,
2951 const InitializedEntity &Entity,
2952 const InitializationKind &Kind,
2953 InitListExpr *InitList,
2954 InitializationSequence &Sequence);
2955
2956/// \brief Attempt list initialization of a reference.
2957static void TryReferenceListInitialization(Sema &S,
2958 const InitializedEntity &Entity,
2959 const InitializationKind &Kind,
2960 InitListExpr *InitList,
2961 InitializationSequence &Sequence)
2962{
2963 // First, catch C++03 where this isn't possible.
2964 if (!S.getLangOptions().CPlusPlus0x) {
2965 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2966 return;
2967 }
2968
2969 QualType DestType = Entity.getType();
2970 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2971 Qualifiers T1Quals;
2972 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2973
2974 // Reference initialization via an initializer list works thus:
2975 // If the initializer list consists of a single element that is
2976 // reference-related to the referenced type, bind directly to that element
2977 // (possibly creating temporaries).
2978 // Otherwise, initialize a temporary with the initializer list and
2979 // bind to that.
2980 if (InitList->getNumInits() == 1) {
2981 Expr *Initializer = InitList->getInit(0);
2982 QualType cv2T2 = Initializer->getType();
2983 Qualifiers T2Quals;
2984 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2985
2986 // If this fails, creating a temporary wouldn't work either.
2987 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
2988 T1, Sequence))
2989 return;
2990
2991 SourceLocation DeclLoc = Initializer->getLocStart();
2992 bool dummy1, dummy2, dummy3;
2993 Sema::ReferenceCompareResult RefRelationship
2994 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
2995 dummy2, dummy3);
2996 if (RefRelationship >= Sema::Ref_Related) {
2997 // Try to bind the reference here.
2998 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
2999 T1Quals, cv2T2, T2, T2Quals, Sequence);
3000 if (Sequence)
3001 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3002 return;
3003 }
3004 }
3005
3006 // Not reference-related. Create a temporary and bind to that.
3007 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3008
3009 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3010 if (Sequence) {
3011 if (DestType->isRValueReferenceType() ||
3012 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3013 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3014 else
3015 Sequence.SetFailed(
3016 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3017 }
3018}
3019
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003020/// \brief Attempt list initialization (C++0x [dcl.init.list])
3021static void TryListInitialization(Sema &S,
3022 const InitializedEntity &Entity,
3023 const InitializationKind &Kind,
3024 InitListExpr *InitList,
3025 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003026 QualType DestType = Entity.getType();
3027
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003028 // C++ doesn't allow scalar initialization with more than one argument.
3029 // But C99 complex numbers are scalars and it makes sense there.
3030 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3031 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3032 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3033 return;
3034 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003035 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003036 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003037 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003038 }
3039 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003040 if (S.getLangOptions().CPlusPlus0x) {
3041 Expr *Arg = InitList;
3042 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3043 Sequence, /*InitListSyntax=*/true);
3044 } else
Sebastian Redled2e5322011-12-22 14:44:04 +00003045 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003046 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003047 }
3048
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003049 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003050 DestType, /*VerifyOnly=*/true,
3051 Kind.getKind() != InitializationKind::IK_Direct ||
3052 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003053 if (CheckInitList.HadError()) {
3054 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3055 return;
3056 }
3057
3058 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003059 Sequence.AddListInitializationStep(DestType);
3060}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003061
3062/// \brief Try a reference initialization that involves calling a conversion
3063/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003064static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3065 const InitializedEntity &Entity,
3066 const InitializationKind &Kind,
3067 Expr *Initializer,
3068 bool AllowRValues,
3069 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003070 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3072 QualType T1 = cv1T1.getUnqualifiedType();
3073 QualType cv2T2 = Initializer->getType();
3074 QualType T2 = cv2T2.getUnqualifiedType();
3075
3076 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003077 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003078 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003080 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003081 ObjCConversion,
3082 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003083 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003084 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003085 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003086 (void)ObjCLifetimeConversion;
3087
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003088 // Build the candidate set directly in the initialization sequence
3089 // structure, so that it will persist if we fail.
3090 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3091 CandidateSet.clear();
3092
3093 // Determine whether we are allowed to call explicit constructors or
3094 // explicit conversion operators.
3095 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003097 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003098 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3099 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003100 // The type we're converting to is a class type. Enumerate its constructors
3101 // to see if there is a suitable conversion.
3102 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003103
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003104 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003105 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003106 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003107 NamedDecl *D = *Con;
3108 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3109
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003110 // Find the constructor (which may be a template).
3111 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003112 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 if (ConstructorTmpl)
3114 Constructor = cast<CXXConstructorDecl>(
3115 ConstructorTmpl->getTemplatedDecl());
3116 else
John McCalla0296f72010-03-19 07:35:19 +00003117 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119 if (!Constructor->isInvalidDecl() &&
3120 Constructor->isConvertingConstructor(AllowExplicit)) {
3121 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003122 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003123 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003124 &Initializer, 1, CandidateSet,
3125 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003126 else
John McCalla0296f72010-03-19 07:35:19 +00003127 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003128 &Initializer, 1, CandidateSet,
3129 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003132 }
John McCall3696dcb2010-08-17 07:23:57 +00003133 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3134 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
Douglas Gregor496e8b342010-05-07 19:42:26 +00003136 const RecordType *T2RecordType = 0;
3137 if ((T2RecordType = T2->getAs<RecordType>()) &&
3138 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003139 // The type we're converting from is a class type, enumerate its conversion
3140 // functions.
3141 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3142
John McCallad371252010-01-20 00:46:10 +00003143 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003145 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3146 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147 NamedDecl *D = *I;
3148 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3149 if (isa<UsingShadowDecl>(D))
3150 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3153 CXXConversionDecl *Conv;
3154 if (ConvTemplate)
3155 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3156 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003157 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 // If the conversion function doesn't return a reference type,
3160 // it can't be considered for this conversion unless we're allowed to
3161 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162 // FIXME: Do we need to make sure that we only consider conversion
3163 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003164 // break recursion.
3165 if ((AllowExplicit || !Conv->isExplicit()) &&
3166 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3167 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003168 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003169 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003170 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 else
John McCalla0296f72010-03-19 07:35:19 +00003172 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003173 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003174 }
3175 }
3176 }
John McCall3696dcb2010-08-17 07:23:57 +00003177 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3178 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003179
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 SourceLocation DeclLoc = Initializer->getLocStart();
3181
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003185 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003186 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003187
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003189
Chandler Carruth30141632011-02-25 19:41:05 +00003190 // This is the overload that will actually be used for the initialization, so
3191 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003192 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003193
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003194 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 if (isa<CXXConversionDecl>(Function))
3196 T2 = Function->getResultType();
3197 else
3198 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003199
3200 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003202 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003203 T2.getNonLValueExprType(S.Context),
3204 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003205
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003207 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003208 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003209 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003210 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003211 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003212 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003213
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003215 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003216 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003217 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003218 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003219 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003220 NewDerivedToBase, NewObjCConversion,
3221 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003222 if (NewRefRelationship == Sema::Ref_Incompatible) {
3223 // If the type we've converted to is not reference-related to the
3224 // type we're looking for, then there is another conversion step
3225 // we need to perform to produce a temporary of the right type
3226 // that we'll be binding to.
3227 ImplicitConversionSequence ICS;
3228 ICS.setStandard();
3229 ICS.Standard = Best->FinalConversion;
3230 T2 = ICS.Standard.getToType(2);
3231 Sequence.AddConversionSequenceStep(ICS, T2);
3232 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 Sequence.AddDerivedToBaseCastStep(
3234 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003236 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003237 else if (NewObjCConversion)
3238 Sequence.AddObjCObjectConversionStep(
3239 S.Context.getQualifiedType(T1,
3240 T2.getNonReferenceType().getQualifiers()));
3241
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003243 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3246 return OR_Success;
3247}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Richard Smithc620f552011-10-19 16:55:56 +00003249static void CheckCXX98CompatAccessibleCopy(Sema &S,
3250 const InitializedEntity &Entity,
3251 Expr *CurInitExpr);
3252
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3254static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003255 const InitializedEntity &Entity,
3256 const InitializationKind &Kind,
3257 Expr *Initializer,
3258 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003259 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003260 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003261 Qualifiers T1Quals;
3262 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003263 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003264 Qualifiers T2Quals;
3265 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 // If the initializer is the address of an overloaded function, try
3268 // to resolve the overloaded function. If all goes well, T2 is the
3269 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003270 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3271 T1, Sequence))
3272 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003273
Sebastian Redl29526f02011-11-27 16:50:07 +00003274 // Delegate everything else to a subfunction.
3275 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3276 T1Quals, cv2T2, T2, T2Quals, Sequence);
3277}
3278
3279/// \brief Reference initialization without resolving overloaded functions.
3280static void TryReferenceInitializationCore(Sema &S,
3281 const InitializedEntity &Entity,
3282 const InitializationKind &Kind,
3283 Expr *Initializer,
3284 QualType cv1T1, QualType T1,
3285 Qualifiers T1Quals,
3286 QualType cv2T2, QualType T2,
3287 Qualifiers T2Quals,
3288 InitializationSequence &Sequence) {
3289 QualType DestType = Entity.getType();
3290 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 // Compute some basic properties of the types and the initializer.
3292 bool isLValueRef = DestType->isLValueReferenceType();
3293 bool isRValueRef = !isLValueRef;
3294 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003295 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003296 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003297 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003298 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003299 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003300 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003301
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003304 // "cv2 T2" as follows:
3305 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003307 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003308 // Note the analogous bullet points for rvlaue refs to functions. Because
3309 // there are no function rvalues in C++, rvalue refs to functions are treated
3310 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003311 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003312 bool T1Function = T1->isFunctionType();
3313 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003315 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003317 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003319 // reference-compatible with "cv2 T2," or
3320 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003322 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003323 // can occur. However, we do pay attention to whether it is a bit-field
3324 // to decide whether we're actually binding to a temporary created from
3325 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003326 if (DerivedToBase)
3327 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003329 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003330 else if (ObjCConversion)
3331 Sequence.AddObjCObjectConversionStep(
3332 S.Context.getQualifiedType(T1, T2Quals));
3333
Chandler Carruth04bdce62010-01-12 20:32:25 +00003334 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003335 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003336 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003337 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003338 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 return;
3340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
3342 // - has a class type (i.e., T2 is a class type), where T1 is not
3343 // reference-related to T2, and can be implicitly converted to an
3344 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3345 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 // applicable conversion functions (13.3.1.6) and choosing the best
3347 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003348 // If we have an rvalue ref to function type here, the rhs must be
3349 // an rvalue.
3350 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3351 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003353 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003354 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 Sequence);
3356 if (ConvOvlResult == OR_Success)
3357 return;
John McCall0d1da222010-01-12 00:44:57 +00003358 if (ConvOvlResult != OR_No_Viable_Function) {
3359 Sequence.SetOverloadFailure(
3360 InitializationSequence::FK_ReferenceInitOverloadFailed,
3361 ConvOvlResult);
3362 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003363 }
3364 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003365
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003367 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003368 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003369 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003370 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3371 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3372 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003373 Sequence.SetOverloadFailure(
3374 InitializationSequence::FK_ReferenceInitOverloadFailed,
3375 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003376 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003377 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003378 ? (RefRelationship == Sema::Ref_Related
3379 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3380 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3381 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003382
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003383 return;
3384 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003385
Douglas Gregor92e460e2011-01-20 16:44:54 +00003386 // - If the initializer expression
3387 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3388 // "cv1 T1" is reference-compatible with "cv2 T2"
3389 // Note: functions are handled below.
3390 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003391 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003393 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003394 (InitCategory.isXValue() ||
3395 (InitCategory.isPRValue() && T2->isRecordType()) ||
3396 (InitCategory.isPRValue() && T2->isArrayType()))) {
3397 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3398 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003399 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3400 // compiler the freedom to perform a copy here or bind to the
3401 // object, while C++0x requires that we bind directly to the
3402 // object. Hence, we always bind to the object without making an
3403 // extra copy. However, in C++03 requires that we check for the
3404 // presence of a suitable copy constructor:
3405 //
3406 // The constructor that would be used to make the copy shall
3407 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003408 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003409 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003410 else if (S.getLangOptions().CPlusPlus0x)
3411 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregor92e460e2011-01-20 16:44:54 +00003414 if (DerivedToBase)
3415 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3416 ValueKind);
3417 else if (ObjCConversion)
3418 Sequence.AddObjCObjectConversionStep(
3419 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor92e460e2011-01-20 16:44:54 +00003421 if (T1Quals != T2Quals)
3422 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003424 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
3428 // - has a class type (i.e., T2 is a class type), where T1 is not
3429 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003430 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3431 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003432 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003433 if (RefRelationship == Sema::Ref_Incompatible) {
3434 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3435 Kind, Initializer,
3436 /*AllowRValues=*/true,
3437 Sequence);
3438 if (ConvOvlResult)
3439 Sequence.SetOverloadFailure(
3440 InitializationSequence::FK_ReferenceInitOverloadFailed,
3441 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003443 return;
3444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003446 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3447 return;
3448 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003449
3450 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003451 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003453 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003454
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003455 // Determine whether we are allowed to call explicit constructors or
3456 // explicit conversion operators.
3457 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003458
3459 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3460
John McCall31168b02011-06-15 23:02:42 +00003461 ImplicitConversionSequence ICS
3462 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003463 /*SuppressUserConversions*/ false,
3464 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003465 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003466 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3467 /*AllowObjCWritebackConversion=*/false);
3468
3469 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003470 // FIXME: Use the conversion function set stored in ICS to turn
3471 // this into an overloading ambiguity diagnostic. However, we need
3472 // to keep that set as an OverloadCandidateSet rather than as some
3473 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003474 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3475 Sequence.SetOverloadFailure(
3476 InitializationSequence::FK_ReferenceInitOverloadFailed,
3477 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003478 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3479 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003480 else
3481 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003482 return;
John McCall31168b02011-06-15 23:02:42 +00003483 } else {
3484 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003485 }
3486
3487 // [...] If T1 is reference-related to T2, cv1 must be the
3488 // same cv-qualification as, or greater cv-qualification
3489 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003490 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3491 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003492 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003493 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003494 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3495 return;
3496 }
3497
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003499 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003501 InitCategory.isLValue()) {
3502 Sequence.SetFailed(
3503 InitializationSequence::FK_RValueReferenceBindingToLValue);
3504 return;
3505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3508 return;
3509}
3510
3511/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512/// (C++ [dcl.init.string], C99 6.7.8).
3513static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003514 const InitializedEntity &Entity,
3515 const InitializationKind &Kind,
3516 Expr *Initializer,
3517 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003518 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003519}
3520
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003521/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003523 const InitializedEntity &Entity,
3524 const InitializationKind &Kind,
3525 InitializationSequence &Sequence) {
3526 // C++ [dcl.init]p5:
3527 //
3528 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003529 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003531 // -- if T is an array type, then each element is value-initialized;
3532 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3533 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003535 if (const RecordType *RT = T->getAs<RecordType>()) {
3536 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3537 // -- if T is a class type (clause 9) with a user-declared
3538 // constructor (12.1), then the default constructor for T is
3539 // called (and the initialization is ill-formed if T has no
3540 // accessible default constructor);
3541 //
3542 // FIXME: we really want to refer to a single subobject of the array,
3543 // but Entity doesn't have a way to capture that (yet).
3544 if (ClassDecl->hasUserDeclaredConstructor())
3545 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003547 // -- if T is a (possibly cv-qualified) non-union class type
3548 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003549 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003550 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003551 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003552 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003553 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003555 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003556 }
3557 }
3558
Douglas Gregor1b303932009-12-22 15:35:07 +00003559 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003560}
3561
Douglas Gregor85dabae2009-12-16 01:38:02 +00003562/// \brief Attempt default initialization (C++ [dcl.init]p6).
3563static void TryDefaultInitialization(Sema &S,
3564 const InitializedEntity &Entity,
3565 const InitializationKind &Kind,
3566 InitializationSequence &Sequence) {
3567 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
Douglas Gregor85dabae2009-12-16 01:38:02 +00003569 // C++ [dcl.init]p6:
3570 // To default-initialize an object of type T means:
3571 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003572 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3573
Douglas Gregor85dabae2009-12-16 01:38:02 +00003574 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3575 // constructor for T is called (and the initialization is ill-formed if
3576 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003577 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003578 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3579 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregor85dabae2009-12-16 01:38:02 +00003582 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregor85dabae2009-12-16 01:38:02 +00003584 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003586 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003587 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003588 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003589 return;
3590 }
3591
3592 // If the destination type has a lifetime property, zero-initialize it.
3593 if (DestType.getQualifiers().hasObjCLifetime()) {
3594 Sequence.AddZeroInitializationStep(Entity.getType());
3595 return;
3596 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003597}
3598
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3600/// which enumerates all conversion functions and performs overload resolution
3601/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003603 const InitializedEntity &Entity,
3604 const InitializationKind &Kind,
3605 Expr *Initializer,
3606 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003607 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003608 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3609 QualType SourceType = Initializer->getType();
3610 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3611 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregor540c3b02009-12-14 17:27:33 +00003613 // Build the candidate set directly in the initialization sequence
3614 // structure, so that it will persist if we fail.
3615 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3616 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
Douglas Gregor540c3b02009-12-14 17:27:33 +00003618 // Determine whether we are allowed to call explicit constructors or
3619 // explicit conversion operators.
3620 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
Douglas Gregor540c3b02009-12-14 17:27:33 +00003622 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3623 // The type we're converting to is a class type. Enumerate its constructors
3624 // to see if there is a suitable conversion.
3625 CXXRecordDecl *DestRecordDecl
3626 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627
Douglas Gregord9848152010-04-26 14:36:57 +00003628 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003630 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003631 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003632 Con != ConEnd; ++Con) {
3633 NamedDecl *D = *Con;
3634 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635
Douglas Gregord9848152010-04-26 14:36:57 +00003636 // Find the constructor (which may be a template).
3637 CXXConstructorDecl *Constructor = 0;
3638 FunctionTemplateDecl *ConstructorTmpl
3639 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003640 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003641 Constructor = cast<CXXConstructorDecl>(
3642 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003643 else
Douglas Gregord9848152010-04-26 14:36:57 +00003644 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregord9848152010-04-26 14:36:57 +00003646 if (!Constructor->isInvalidDecl() &&
3647 Constructor->isConvertingConstructor(AllowExplicit)) {
3648 if (ConstructorTmpl)
3649 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3650 /*ExplicitArgs*/ 0,
3651 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003652 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003653 else
3654 S.AddOverloadCandidate(Constructor, FoundDecl,
3655 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003656 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 }
Douglas Gregord9848152010-04-26 14:36:57 +00003659 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003660 }
Eli Friedman78275202009-12-19 08:11:05 +00003661
3662 SourceLocation DeclLoc = Initializer->getLocStart();
3663
Douglas Gregor540c3b02009-12-14 17:27:33 +00003664 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3665 // The type we're converting from is a class type, enumerate its conversion
3666 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003667
Eli Friedman4afe9a32009-12-20 22:12:03 +00003668 // We can only enumerate the conversion functions for a complete type; if
3669 // the type isn't complete, simply skip this step.
3670 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3671 CXXRecordDecl *SourceRecordDecl
3672 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
John McCallad371252010-01-20 00:46:10 +00003674 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003675 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003676 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003678 I != E; ++I) {
3679 NamedDecl *D = *I;
3680 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3681 if (isa<UsingShadowDecl>(D))
3682 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683
Eli Friedman4afe9a32009-12-20 22:12:03 +00003684 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3685 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003686 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003687 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003688 else
John McCallda4458e2010-03-31 01:36:47 +00003689 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690
Eli Friedman4afe9a32009-12-20 22:12:03 +00003691 if (AllowExplicit || !Conv->isExplicit()) {
3692 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003693 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003694 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003695 CandidateSet);
3696 else
John McCalla0296f72010-03-19 07:35:19 +00003697 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003698 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003699 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003700 }
3701 }
3702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703
3704 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003705 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003706 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003707 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003708 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003710 Result);
3711 return;
3712 }
John McCall0d1da222010-01-12 00:44:57 +00003713
Douglas Gregor540c3b02009-12-14 17:27:33 +00003714 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003715 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003716 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
Douglas Gregor540c3b02009-12-14 17:27:33 +00003718 if (isa<CXXConstructorDecl>(Function)) {
3719 // Add the user-defined conversion step. Any cv-qualification conversion is
3720 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003721 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3722 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003723 return;
3724 }
3725
3726 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003727 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003728 if (ConvType->getAs<RecordType>()) {
3729 // If we're converting to a class type, there may be an copy if
3730 // the resulting temporary object (possible to create an object of
3731 // a base class type). That copy is not a separate conversion, so
3732 // we just make a note of the actual destination type (possibly a
3733 // base class of the type returned by the conversion function) and
3734 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003735 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3736 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003737 return;
3738 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003739
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003740 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3741 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Douglas Gregor5ab11652010-04-17 22:01:05 +00003743 // If the conversion following the call to the conversion function
3744 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003745 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3746 Best->FinalConversion.Third) {
3747 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003748 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003749 ICS.Standard = Best->FinalConversion;
3750 Sequence.AddConversionSequenceStep(ICS, DestType);
3751 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752}
3753
John McCall31168b02011-06-15 23:02:42 +00003754/// The non-zero enum values here are indexes into diagnostic alternatives.
3755enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3756
3757/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003758static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3759 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003760 // Skip parens.
3761 e = e->IgnoreParens();
3762
3763 // Skip address-of nodes.
3764 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3765 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003766 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003767
3768 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003769 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3770 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003771 case CK_Dependent:
3772 case CK_BitCast:
3773 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003774 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003775 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003776
3777 case CK_ArrayToPointerDecay:
3778 return IIK_nonscalar;
3779
3780 case CK_NullToPointer:
3781 return IIK_okay;
3782
3783 default:
3784 break;
3785 }
3786
3787 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003788 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3789 if (!isAddressOf) return IIK_nonlocal;
3790
3791 VarDecl *var;
3792 if (isa<DeclRefExpr>(e)) {
3793 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3794 if (!var) return IIK_nonlocal;
3795 } else {
3796 var = cast<BlockDeclRefExpr>(e)->getDecl();
3797 }
3798
3799 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003800
3801 // If we have a conditional operator, check both sides.
3802 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003803 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003804 return iik;
3805
John McCall63f84442011-06-27 23:59:58 +00003806 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003807
3808 // These are never scalar.
3809 } else if (isa<ArraySubscriptExpr>(e)) {
3810 return IIK_nonscalar;
3811
3812 // Otherwise, it needs to be a null pointer constant.
3813 } else {
3814 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3815 ? IIK_okay : IIK_nonlocal);
3816 }
3817
3818 return IIK_nonlocal;
3819}
3820
3821/// Check whether the given expression is a valid operand for an
3822/// indirect copy/restore.
3823static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3824 assert(src->isRValue());
3825
John McCall63f84442011-06-27 23:59:58 +00003826 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003827 if (iik == IIK_okay) return;
3828
3829 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3830 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3831 << src->getSourceRange();
3832}
3833
Douglas Gregore2f943b2011-02-22 18:29:51 +00003834/// \brief Determine whether we have compatible array types for the
3835/// purposes of GNU by-copy array initialization.
3836static bool hasCompatibleArrayTypes(ASTContext &Context,
3837 const ArrayType *Dest,
3838 const ArrayType *Source) {
3839 // If the source and destination array types are equivalent, we're
3840 // done.
3841 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3842 return true;
3843
3844 // Make sure that the element types are the same.
3845 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3846 return false;
3847
3848 // The only mismatch we allow is when the destination is an
3849 // incomplete array type and the source is a constant array type.
3850 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3851}
3852
John McCall31168b02011-06-15 23:02:42 +00003853static bool tryObjCWritebackConversion(Sema &S,
3854 InitializationSequence &Sequence,
3855 const InitializedEntity &Entity,
3856 Expr *Initializer) {
3857 bool ArrayDecay = false;
3858 QualType ArgType = Initializer->getType();
3859 QualType ArgPointee;
3860 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3861 ArrayDecay = true;
3862 ArgPointee = ArgArrayType->getElementType();
3863 ArgType = S.Context.getPointerType(ArgPointee);
3864 }
3865
3866 // Handle write-back conversion.
3867 QualType ConvertedArgType;
3868 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3869 ConvertedArgType))
3870 return false;
3871
3872 // We should copy unless we're passing to an argument explicitly
3873 // marked 'out'.
3874 bool ShouldCopy = true;
3875 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3876 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3877
3878 // Do we need an lvalue conversion?
3879 if (ArrayDecay || Initializer->isGLValue()) {
3880 ImplicitConversionSequence ICS;
3881 ICS.setStandard();
3882 ICS.Standard.setAsIdentityConversion();
3883
3884 QualType ResultType;
3885 if (ArrayDecay) {
3886 ICS.Standard.First = ICK_Array_To_Pointer;
3887 ResultType = S.Context.getPointerType(ArgPointee);
3888 } else {
3889 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3890 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3891 }
3892
3893 Sequence.AddConversionSequenceStep(ICS, ResultType);
3894 }
3895
3896 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3897 return true;
3898}
3899
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900InitializationSequence::InitializationSequence(Sema &S,
3901 const InitializedEntity &Entity,
3902 const InitializationKind &Kind,
3903 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003904 unsigned NumArgs)
3905 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003906 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909 // The semantics of initializers are as follows. The destination type is
3910 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003911 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003913 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003914 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003915
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003916 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3918 SequenceKind = DependentSequence;
3919 return;
3920 }
3921
Sebastian Redld201edf2011-06-05 13:59:11 +00003922 // Almost everything is a normal sequence.
3923 setSequenceKind(NormalSequence);
3924
John McCalled75c092010-12-07 22:54:16 +00003925 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003926 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003927 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003928 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3929 if (result.isInvalid()) {
3930 SetFailed(FK_PlaceholderType);
3931 return;
John McCall4124c492011-10-17 18:40:02 +00003932 }
John McCalld5c98ae2011-11-15 01:35:18 +00003933 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003934 }
John McCalled75c092010-12-07 22:54:16 +00003935
John McCall4124c492011-10-17 18:40:02 +00003936
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003937 QualType SourceType;
3938 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003939 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003940 Initializer = Args[0];
3941 if (!isa<InitListExpr>(Initializer))
3942 SourceType = Initializer->getType();
3943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944
3945 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003946 // list-initialized (8.5.4).
3947 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003948 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003949 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003952 // - If the destination type is a reference type, see 8.5.3.
3953 if (DestType->isReferenceType()) {
3954 // C++0x [dcl.init.ref]p1:
3955 // A variable declared to be a T& or T&&, that is, "reference to type T"
3956 // (8.3.2), shall be initialized by an object, or function, of type T or
3957 // by an object that can be converted into a T.
3958 // (Therefore, multiple arguments are not permitted.)
3959 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003960 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003961 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003962 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003963 return;
3964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003966 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003967 if (Kind.getKind() == InitializationKind::IK_Value ||
3968 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003969 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003970 return;
3971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972
Douglas Gregor85dabae2009-12-16 01:38:02 +00003973 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003974 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003975 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003976 return;
3977 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003978
John McCall66884dd2011-02-21 07:22:22 +00003979 // - If the destination type is an array of characters, an array of
3980 // char16_t, an array of char32_t, or an array of wchar_t, and the
3981 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003982 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003983 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003984 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00003985 if (Initializer && isa<VariableArrayType>(DestAT)) {
3986 SetFailed(FK_VariableLengthArrayHasInitializer);
3987 return;
3988 }
3989
Douglas Gregore2f943b2011-02-22 18:29:51 +00003990 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003991 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003992 return;
3993 }
3994
Douglas Gregore2f943b2011-02-22 18:29:51 +00003995 // Note: as an GNU C extension, we allow initialization of an
3996 // array from a compound literal that creates an array of the same
3997 // type, so long as the initializer has no side effects.
3998 if (!S.getLangOptions().CPlusPlus && Initializer &&
3999 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4000 Initializer->getType()->isArrayType()) {
4001 const ArrayType *SourceAT
4002 = Context.getAsArrayType(Initializer->getType());
4003 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004004 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004005 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004006 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004007 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004008 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004009 }
4010 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004011 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004013 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004015 return;
4016 }
Eli Friedman78275202009-12-19 08:11:05 +00004017
John McCall31168b02011-06-15 23:02:42 +00004018 // Determine whether we should consider writeback conversions for
4019 // Objective-C ARC.
4020 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4021 Entity.getKind() == InitializedEntity::EK_Parameter;
4022
4023 // We're at the end of the line for C: it's either a write-back conversion
4024 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004025 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004026 // If allowed, check whether this is an Objective-C writeback conversion.
4027 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004028 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004029 return;
4030 }
4031
4032 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004033 AddCAssignmentStep(DestType);
4034 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004035 return;
4036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037
John McCall31168b02011-06-15 23:02:42 +00004038 assert(S.getLangOptions().CPlusPlus);
4039
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 // - If the destination type is a (possibly cv-qualified) class type:
4041 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042 // - If the initialization is direct-initialization, or if it is
4043 // copy-initialization where the cv-unqualified version of the
4044 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004045 // class of the destination, constructors are considered. [...]
4046 if (Kind.getKind() == InitializationKind::IK_Direct ||
4047 (Kind.getKind() == InitializationKind::IK_Copy &&
4048 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4049 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004051 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004055 // used) to a derived class thereof are enumerated as described in
4056 // 13.3.1.4, and the best one is chosen through overload resolution
4057 // (13.3).
4058 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004059 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004060 return;
4061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Douglas Gregor85dabae2009-12-16 01:38:02 +00004063 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004064 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004065 return;
4066 }
4067 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068
4069 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004070 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004071 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004072 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4073 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 return;
4075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004077 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004078 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004079 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004081 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004082
4083 ImplicitConversionSequence ICS
4084 = S.TryImplicitConversion(Initializer, Entity.getType(),
4085 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004086 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004087 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004088 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4089 allowObjCWritebackConversion);
4090
4091 if (ICS.isStandard() &&
4092 ICS.Standard.Second == ICK_Writeback_Conversion) {
4093 // Objective-C ARC writeback conversion.
4094
4095 // We should copy unless we're passing to an argument explicitly
4096 // marked 'out'.
4097 bool ShouldCopy = true;
4098 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4099 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4100
4101 // If there was an lvalue adjustment, add it as a separate conversion.
4102 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4103 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4104 ImplicitConversionSequence LvalueICS;
4105 LvalueICS.setStandard();
4106 LvalueICS.Standard.setAsIdentityConversion();
4107 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4108 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004109 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004110 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004111
4112 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004113 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004114 DeclAccessPair dap;
4115 if (Initializer->getType() == Context.OverloadTy &&
4116 !S.ResolveAddressOfOverloadedFunction(Initializer
4117 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004118 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004119 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004120 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004121 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004122 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004123
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004124 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004125 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004126}
4127
4128InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004129 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004130 StepEnd = Steps.end();
4131 Step != StepEnd; ++Step)
4132 Step->Destroy();
4133}
4134
4135//===----------------------------------------------------------------------===//
4136// Perform initialization
4137//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004139getAssignmentAction(const InitializedEntity &Entity) {
4140 switch(Entity.getKind()) {
4141 case InitializedEntity::EK_Variable:
4142 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004143 case InitializedEntity::EK_Exception:
4144 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004145 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004146 return Sema::AA_Initializing;
4147
4148 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004149 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004150 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4151 return Sema::AA_Sending;
4152
Douglas Gregore1314a62009-12-18 05:02:21 +00004153 return Sema::AA_Passing;
4154
4155 case InitializedEntity::EK_Result:
4156 return Sema::AA_Returning;
4157
Douglas Gregore1314a62009-12-18 05:02:21 +00004158 case InitializedEntity::EK_Temporary:
4159 // FIXME: Can we tell apart casting vs. converting?
4160 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregore1314a62009-12-18 05:02:21 +00004162 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004163 case InitializedEntity::EK_ArrayElement:
4164 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004165 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004166 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004167 return Sema::AA_Initializing;
4168 }
4169
David Blaikie8a40f702012-01-17 06:56:22 +00004170 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004171}
4172
Douglas Gregor95562572010-04-24 23:45:46 +00004173/// \brief Whether we should binding a created object as a temporary when
4174/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004175static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004176 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004177 case InitializedEntity::EK_ArrayElement:
4178 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004179 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004180 case InitializedEntity::EK_New:
4181 case InitializedEntity::EK_Variable:
4182 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004183 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004184 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004185 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004186 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004187 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004188 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
Douglas Gregore1314a62009-12-18 05:02:21 +00004190 case InitializedEntity::EK_Parameter:
4191 case InitializedEntity::EK_Temporary:
4192 return true;
4193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
Douglas Gregore1314a62009-12-18 05:02:21 +00004195 llvm_unreachable("missed an InitializedEntity kind?");
4196}
4197
Douglas Gregor95562572010-04-24 23:45:46 +00004198/// \brief Whether the given entity, when initialized with an object
4199/// created for that initialization, requires destruction.
4200static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4201 switch (Entity.getKind()) {
4202 case InitializedEntity::EK_Member:
4203 case InitializedEntity::EK_Result:
4204 case InitializedEntity::EK_New:
4205 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004206 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004207 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004208 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004209 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004210 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregor95562572010-04-24 23:45:46 +00004212 case InitializedEntity::EK_Variable:
4213 case InitializedEntity::EK_Parameter:
4214 case InitializedEntity::EK_Temporary:
4215 case InitializedEntity::EK_ArrayElement:
4216 case InitializedEntity::EK_Exception:
4217 return true;
4218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219
4220 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004221}
4222
Richard Smithc620f552011-10-19 16:55:56 +00004223/// \brief Look for copy and move constructors and constructor templates, for
4224/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4225static void LookupCopyAndMoveConstructors(Sema &S,
4226 OverloadCandidateSet &CandidateSet,
4227 CXXRecordDecl *Class,
4228 Expr *CurInitExpr) {
4229 DeclContext::lookup_iterator Con, ConEnd;
4230 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4231 Con != ConEnd; ++Con) {
4232 CXXConstructorDecl *Constructor = 0;
4233
4234 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4235 // Handle copy/moveconstructors, only.
4236 if (!Constructor || Constructor->isInvalidDecl() ||
4237 !Constructor->isCopyOrMoveConstructor() ||
4238 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4239 continue;
4240
4241 DeclAccessPair FoundDecl
4242 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4243 S.AddOverloadCandidate(Constructor, FoundDecl,
4244 &CurInitExpr, 1, CandidateSet);
4245 continue;
4246 }
4247
4248 // Handle constructor templates.
4249 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4250 if (ConstructorTmpl->isInvalidDecl())
4251 continue;
4252
4253 Constructor = cast<CXXConstructorDecl>(
4254 ConstructorTmpl->getTemplatedDecl());
4255 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4256 continue;
4257
4258 // FIXME: Do we need to limit this to copy-constructor-like
4259 // candidates?
4260 DeclAccessPair FoundDecl
4261 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4262 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4263 &CurInitExpr, 1, CandidateSet, true);
4264 }
4265}
4266
4267/// \brief Get the location at which initialization diagnostics should appear.
4268static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4269 Expr *Initializer) {
4270 switch (Entity.getKind()) {
4271 case InitializedEntity::EK_Result:
4272 return Entity.getReturnLoc();
4273
4274 case InitializedEntity::EK_Exception:
4275 return Entity.getThrowLoc();
4276
4277 case InitializedEntity::EK_Variable:
4278 return Entity.getDecl()->getLocation();
4279
4280 case InitializedEntity::EK_ArrayElement:
4281 case InitializedEntity::EK_Member:
4282 case InitializedEntity::EK_Parameter:
4283 case InitializedEntity::EK_Temporary:
4284 case InitializedEntity::EK_New:
4285 case InitializedEntity::EK_Base:
4286 case InitializedEntity::EK_Delegating:
4287 case InitializedEntity::EK_VectorElement:
4288 case InitializedEntity::EK_ComplexElement:
4289 case InitializedEntity::EK_BlockElement:
4290 return Initializer->getLocStart();
4291 }
4292 llvm_unreachable("missed an InitializedEntity kind?");
4293}
4294
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004295/// \brief Make a (potentially elidable) temporary copy of the object
4296/// provided by the given initializer by calling the appropriate copy
4297/// constructor.
4298///
4299/// \param S The Sema object used for type-checking.
4300///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004301/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004302/// the type of the initializer expression or a superclass thereof.
4303///
4304/// \param Enter The entity being initialized.
4305///
4306/// \param CurInit The initializer expression.
4307///
4308/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4309/// is permitted in C++03 (but not C++0x) when binding a reference to
4310/// an rvalue.
4311///
4312/// \returns An expression that copies the initializer expression into
4313/// a temporary object, or an error expression if a copy could not be
4314/// created.
John McCalldadc5752010-08-24 06:29:42 +00004315static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004316 QualType T,
4317 const InitializedEntity &Entity,
4318 ExprResult CurInit,
4319 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004320 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004321 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004323 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004324 Class = cast<CXXRecordDecl>(Record->getDecl());
4325 if (!Class)
4326 return move(CurInit);
4327
Douglas Gregor5d369002011-01-21 18:05:27 +00004328 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004329 // When certain criteria are met, an implementation is allowed to
4330 // omit the copy/move construction of a class object, even if the
4331 // copy/move constructor and/or destructor for the object have
4332 // side effects. [...]
4333 // - when a temporary class object that has not been bound to a
4334 // reference (12.2) would be copied/moved to a class object
4335 // with the same cv-unqualified type, the copy/move operation
4336 // can be omitted by constructing the temporary object
4337 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004339 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004340 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004342 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004343 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004344 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004345
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004347 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4348 return move(CurInit);
4349
Douglas Gregorf282a762011-01-21 19:38:21 +00004350 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004351 // Only consider constructors and constructor templates. Per
4352 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4353 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004354 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004355 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004357 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4358
Douglas Gregore1314a62009-12-18 05:02:21 +00004359 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004360 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004361 case OR_Success:
4362 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004363
Douglas Gregore1314a62009-12-18 05:02:21 +00004364 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004365 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4366 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4367 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004368 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004369 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004370 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004371 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004372 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004373 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374
Douglas Gregore1314a62009-12-18 05:02:21 +00004375 case OR_Ambiguous:
4376 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004377 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004378 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004379 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004380 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregore1314a62009-12-18 05:02:21 +00004382 case OR_Deleted:
4383 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004384 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004385 << CurInitExpr->getSourceRange();
4386 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004387 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004388 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004389 }
4390
Douglas Gregor5ab11652010-04-17 22:01:05 +00004391 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004392 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004393 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004394
Anders Carlssona01874b2010-04-21 18:47:17 +00004395 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004396 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004397
4398 if (IsExtraneousCopy) {
4399 // If this is a totally extraneous copy for C++03 reference
4400 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004401 // expression. We don't generate an (elided) copy operation here
4402 // because doing so would require us to pass down a flag to avoid
4403 // infinite recursion, where each step adds another extraneous,
4404 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004405
Douglas Gregor30b52772010-04-18 07:57:34 +00004406 // Instantiate the default arguments of any extra parameters in
4407 // the selected copy constructor, as if we were going to create a
4408 // proper call to the copy constructor.
4409 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4410 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4411 if (S.RequireCompleteType(Loc, Parm->getType(),
4412 S.PDiag(diag::err_call_incomplete_argument)))
4413 break;
4414
4415 // Build the default argument expression; we don't actually care
4416 // if this succeeds or not, because this routine will complain
4417 // if there was a problem.
4418 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4419 }
4420
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004421 return S.Owned(CurInitExpr);
4422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Eli Friedmanfa0df832012-02-02 03:46:19 +00004424 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004425
Douglas Gregor5ab11652010-04-17 22:01:05 +00004426 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004427 // constructor call (we might have derived-to-base conversions, or
4428 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004429 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004430 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004431 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004432
Douglas Gregord0ace022010-04-25 00:55:24 +00004433 // Actually perform the constructor call.
4434 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004435 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004436 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004437 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004438 CXXConstructExpr::CK_Complete,
4439 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440
Douglas Gregord0ace022010-04-25 00:55:24 +00004441 // If we're supposed to bind temporaries, do so.
4442 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4443 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4444 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004445}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004446
Richard Smithc620f552011-10-19 16:55:56 +00004447/// \brief Check whether elidable copy construction for binding a reference to
4448/// a temporary would have succeeded if we were building in C++98 mode, for
4449/// -Wc++98-compat.
4450static void CheckCXX98CompatAccessibleCopy(Sema &S,
4451 const InitializedEntity &Entity,
4452 Expr *CurInitExpr) {
4453 assert(S.getLangOptions().CPlusPlus0x);
4454
4455 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4456 if (!Record)
4457 return;
4458
4459 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4460 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4461 == DiagnosticsEngine::Ignored)
4462 return;
4463
4464 // Find constructors which would have been considered.
4465 OverloadCandidateSet CandidateSet(Loc);
4466 LookupCopyAndMoveConstructors(
4467 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4468
4469 // Perform overload resolution.
4470 OverloadCandidateSet::iterator Best;
4471 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4472
4473 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4474 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4475 << CurInitExpr->getSourceRange();
4476
4477 switch (OR) {
4478 case OR_Success:
4479 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4480 Best->FoundDecl.getAccess(), Diag);
4481 // FIXME: Check default arguments as far as that's possible.
4482 break;
4483
4484 case OR_No_Viable_Function:
4485 S.Diag(Loc, Diag);
4486 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4487 break;
4488
4489 case OR_Ambiguous:
4490 S.Diag(Loc, Diag);
4491 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4492 break;
4493
4494 case OR_Deleted:
4495 S.Diag(Loc, Diag);
4496 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4497 << 1 << Best->Function->isDeleted();
4498 break;
4499 }
4500}
4501
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004502void InitializationSequence::PrintInitLocationNote(Sema &S,
4503 const InitializedEntity &Entity) {
4504 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4505 if (Entity.getDecl()->getLocation().isInvalid())
4506 return;
4507
4508 if (Entity.getDecl()->getDeclName())
4509 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4510 << Entity.getDecl()->getDeclName();
4511 else
4512 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4513 }
4514}
4515
Sebastian Redl112aa822011-07-14 19:07:55 +00004516static bool isReferenceBinding(const InitializationSequence::Step &s) {
4517 return s.Kind == InitializationSequence::SK_BindReference ||
4518 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4519}
4520
Sebastian Redled2e5322011-12-22 14:44:04 +00004521static ExprResult
4522PerformConstructorInitialization(Sema &S,
4523 const InitializedEntity &Entity,
4524 const InitializationKind &Kind,
4525 MultiExprArg Args,
4526 const InitializationSequence::Step& Step,
4527 bool &ConstructorInitRequiresZeroInit) {
4528 unsigned NumArgs = Args.size();
4529 CXXConstructorDecl *Constructor
4530 = cast<CXXConstructorDecl>(Step.Function.Function);
4531 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4532
4533 // Build a call to the selected constructor.
4534 ASTOwningVector<Expr*> ConstructorArgs(S);
4535 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4536 ? Kind.getEqualLoc()
4537 : Kind.getLocation();
4538
4539 if (Kind.getKind() == InitializationKind::IK_Default) {
4540 // Force even a trivial, implicit default constructor to be
4541 // semantically checked. We do this explicitly because we don't build
4542 // the definition for completely trivial constructors.
4543 CXXRecordDecl *ClassDecl = Constructor->getParent();
4544 assert(ClassDecl && "No parent class for constructor.");
4545 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4546 ClassDecl->hasTrivialDefaultConstructor() &&
4547 !Constructor->isUsed(false))
4548 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4549 }
4550
4551 ExprResult CurInit = S.Owned((Expr *)0);
4552
4553 // Determine the arguments required to actually perform the constructor
4554 // call.
4555 if (S.CompleteConstructorCall(Constructor, move(Args),
4556 Loc, ConstructorArgs))
4557 return ExprError();
4558
4559
4560 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4561 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4562 (Kind.getKind() == InitializationKind::IK_Direct ||
4563 Kind.getKind() == InitializationKind::IK_Value)) {
4564 // An explicitly-constructed temporary, e.g., X(1, 2).
4565 unsigned NumExprs = ConstructorArgs.size();
4566 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004567 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004568 S.DiagnoseUseOfDecl(Constructor, Loc);
4569
4570 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4571 if (!TSInfo)
4572 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4573
4574 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4575 Constructor,
4576 TSInfo,
4577 Exprs,
4578 NumExprs,
4579 Kind.getParenRange(),
4580 HadMultipleCandidates,
4581 ConstructorInitRequiresZeroInit));
4582 } else {
4583 CXXConstructExpr::ConstructionKind ConstructKind =
4584 CXXConstructExpr::CK_Complete;
4585
4586 if (Entity.getKind() == InitializedEntity::EK_Base) {
4587 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4588 CXXConstructExpr::CK_VirtualBase :
4589 CXXConstructExpr::CK_NonVirtualBase;
4590 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4591 ConstructKind = CXXConstructExpr::CK_Delegating;
4592 }
4593
4594 // Only get the parenthesis range if it is a direct construction.
4595 SourceRange parenRange =
4596 Kind.getKind() == InitializationKind::IK_Direct ?
4597 Kind.getParenRange() : SourceRange();
4598
4599 // If the entity allows NRVO, mark the construction as elidable
4600 // unconditionally.
4601 if (Entity.allowsNRVO())
4602 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4603 Constructor, /*Elidable=*/true,
4604 move_arg(ConstructorArgs),
4605 HadMultipleCandidates,
4606 ConstructorInitRequiresZeroInit,
4607 ConstructKind,
4608 parenRange);
4609 else
4610 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4611 Constructor,
4612 move_arg(ConstructorArgs),
4613 HadMultipleCandidates,
4614 ConstructorInitRequiresZeroInit,
4615 ConstructKind,
4616 parenRange);
4617 }
4618 if (CurInit.isInvalid())
4619 return ExprError();
4620
4621 // Only check access if all of that succeeded.
4622 S.CheckConstructorAccess(Loc, Constructor, Entity,
4623 Step.Function.FoundDecl.getAccess());
4624 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4625
4626 if (shouldBindAsTemporary(Entity))
4627 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4628
4629 return move(CurInit);
4630}
4631
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004633InitializationSequence::Perform(Sema &S,
4634 const InitializedEntity &Entity,
4635 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004636 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004637 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004638 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004639 unsigned NumArgs = Args.size();
4640 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004641 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643
Sebastian Redld201edf2011-06-05 13:59:11 +00004644 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004645 // If the declaration is a non-dependent, incomplete array type
4646 // that has an initializer, then its type will be completed once
4647 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004648 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004649 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004650 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004651 if (const IncompleteArrayType *ArrayT
4652 = S.Context.getAsIncompleteArrayType(DeclType)) {
4653 // FIXME: We don't currently have the ability to accurately
4654 // compute the length of an initializer list without
4655 // performing full type-checking of the initializer list
4656 // (since we have to determine where braces are implicitly
4657 // introduced and such). So, we fall back to making the array
4658 // type a dependently-sized array type with no specified
4659 // bound.
4660 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4661 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004662
Douglas Gregor51e77d52009-12-10 17:56:55 +00004663 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004664 if (DeclaratorDecl *DD = Entity.getDecl()) {
4665 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4666 TypeLoc TL = TInfo->getTypeLoc();
4667 if (IncompleteArrayTypeLoc *ArrayLoc
4668 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4669 Brackets = ArrayLoc->getBracketsRange();
4670 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004671 }
4672
4673 *ResultType
4674 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4675 /*NumElts=*/0,
4676 ArrayT->getSizeModifier(),
4677 ArrayT->getIndexTypeCVRQualifiers(),
4678 Brackets);
4679 }
4680
4681 }
4682 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004683 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4684 Kind.isExplicitCast());
4685 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004686 }
4687
Sebastian Redld201edf2011-06-05 13:59:11 +00004688 // No steps means no initialization.
4689 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004690 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor1b303932009-12-22 15:35:07 +00004692 QualType DestType = Entity.getType().getNonReferenceType();
4693 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004694 // the same as Entity.getDecl()->getType() in cases involving type merging,
4695 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004696 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004697 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004698 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699
John McCalldadc5752010-08-24 06:29:42 +00004700 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004703 // grab the only argument out the Args and place it into the "current"
4704 // initializer.
4705 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004706 case SK_ResolveAddressOfOverloadedFunction:
4707 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004708 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004709 case SK_CastDerivedToBaseLValue:
4710 case SK_BindReference:
4711 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004712 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004713 case SK_UserConversion:
4714 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004715 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004716 case SK_QualificationConversionRValue:
4717 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004718 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004719 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004720 case SK_UnwrapInitList:
4721 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004722 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004723 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004724 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004725 case SK_ArrayInit:
4726 case SK_PassByIndirectCopyRestore:
4727 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004728 case SK_ProduceObjCObject:
4729 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004730 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004731 CurInit = Args.get()[0];
4732 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004733 break;
John McCall34376a62010-12-04 03:47:34 +00004734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregore1314a62009-12-18 05:02:21 +00004736 case SK_ConstructorInitialization:
4737 case SK_ZeroInitialization:
4738 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
4741 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004742 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004743 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004744 for (step_iterator Step = step_begin(), StepEnd = step_end();
4745 Step != StepEnd; ++Step) {
4746 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004747 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
John Wiegley01296292011-04-08 18:41:53 +00004749 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004751 switch (Step->Kind) {
4752 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004755 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004756 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004757 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004758 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004759 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004762 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004763 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004764 case SK_CastDerivedToBaseLValue: {
4765 // We have a derived-to-base cast that produces either an rvalue or an
4766 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
John McCallcf142162010-08-07 06:22:56 +00004768 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004770 // Casts to inaccessible base classes are allowed with C-style casts.
4771 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4772 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004773 CurInit.get()->getLocStart(),
4774 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004775 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004776 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor88d292c2010-05-13 16:44:06 +00004778 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4779 QualType T = SourceType;
4780 if (const PointerType *Pointer = T->getAs<PointerType>())
4781 T = Pointer->getPointeeType();
4782 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004783 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004784 cast<CXXRecordDecl>(RecordTy->getDecl()));
4785 }
4786
John McCall2536c6d2010-08-25 10:28:54 +00004787 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004788 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004789 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004790 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004791 VK_XValue :
4792 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004793 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4794 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004795 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004796 CurInit.get(),
4797 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004798 break;
4799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004801 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004802 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004803 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4804 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004805 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004806 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004807 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004808 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004809 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004810 }
Anders Carlssona91be642010-01-29 02:47:33 +00004811
John Wiegley01296292011-04-08 18:41:53 +00004812 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004813 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004814 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4815 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004816 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004817 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004818 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004821 // Reference binding does not have any corresponding ASTs.
4822
4823 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004824 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004825 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004826
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004827 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004828
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004829 case SK_BindReferenceToTemporary:
4830 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004831 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004832 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004833
Douglas Gregorfe314812011-06-21 17:03:29 +00004834 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004835 CurInit = new (S.Context) MaterializeTemporaryExpr(
4836 Entity.getType().getNonReferenceType(),
4837 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004838 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004839
4840 // If we're binding to an Objective-C object that has lifetime, we
4841 // need cleanups.
4842 if (S.getLangOptions().ObjCAutoRefCount &&
4843 CurInit.get()->getType()->isObjCLifetimeType())
4844 S.ExprNeedsCleanups = true;
4845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004848 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004850 /*IsExtraneousCopy=*/true);
4851 break;
4852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 case SK_UserConversion: {
4854 // We have a user-defined conversion that invokes either a constructor
4855 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004856 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004857 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004858 FunctionDecl *Fn = Step->Function.Function;
4859 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004860 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004861 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004862 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004863 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004864 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004865 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004867
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868 // Determine the arguments required to actually perform the constructor
4869 // call.
John Wiegley01296292011-04-08 18:41:53 +00004870 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004871 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004872 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004873 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004874 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004875
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004876 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004878 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004879 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004880 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004881 CXXConstructExpr::CK_Complete,
4882 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004883 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004884 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004885
Anders Carlssona01874b2010-04-21 18:47:17 +00004886 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004887 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004888 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
John McCalle3027922010-08-25 11:45:40 +00004890 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004891 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4892 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4893 S.IsDerivedFrom(SourceType, Class))
4894 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregor95562572010-04-24 23:45:46 +00004896 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 } else {
4898 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004899 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004900 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004901 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004902 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
4904 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004905 // derived-to-base conversion? I believe the answer is "no", because
4906 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004907 ExprResult CurInitExprRes =
4908 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4909 FoundFn, Conversion);
4910 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004911 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004912 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004914 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004915 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4916 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004917 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004918 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004919
John McCalle3027922010-08-25 11:45:40 +00004920 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921
Douglas Gregor95562572010-04-24 23:45:46 +00004922 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Sebastian Redl112aa822011-07-14 19:07:55 +00004925 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004926 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4927
4928 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004929 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004930 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004932 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004933 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004934 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004935 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00004936 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004937 }
4938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
John McCallcf142162010-08-07 06:22:56 +00004940 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004941 CurInit.get()->getType(),
4942 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004943 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004944 if (MaybeBindToTemp)
4945 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004946 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004947 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4948 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004949 break;
4950 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004951
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004952 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004953 case SK_QualificationConversionXValue:
4954 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004955 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004956 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004957 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004958 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004959 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004960 VK_XValue :
4961 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004962 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004963 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004964 }
4965
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004966 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004967 Sema::CheckedConversionKind CCK
4968 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4969 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00004970 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00004971 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004972 ExprResult CurInitExprRes =
4973 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004974 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004975 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004976 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004977 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004978 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregor51e77d52009-12-10 17:56:55 +00004981 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004982 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00004983 // Hack: We must pass *ResultType if available in order to set the type
4984 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
4985 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
4986 // temporary, not a reference, so we should pass Ty.
4987 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
4988 // Since this step is never used for a reference directly, we explicitly
4989 // unwrap references here and rewrap them afterwards.
4990 // We also need to create a InitializeTemporary entity for this.
4991 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
4992 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
4993 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
4994 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
4995 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00004996 Kind.getKind() != InitializationKind::IK_Direct ||
4997 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004998 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004999 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005000
Sebastian Redl29526f02011-11-27 16:50:07 +00005001 if (ResultType) {
5002 if ((*ResultType)->isRValueReferenceType())
5003 Ty = S.Context.getRValueReferenceType(Ty);
5004 else if ((*ResultType)->isLValueReferenceType())
5005 Ty = S.Context.getLValueReferenceType(Ty,
5006 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5007 *ResultType = Ty;
5008 }
5009
5010 InitListExpr *StructuredInitList =
5011 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005012 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005013 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005014 break;
5015 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005016
Sebastian Redled2e5322011-12-22 14:44:04 +00005017 case SK_ListConstructorCall: {
5018 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5019 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5020 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5021 move(Arg), *Step,
5022 ConstructorInitRequiresZeroInit);
5023 break;
5024 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005025
Sebastian Redl29526f02011-11-27 16:50:07 +00005026 case SK_UnwrapInitList:
5027 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5028 break;
5029
5030 case SK_RewrapInitList: {
5031 Expr *E = CurInit.take();
5032 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5033 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5034 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5035 ILE->setSyntacticForm(Syntactic);
5036 ILE->setType(E->getType());
5037 ILE->setValueKind(E->getValueKind());
5038 CurInit = S.Owned(ILE);
5039 break;
5040 }
5041
Sebastian Redled2e5322011-12-22 14:44:04 +00005042 case SK_ConstructorInitialization:
5043 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5044 *Step,
5045 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005048 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005049 step_iterator NextStep = Step;
5050 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005052 NextStep->Kind == SK_ConstructorInitialization) {
5053 // The need for zero-initialization is recorded directly into
5054 // the call to the object's constructor within the next step.
5055 ConstructorInitRequiresZeroInit = true;
5056 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5057 S.getLangOptions().CPlusPlus &&
5058 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005059 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5060 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005062 Kind.getRange().getBegin());
5063
5064 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5065 TSInfo->getType().getNonLValueExprType(S.Context),
5066 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005067 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005068 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005069 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005070 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005071 break;
5072 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005073
5074 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005075 QualType SourceType = CurInit.get()->getType();
5076 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005077 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005078 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5079 if (Result.isInvalid())
5080 return ExprError();
5081 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005082
5083 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005084 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005085 if (ConvTy != Sema::Compatible &&
5086 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005087 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005088 == Sema::Compatible)
5089 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005090 if (CurInitExprRes.isInvalid())
5091 return ExprError();
5092 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005093
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005094 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005095 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5096 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005097 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005098 getAssignmentAction(Entity),
5099 &Complained)) {
5100 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005101 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005102 } else if (Complained)
5103 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005104 break;
5105 }
Eli Friedman78275202009-12-19 08:11:05 +00005106
5107 case SK_StringInit: {
5108 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005109 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005110 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005111 break;
5112 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005113
5114 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005115 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005116 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005117 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005118 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005119
5120 case SK_ArrayInit:
5121 // Okay: we checked everything before creating this step. Note that
5122 // this is a GNU extension.
5123 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005124 << Step->Type << CurInit.get()->getType()
5125 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005126
5127 // If the destination type is an incomplete array type, update the
5128 // type accordingly.
5129 if (ResultType) {
5130 if (const IncompleteArrayType *IncompleteDest
5131 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5132 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005133 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005134 *ResultType = S.Context.getConstantArrayType(
5135 IncompleteDest->getElementType(),
5136 ConstantSource->getSize(),
5137 ArrayType::Normal, 0);
5138 }
5139 }
5140 }
John McCall31168b02011-06-15 23:02:42 +00005141 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005142
John McCall31168b02011-06-15 23:02:42 +00005143 case SK_PassByIndirectCopyRestore:
5144 case SK_PassByIndirectRestore:
5145 checkIndirectCopyRestoreSource(S, CurInit.get());
5146 CurInit = S.Owned(new (S.Context)
5147 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5148 Step->Kind == SK_PassByIndirectCopyRestore));
5149 break;
5150
5151 case SK_ProduceObjCObject:
5152 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005153 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005154 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005155 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005156
5157 case SK_StdInitializerList: {
5158 QualType Dest = Step->Type;
5159 QualType E;
5160 bool Success = S.isStdInitializerList(Dest, &E);
5161 (void)Success;
5162 assert(Success && "Destination type changed?");
5163 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5164 unsigned NumInits = ILE->getNumInits();
5165 SmallVector<Expr*, 16> Converted(NumInits);
5166 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5167 S.Context.getConstantArrayType(E,
5168 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5169 NumInits),
5170 ArrayType::Normal, 0));
5171 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5172 0, HiddenArray);
5173 for (unsigned i = 0; i < NumInits; ++i) {
5174 Element.setElementIndex(i);
5175 ExprResult Init = S.Owned(ILE->getInit(i));
5176 ExprResult Res = S.PerformCopyInitialization(Element,
5177 Init.get()->getExprLoc(),
5178 Init);
5179 assert(!Res.isInvalid() && "Result changed since try phase.");
5180 Converted[i] = Res.take();
5181 }
5182 InitListExpr *Semantic = new (S.Context)
5183 InitListExpr(S.Context, ILE->getLBraceLoc(),
5184 Converted.data(), NumInits, ILE->getRBraceLoc());
5185 Semantic->setSyntacticForm(ILE);
5186 Semantic->setType(Dest);
5187 CurInit = S.Owned(Semantic);
5188 break;
5189 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005190 }
5191 }
John McCall1f425642010-11-11 03:21:53 +00005192
5193 // Diagnose non-fatal problems with the completed initialization.
5194 if (Entity.getKind() == InitializedEntity::EK_Member &&
5195 cast<FieldDecl>(Entity.getDecl())->isBitField())
5196 S.CheckBitFieldInitialization(Kind.getLocation(),
5197 cast<FieldDecl>(Entity.getDecl()),
5198 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005200 return move(CurInit);
5201}
5202
5203//===----------------------------------------------------------------------===//
5204// Diagnose initialization failures
5205//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005207 const InitializedEntity &Entity,
5208 const InitializationKind &Kind,
5209 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005210 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005211 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Douglas Gregor1b303932009-12-22 15:35:07 +00005213 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005214 switch (Failure) {
5215 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005216 // FIXME: Customize for the initialized entity?
5217 if (NumArgs == 0)
5218 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5219 << DestType.getNonReferenceType();
5220 else // FIXME: diagnostic below could be better!
5221 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5222 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005223 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005225 case FK_ArrayNeedsInitList:
5226 case FK_ArrayNeedsInitListOrStringLiteral:
5227 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5228 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5229 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
Douglas Gregore2f943b2011-02-22 18:29:51 +00005231 case FK_ArrayTypeMismatch:
5232 case FK_NonConstantArrayInit:
5233 S.Diag(Kind.getLocation(),
5234 (Failure == FK_ArrayTypeMismatch
5235 ? diag::err_array_init_different_type
5236 : diag::err_array_init_non_constant_array))
5237 << DestType.getNonReferenceType()
5238 << Args[0]->getType()
5239 << Args[0]->getSourceRange();
5240 break;
5241
John McCalla59dc2f2012-01-05 00:13:19 +00005242 case FK_VariableLengthArrayHasInitializer:
5243 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5244 << Args[0]->getSourceRange();
5245 break;
5246
John McCall16df1e52010-03-30 21:47:33 +00005247 case FK_AddressOfOverloadFailed: {
5248 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005250 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005251 true,
5252 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005253 break;
John McCall16df1e52010-03-30 21:47:33 +00005254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005256 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005257 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005258 switch (FailedOverloadResult) {
5259 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005260 if (Failure == FK_UserConversionOverloadFailed)
5261 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5262 << Args[0]->getType() << DestType
5263 << Args[0]->getSourceRange();
5264 else
5265 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5266 << DestType << Args[0]->getType()
5267 << Args[0]->getSourceRange();
5268
John McCall5c32be02010-08-24 20:38:10 +00005269 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005272 case OR_No_Viable_Function:
5273 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5274 << Args[0]->getType() << DestType.getNonReferenceType()
5275 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005276 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005279 case OR_Deleted: {
5280 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5281 << Args[0]->getType() << DestType.getNonReferenceType()
5282 << Args[0]->getSourceRange();
5283 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005284 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005285 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5286 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005287 if (Ovl == OR_Deleted) {
5288 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005289 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005290 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005291 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005292 }
5293 break;
5294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005296 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005297 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298 }
5299 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005301 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005302 if (isa<InitListExpr>(Args[0])) {
5303 S.Diag(Kind.getLocation(),
5304 diag::err_lvalue_reference_bind_to_initlist)
5305 << DestType.getNonReferenceType().isVolatileQualified()
5306 << DestType.getNonReferenceType()
5307 << Args[0]->getSourceRange();
5308 break;
5309 }
5310 // Intentional fallthrough
5311
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005314 Failure == FK_NonConstLValueReferenceBindingToTemporary
5315 ? diag::err_lvalue_reference_bind_to_temporary
5316 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005317 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005318 << DestType.getNonReferenceType()
5319 << Args[0]->getType()
5320 << Args[0]->getSourceRange();
5321 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 case FK_RValueReferenceBindingToLValue:
5324 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005325 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005326 << Args[0]->getSourceRange();
5327 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005329 case FK_ReferenceInitDropsQualifiers:
5330 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5331 << DestType.getNonReferenceType()
5332 << Args[0]->getType()
5333 << Args[0]->getSourceRange();
5334 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005335
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005336 case FK_ReferenceInitFailed:
5337 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5338 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005339 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005340 << Args[0]->getType()
5341 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005342 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5343 Args[0]->getType()->isObjCObjectPointerType())
5344 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005345 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregorb491ed32011-02-19 21:32:49 +00005347 case FK_ConversionFailed: {
5348 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005349 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005350 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005351 << DestType
John McCall086a4642010-11-24 05:12:34 +00005352 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005353 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005354 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005355 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5356 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005357 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5358 Args[0]->getType()->isObjCObjectPointerType())
5359 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005360 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005361 }
John Wiegley01296292011-04-08 18:41:53 +00005362
5363 case FK_ConversionFromPropertyFailed:
5364 // No-op. This error has already been reported.
5365 break;
5366
Douglas Gregor51e77d52009-12-10 17:56:55 +00005367 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005368 SourceRange R;
5369
5370 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005371 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005372 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005374 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005375
Douglas Gregor8ec51732010-09-08 21:40:08 +00005376 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5377 if (Kind.isCStyleOrFunctionalCast())
5378 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5379 << R;
5380 else
5381 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5382 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005383 break;
5384 }
5385
5386 case FK_ReferenceBindingToInitList:
5387 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5388 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5389 break;
5390
5391 case FK_InitListBadDestinationType:
5392 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5393 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005395
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005396 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005397 case FK_ConstructorOverloadFailed: {
5398 SourceRange ArgsRange;
5399 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005400 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005401 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005402
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005403 if (Failure == FK_ListConstructorOverloadFailed) {
5404 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5405 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5406 Args = InitList->getInits();
5407 NumArgs = InitList->getNumInits();
5408 }
5409
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005410 // FIXME: Using "DestType" for the entity we're printing is probably
5411 // bad.
5412 switch (FailedOverloadResult) {
5413 case OR_Ambiguous:
5414 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5415 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005416 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5417 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005420 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005421 if (Kind.getKind() == InitializationKind::IK_Default &&
5422 (Entity.getKind() == InitializedEntity::EK_Base ||
5423 Entity.getKind() == InitializedEntity::EK_Member) &&
5424 isa<CXXConstructorDecl>(S.CurContext)) {
5425 // This is implicit default initialization of a member or
5426 // base within a constructor. If no viable function was
5427 // found, notify the user that she needs to explicitly
5428 // initialize this base/member.
5429 CXXConstructorDecl *Constructor
5430 = cast<CXXConstructorDecl>(S.CurContext);
5431 if (Entity.getKind() == InitializedEntity::EK_Base) {
5432 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5433 << Constructor->isImplicit()
5434 << S.Context.getTypeDeclType(Constructor->getParent())
5435 << /*base=*/0
5436 << Entity.getType();
5437
5438 RecordDecl *BaseDecl
5439 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5440 ->getDecl();
5441 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5442 << S.Context.getTagDeclType(BaseDecl);
5443 } else {
5444 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5445 << Constructor->isImplicit()
5446 << S.Context.getTypeDeclType(Constructor->getParent())
5447 << /*member=*/1
5448 << Entity.getName();
5449 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5450
5451 if (const RecordType *Record
5452 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005454 diag::note_previous_decl)
5455 << S.Context.getTagDeclType(Record->getDecl());
5456 }
5457 break;
5458 }
5459
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005460 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5461 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005462 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005465 case OR_Deleted: {
5466 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5467 << true << DestType << ArgsRange;
5468 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005469 OverloadingResult Ovl
5470 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005471 if (Ovl == OR_Deleted) {
5472 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005473 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005474 } else {
5475 llvm_unreachable("Inconsistent overload resolution?");
5476 }
5477 break;
5478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005480 case OR_Success:
5481 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005482 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005483 }
David Blaikie60deeee2012-01-17 08:24:58 +00005484 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
Douglas Gregor85dabae2009-12-16 01:38:02 +00005486 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005487 if (Entity.getKind() == InitializedEntity::EK_Member &&
5488 isa<CXXConstructorDecl>(S.CurContext)) {
5489 // This is implicit default-initialization of a const member in
5490 // a constructor. Complain that it needs to be explicitly
5491 // initialized.
5492 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5493 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5494 << Constructor->isImplicit()
5495 << S.Context.getTypeDeclType(Constructor->getParent())
5496 << /*const=*/1
5497 << Entity.getName();
5498 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5499 << Entity.getName();
5500 } else {
5501 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5502 << DestType << (bool)DestType->getAs<RecordType>();
5503 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005504 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005506 case FK_Incomplete:
5507 S.RequireCompleteType(Kind.getLocation(), DestType,
5508 diag::err_init_incomplete_type);
5509 break;
5510
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005511 case FK_ListInitializationFailed: {
5512 // Run the init list checker again to emit diagnostics.
5513 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5514 QualType DestType = Entity.getType();
5515 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005516 DestType, /*VerifyOnly=*/false,
5517 Kind.getKind() != InitializationKind::IK_Direct ||
5518 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005519 assert(DiagnoseInitList.HadError() &&
5520 "Inconsistent init list check result.");
5521 break;
5522 }
John McCall4124c492011-10-17 18:40:02 +00005523
5524 case FK_PlaceholderType: {
5525 // FIXME: Already diagnosed!
5526 break;
5527 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005528
5529 case FK_InitListElementCopyFailure: {
5530 // Try to perform all copies again.
5531 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5532 unsigned NumInits = InitList->getNumInits();
5533 QualType DestType = Entity.getType();
5534 QualType E;
5535 bool Success = S.isStdInitializerList(DestType, &E);
5536 (void)Success;
5537 assert(Success && "Where did the std::initializer_list go?");
5538 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5539 S.Context.getConstantArrayType(E,
5540 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5541 NumInits),
5542 ArrayType::Normal, 0));
5543 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5544 0, HiddenArray);
5545 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5546 // where the init list type is wrong, e.g.
5547 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5548 // FIXME: Emit a note if we hit the limit?
5549 int ErrorCount = 0;
5550 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5551 Element.setElementIndex(i);
5552 ExprResult Init = S.Owned(InitList->getInit(i));
5553 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5554 .isInvalid())
5555 ++ErrorCount;
5556 }
5557 break;
5558 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005561 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005562 return true;
5563}
Douglas Gregore1314a62009-12-18 05:02:21 +00005564
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005565void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005566 switch (SequenceKind) {
5567 case FailedSequence: {
5568 OS << "Failed sequence: ";
5569 switch (Failure) {
5570 case FK_TooManyInitsForReference:
5571 OS << "too many initializers for reference";
5572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005574 case FK_ArrayNeedsInitList:
5575 OS << "array requires initializer list";
5576 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005578 case FK_ArrayNeedsInitListOrStringLiteral:
5579 OS << "array requires initializer list or string literal";
5580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Douglas Gregore2f943b2011-02-22 18:29:51 +00005582 case FK_ArrayTypeMismatch:
5583 OS << "array type mismatch";
5584 break;
5585
5586 case FK_NonConstantArrayInit:
5587 OS << "non-constant array initializer";
5588 break;
5589
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005590 case FK_AddressOfOverloadFailed:
5591 OS << "address of overloaded function failed";
5592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005594 case FK_ReferenceInitOverloadFailed:
5595 OS << "overload resolution for reference initialization failed";
5596 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005597
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005598 case FK_NonConstLValueReferenceBindingToTemporary:
5599 OS << "non-const lvalue reference bound to temporary";
5600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005602 case FK_NonConstLValueReferenceBindingToUnrelated:
5603 OS << "non-const lvalue reference bound to unrelated type";
5604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005606 case FK_RValueReferenceBindingToLValue:
5607 OS << "rvalue reference bound to an lvalue";
5608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005610 case FK_ReferenceInitDropsQualifiers:
5611 OS << "reference initialization drops qualifiers";
5612 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005614 case FK_ReferenceInitFailed:
5615 OS << "reference initialization failed";
5616 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005618 case FK_ConversionFailed:
5619 OS << "conversion failed";
5620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
John Wiegley01296292011-04-08 18:41:53 +00005622 case FK_ConversionFromPropertyFailed:
5623 OS << "conversion from property failed";
5624 break;
5625
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005626 case FK_TooManyInitsForScalar:
5627 OS << "too many initializers for scalar";
5628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005630 case FK_ReferenceBindingToInitList:
5631 OS << "referencing binding to initializer list";
5632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005634 case FK_InitListBadDestinationType:
5635 OS << "initializer list for non-aggregate, non-scalar type";
5636 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005638 case FK_UserConversionOverloadFailed:
5639 OS << "overloading failed for user-defined conversion";
5640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005642 case FK_ConstructorOverloadFailed:
5643 OS << "constructor overloading failed";
5644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005646 case FK_DefaultInitOfConst:
5647 OS << "default initialization of a const variable";
5648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005650 case FK_Incomplete:
5651 OS << "initialization of incomplete type";
5652 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005653
5654 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005655 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005656 break;
5657
John McCalla59dc2f2012-01-05 00:13:19 +00005658 case FK_VariableLengthArrayHasInitializer:
5659 OS << "variable length array has an initializer";
5660 break;
5661
John McCall4124c492011-10-17 18:40:02 +00005662 case FK_PlaceholderType:
5663 OS << "initializer expression isn't contextually valid";
5664 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005665
5666 case FK_ListConstructorOverloadFailed:
5667 OS << "list constructor overloading failed";
5668 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005669
5670 case FK_InitListElementCopyFailure:
5671 OS << "copy construction of initializer list element failed";
5672 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005674 OS << '\n';
5675 return;
5676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005678 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005679 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005680 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005681
Sebastian Redld201edf2011-06-05 13:59:11 +00005682 case NormalSequence:
5683 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005684 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005687 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5688 if (S != step_begin()) {
5689 OS << " -> ";
5690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005692 switch (S->Kind) {
5693 case SK_ResolveAddressOfOverloadedFunction:
5694 OS << "resolve address of overloaded function";
5695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005697 case SK_CastDerivedToBaseRValue:
5698 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5699 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005700
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005701 case SK_CastDerivedToBaseXValue:
5702 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5703 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005705 case SK_CastDerivedToBaseLValue:
5706 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5707 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005709 case SK_BindReference:
5710 OS << "bind reference to lvalue";
5711 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005713 case SK_BindReferenceToTemporary:
5714 OS << "bind reference to a temporary";
5715 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005716
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005717 case SK_ExtraneousCopyToTemporary:
5718 OS << "extraneous C++03 copy to temporary";
5719 break;
5720
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005721 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005722 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005723 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005724
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005725 case SK_QualificationConversionRValue:
5726 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005727 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005728
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005729 case SK_QualificationConversionXValue:
5730 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005731 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005732
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005733 case SK_QualificationConversionLValue:
5734 OS << "qualification conversion (lvalue)";
5735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005737 case SK_ConversionSequence:
5738 OS << "implicit conversion sequence (";
5739 S->ICS->DebugPrint(); // FIXME: use OS
5740 OS << ")";
5741 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005743 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005744 OS << "list aggregate initialization";
5745 break;
5746
5747 case SK_ListConstructorCall:
5748 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
Sebastian Redl29526f02011-11-27 16:50:07 +00005751 case SK_UnwrapInitList:
5752 OS << "unwrap reference initializer list";
5753 break;
5754
5755 case SK_RewrapInitList:
5756 OS << "rewrap reference initializer list";
5757 break;
5758
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005759 case SK_ConstructorInitialization:
5760 OS << "constructor initialization";
5761 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005762
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005763 case SK_ZeroInitialization:
5764 OS << "zero initialization";
5765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005767 case SK_CAssignment:
5768 OS << "C assignment";
5769 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005771 case SK_StringInit:
5772 OS << "string initialization";
5773 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005774
5775 case SK_ObjCObjectConversion:
5776 OS << "Objective-C object conversion";
5777 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005778
5779 case SK_ArrayInit:
5780 OS << "array initialization";
5781 break;
John McCall31168b02011-06-15 23:02:42 +00005782
5783 case SK_PassByIndirectCopyRestore:
5784 OS << "pass by indirect copy and restore";
5785 break;
5786
5787 case SK_PassByIndirectRestore:
5788 OS << "pass by indirect restore";
5789 break;
5790
5791 case SK_ProduceObjCObject:
5792 OS << "Objective-C object retension";
5793 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005794
5795 case SK_StdInitializerList:
5796 OS << "std::initializer_list from initializer list";
5797 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005798 }
5799 }
5800}
5801
5802void InitializationSequence::dump() const {
5803 dump(llvm::errs());
5804}
5805
Richard Smith66e05fe2012-01-18 05:21:49 +00005806static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5807 QualType EntityType,
5808 const Expr *PreInit,
5809 const Expr *PostInit) {
5810 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5811 return;
5812
5813 // A narrowing conversion can only appear as the final implicit conversion in
5814 // an initialization sequence.
5815 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5816 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5817 return;
5818
5819 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5820 const StandardConversionSequence *SCS = 0;
5821 switch (ICS.getKind()) {
5822 case ImplicitConversionSequence::StandardConversion:
5823 SCS = &ICS.Standard;
5824 break;
5825 case ImplicitConversionSequence::UserDefinedConversion:
5826 SCS = &ICS.UserDefined.After;
5827 break;
5828 case ImplicitConversionSequence::AmbiguousConversion:
5829 case ImplicitConversionSequence::EllipsisConversion:
5830 case ImplicitConversionSequence::BadConversion:
5831 return;
5832 }
5833
5834 // Determine the type prior to the narrowing conversion. If a conversion
5835 // operator was used, this may be different from both the type of the entity
5836 // and of the pre-initialization expression.
5837 QualType PreNarrowingType = PreInit->getType();
5838 if (Seq.step_begin() + 1 != Seq.step_end())
5839 PreNarrowingType = Seq.step_end()[-2].Type;
5840
5841 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5842 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005843 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005844 case NK_Not_Narrowing:
5845 // No narrowing occurred.
5846 return;
5847
5848 case NK_Type_Narrowing:
5849 // This was a floating-to-integer conversion, which is always considered a
5850 // narrowing conversion even if the value is a constant and can be
5851 // represented exactly as an integer.
5852 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005853 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5854 diag::warn_init_list_type_narrowing
5855 : S.isSFINAEContext()?
5856 diag::err_init_list_type_narrowing_sfinae
5857 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005858 << PostInit->getSourceRange()
5859 << PreNarrowingType.getLocalUnqualifiedType()
5860 << EntityType.getLocalUnqualifiedType();
5861 break;
5862
5863 case NK_Constant_Narrowing:
5864 // A constant value was narrowed.
5865 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005866 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5867 diag::warn_init_list_constant_narrowing
5868 : S.isSFINAEContext()?
5869 diag::err_init_list_constant_narrowing_sfinae
5870 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005871 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005872 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005873 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005874 break;
5875
5876 case NK_Variable_Narrowing:
5877 // A variable's value may have been narrowed.
5878 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005879 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5880 diag::warn_init_list_variable_narrowing
5881 : S.isSFINAEContext()?
5882 diag::err_init_list_variable_narrowing_sfinae
5883 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005884 << PostInit->getSourceRange()
5885 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005886 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005887 break;
5888 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005889
5890 llvm::SmallString<128> StaticCast;
5891 llvm::raw_svector_ostream OS(StaticCast);
5892 OS << "static_cast<";
5893 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5894 // It's important to use the typedef's name if there is one so that the
5895 // fixit doesn't break code using types like int64_t.
5896 //
5897 // FIXME: This will break if the typedef requires qualification. But
5898 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005899 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005900 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5901 OS << BT->getName(S.getLangOptions());
5902 else {
5903 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5904 // with a broken cast.
5905 return;
5906 }
5907 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005908 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5909 << PostInit->getSourceRange()
5910 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005911 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005912 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005913}
5914
Douglas Gregore1314a62009-12-18 05:02:21 +00005915//===----------------------------------------------------------------------===//
5916// Initialization helper functions
5917//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005918bool
5919Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5920 ExprResult Init) {
5921 if (Init.isInvalid())
5922 return false;
5923
5924 Expr *InitE = Init.get();
5925 assert(InitE && "No initialization expression");
5926
5927 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5928 SourceLocation());
5929 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005930 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005931}
5932
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005934Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5935 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005936 ExprResult Init,
5937 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005938 if (Init.isInvalid())
5939 return ExprError();
5940
John McCall1f425642010-11-11 03:21:53 +00005941 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005942 assert(InitE && "No initialization expression?");
5943
5944 if (EqualLoc.isInvalid())
5945 EqualLoc = InitE->getLocStart();
5946
5947 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5948 EqualLoc);
5949 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5950 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005951
Richard Smith66e05fe2012-01-18 05:21:49 +00005952 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5953
5954 if (!Result.isInvalid() && TopLevelOfInitList)
5955 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5956 InitE, Result.get());
5957
5958 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00005959}