blob: 3c942fa40ed6fc7804045c9457fcd22971021bef [file] [log] [blame]
Steve Naroff0cca7492008-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 Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-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 Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-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 Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-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 McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +000095 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Richard Smithbebf5b12013-04-26 14:36:30 +0000100 Str->setType(DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-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.
David Blaikie4e4d0842012-03-11 07:00:24 +0000109 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-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 Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000121 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000122 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())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000127 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-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 Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000176 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000177 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman0c706c22011-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 Carlsson8ff9e862010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000253
Douglas Gregord6d37de2009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000264public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000275
Sebastian Redl3ff5c862011-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 Gregord6d37de2009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000292 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000297 // If there's no explicit initializer but we have a default initializer, use
298 // that. This only happens in C++1y, since classes with default
299 // initializers are not aggregates in C++11.
300 if (Field->hasInClassInitializer()) {
301 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
302 ILE->getRBraceLoc(), Field);
303 if (Init < NumInits)
304 ILE->setInit(Init, DIE);
305 else {
306 ILE->updateInit(SemaRef.Context, Init, DIE);
307 RequiresSecondPass = true;
308 }
309 return;
310 }
311
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312 // FIXME: We probably don't need to handle references
313 // specially here, since value-initialization of references is
314 // handled in InitializationSequence.
315 if (Field->getType()->isReferenceType()) {
316 // C++ [dcl.init.aggr]p9:
317 // If an incomplete or empty initializer-list leaves a
318 // member of reference type uninitialized, the program is
319 // ill-formed.
320 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
321 << Field->getType()
322 << ILE->getSyntacticForm()->getSourceRange();
323 SemaRef.Diag(Field->getLocation(),
324 diag::note_uninit_reference_member);
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
330 true);
331 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
332 if (!InitSeq) {
333 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
334 hadError = true;
335 return;
336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000337
John McCall60d7b3a2010-08-24 06:29:42 +0000338 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000339 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (MemberInit.isInvalid()) {
341 hadError = true;
342 return;
343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345 if (hadError) {
346 // Do nothing
347 } else if (Init < NumInits) {
348 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000349 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000350 // Value-initialization requires a constructor call, so
351 // extend the initializer list to include the constructor
352 // call and make a note that we'll need to take another pass
353 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000354 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355 RequiresSecondPass = true;
356 }
357 } else if (InitListExpr *InnerILE
358 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359 FillInValueInitializations(MemberEntity, InnerILE,
360 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361}
362
Douglas Gregor4c678342009-01-28 21:54:33 +0000363/// Recursively replaces NULL values within the given initializer list
364/// with expressions that perform value-initialization of the
365/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000366void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
368 InitListExpr *ILE,
369 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000370 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000371 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000372 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000374 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Ted Kremenek6217b802009-07-29 21:53:49 +0000376 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000377 const RecordDecl *RDecl = RType->getDecl();
378 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000379 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
380 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000381 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
382 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
383 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
384 FieldEnd = RDecl->field_end();
385 Field != FieldEnd; ++Field) {
386 if (Field->hasInClassInitializer()) {
387 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
388 break;
389 }
390 }
391 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000392 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000393 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
394 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000395 Field != FieldEnd; ++Field) {
396 if (Field->isUnnamedBitfield())
397 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000398
Douglas Gregord6d37de2009-12-22 00:05:34 +0000399 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000400 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000401
David Blaikie581deb32012-06-06 20:45:41 +0000402 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000403 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000404 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405
Douglas Gregord6d37de2009-12-22 00:05:34 +0000406 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407
Douglas Gregord6d37de2009-12-22 00:05:34 +0000408 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000409 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000410 break;
411 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000412 }
413
414 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000415 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000416
417 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000420 unsigned NumInits = ILE->getNumInits();
421 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000422 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000423 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000424 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
425 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000426 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000427 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000428 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000429 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000430 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000432 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000433 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000434 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000435
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000436
Douglas Gregor87fd7032009-02-02 17:43:21 +0000437 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000438 if (hadError)
439 return;
440
Anders Carlssond3d824d2010-01-23 04:34:47 +0000441 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
442 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000443 ElementEntity.setElementIndex(Init);
444
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000445 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
446 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
448 true);
449 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
450 if (!InitSeq) {
451 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000452 hadError = true;
453 return;
454 }
455
John McCall60d7b3a2010-08-24 06:29:42 +0000456 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000457 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000458 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000459 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000460 return;
461 }
462
463 if (hadError) {
464 // Do nothing
465 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000466 // For arrays, just set the expression used for value-initialization
467 // of the "holes" in the array.
468 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
469 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
470 else
471 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000472 } else {
473 // For arrays, just set the expression used for value-initialization
474 // of the rest of elements and exit.
475 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
476 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
477 return;
478 }
479
Sebastian Redl7491c492011-06-05 13:59:11 +0000480 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000481 // Value-initialization requires a constructor call, so
482 // extend the initializer list to include the constructor
483 // call and make a note that we'll need to take another pass
484 // through the initializer list.
485 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
486 RequiresSecondPass = true;
487 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000488 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000489 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000490 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000491 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 }
493}
494
Chris Lattner68355a52009-01-29 05:10:57 +0000495
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000496InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000497 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000498 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000499 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000501
Eli Friedmanb85f7072008-05-19 19:16:24 +0000502 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000504 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000505 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000506 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000507 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000508 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000509
Sebastian Redl14b0c192011-09-24 17:48:00 +0000510 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000511 bool RequiresSecondPass = false;
512 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000513 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000514 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000515 RequiresSecondPass);
516 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
519int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000520 // FIXME: use a proper constant
521 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000522 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000523 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
525 }
526 return maxElements;
527}
528
529int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000530 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000531 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000532 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000533 Field = structDecl->field_begin(),
534 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000535 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000536 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000537 ++InitializableMembers;
538 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000539 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000540 return std::min(InitializableMembers, 1);
541 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000542}
543
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000544void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000545 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000546 QualType T, unsigned &Index,
547 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000548 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000549 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Steve Naroff0cca7492008-05-01 22:18:59 +0000551 if (T->isArrayType())
552 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000553 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000554 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000555 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000556 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000557 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000558 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000559
Eli Friedman402256f2008-05-25 13:49:22 +0000560 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000561 if (!VerifyOnly)
562 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
563 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000565 hadError = true;
566 return;
567 }
568
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 // Build a structured initializer list corresponding to this subobject.
570 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000571 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
572 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000573 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000574 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000576
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000578 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000580 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000581 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000582 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000583
584 if (VerifyOnly) {
585 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
586 hadError = true;
587 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000589
Sebastian Redlc2235182011-10-16 18:19:28 +0000590 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000591 // Update the structured sub-object initializer so that it's ending
592 // range corresponds with the end of the last initializer it used.
593 if (EndIndex < ParentIList->getNumInits()) {
594 SourceLocation EndLoc
595 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
596 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Sebastian Redlc2235182011-10-16 18:19:28 +0000599 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000600 if (T->isArrayType() || T->isRecordType()) {
601 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000602 AllowBraceElision ? diag::warn_missing_braces :
603 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000604 << StructuredSubobjectInitList->getSourceRange()
605 << FixItHint::CreateInsertion(
606 StructuredSubobjectInitList->getLocStart(), "{")
607 << FixItHint::CreateInsertion(
608 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000610 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000611 if (!AllowBraceElision)
612 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000613 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000614 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000615}
616
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000617void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000618 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000619 unsigned &Index,
620 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000621 unsigned &StructuredIndex,
622 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000623 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000624 if (!VerifyOnly) {
625 SyntacticToSemantic[IList] = StructuredList;
626 StructuredList->setSyntacticForm(IList);
627 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000630 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000631 QualType ExprTy = T;
632 if (!ExprTy->isArrayType())
633 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000634 IList->setType(ExprTy);
635 StructuredList->setType(ExprTy);
636 }
Eli Friedman638e1442008-05-25 13:22:35 +0000637 if (hadError)
638 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000639
Eli Friedman638e1442008-05-25 13:22:35 +0000640 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000641 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000642 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000643 if (SemaRef.getLangOpts().CPlusPlus ||
644 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000645 IList->getType()->isVectorType())) {
646 hadError = true;
647 }
648 return;
649 }
650
Eli Friedmane5408582009-05-29 20:20:05 +0000651 if (StructuredIndex == 1 &&
652 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000653 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000654 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000655 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000656 hadError = true;
657 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000658 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000659 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000660 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000661 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000662 // Don't complain for incomplete types, since we'll get an error
663 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000664 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000665 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000666 CurrentObjectType->isArrayType()? 0 :
667 CurrentObjectType->isVectorType()? 1 :
668 CurrentObjectType->isScalarType()? 2 :
669 CurrentObjectType->isUnionType()? 3 :
670 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000671
672 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000673 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000674 DK = diag::err_excess_initializers;
675 hadError = true;
676 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000677 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000678 DK = diag::err_excess_initializers;
679 hadError = true;
680 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000681
Chris Lattner08202542009-02-24 22:50:46 +0000682 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000683 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 }
685 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000686
Sebastian Redl14b0c192011-09-24 17:48:00 +0000687 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
688 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000689 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000690 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000691 << FixItHint::CreateRemoval(IList->getLocStart())
692 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000693}
694
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000695void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000697 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000698 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000699 unsigned &Index,
700 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000701 unsigned &StructuredIndex,
702 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000703 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
704 // Explicitly braced initializer for complex type can be real+imaginary
705 // parts.
706 CheckComplexType(Entity, IList, DeclType, Index,
707 StructuredList, StructuredIndex);
708 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000709 CheckScalarType(Entity, IList, DeclType, Index,
710 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000711 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000713 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000714 } else if (DeclType->isRecordType()) {
715 assert(DeclType->isAggregateType() &&
716 "non-aggregate records should be handed in CheckSubElementType");
717 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
718 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
719 SubobjectIsDesignatorContext, Index,
720 StructuredList, StructuredIndex,
721 TopLevelObject);
722 } else if (DeclType->isArrayType()) {
723 llvm::APSInt Zero(
724 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
725 false);
726 CheckArrayType(Entity, IList, DeclType, Zero,
727 SubobjectIsDesignatorContext, Index,
728 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000729 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
730 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000731 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000732 if (!VerifyOnly)
733 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
734 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000735 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000737 CheckReferenceType(Entity, IList, DeclType, Index,
738 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000739 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000740 if (!VerifyOnly)
741 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
742 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000743 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000744 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000745 if (!VerifyOnly)
746 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
747 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000748 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000749 }
750}
751
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000752void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000753 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000754 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 unsigned &Index,
756 InitListExpr *StructuredList,
757 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000758 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000759 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000760 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
761 unsigned newIndex = 0;
762 unsigned newStructuredIndex = 0;
763 InitListExpr *newStructuredList
764 = getStructuredSubobjectInit(IList, Index, ElemType,
765 StructuredList, StructuredIndex,
766 SubInitList->getSourceRange());
767 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
768 newStructuredList, newStructuredIndex);
769 ++StructuredIndex;
770 ++Index;
771 return;
772 }
773 assert(SemaRef.getLangOpts().CPlusPlus &&
774 "non-aggregate records are only possible in C++");
775 // C++ initialization is handled later.
776 }
777
778 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000779 return CheckScalarType(Entity, IList, ElemType, Index,
780 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000781 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000782 return CheckReferenceType(Entity, IList, ElemType, Index,
783 StructuredList, StructuredIndex);
784 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000785
John McCallfef8b342011-02-21 07:57:55 +0000786 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
787 // arrayType can be incomplete if we're initializing a flexible
788 // array member. There's nothing we can do with the completed
789 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000790
John McCallfef8b342011-02-21 07:57:55 +0000791 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000792 if (!VerifyOnly) {
793 CheckStringInit(Str, ElemType, arrayType, SemaRef);
794 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
795 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000796 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000797 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000798 }
John McCallfef8b342011-02-21 07:57:55 +0000799
800 // Fall through for subaggregate initialization.
801
David Blaikie4e4d0842012-03-11 07:00:24 +0000802 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000803 // C++ [dcl.init.aggr]p12:
804 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000805 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000806 // an initializer-list. If the initializer can initialize a
807 // member, the member is initialized. [...]
808
809 // FIXME: Better EqualLoc?
810 InitializationKind Kind =
811 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
812 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
813
814 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000815 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000816 ExprResult Result =
817 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
818 if (Result.isInvalid())
819 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000820
Sebastian Redl14b0c192011-09-24 17:48:00 +0000821 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000822 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000823 }
John McCallfef8b342011-02-21 07:57:55 +0000824 ++Index;
825 return;
826 }
827
828 // Fall through for subaggregate initialization
829 } else {
830 // C99 6.7.8p13:
831 //
832 // The initializer for a structure or union object that has
833 // automatic storage duration shall be either an initializer
834 // list as described below, or a single expression that has
835 // compatible structure or union type. In the latter case, the
836 // initial value of the object, including unnamed members, is
837 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000838 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000839 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000840 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
841 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000842 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000843 if (ExprRes.isInvalid())
844 hadError = true;
845 else {
846 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
847 if (ExprRes.isInvalid())
848 hadError = true;
849 }
850 UpdateStructuredListElement(StructuredList, StructuredIndex,
851 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000852 ++Index;
853 return;
854 }
John Wiegley429bb272011-04-08 18:41:53 +0000855 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000856 // Fall through for subaggregate initialization
857 }
858
859 // C++ [dcl.init.aggr]p12:
860 //
861 // [...] Otherwise, if the member is itself a non-empty
862 // subaggregate, brace elision is assumed and the initializer is
863 // considered for the initialization of the first member of
864 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000865 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000866 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000867 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
868 StructuredIndex);
869 ++StructuredIndex;
870 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000871 if (!VerifyOnly) {
872 // We cannot initialize this element, so let
873 // PerformCopyInitialization produce the appropriate diagnostic.
874 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
877 }
John McCallfef8b342011-02-21 07:57:55 +0000878 hadError = true;
879 ++Index;
880 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000881 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000882}
883
Eli Friedman0c706c22011-09-19 23:17:44 +0000884void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
885 InitListExpr *IList, QualType DeclType,
886 unsigned &Index,
887 InitListExpr *StructuredList,
888 unsigned &StructuredIndex) {
889 assert(Index == 0 && "Index in explicit init list must be zero");
890
891 // As an extension, clang supports complex initializers, which initialize
892 // a complex number component-wise. When an explicit initializer list for
893 // a complex number contains two two initializers, this extension kicks in:
894 // it exepcts the initializer list to contain two elements convertible to
895 // the element type of the complex type. The first element initializes
896 // the real part, and the second element intitializes the imaginary part.
897
898 if (IList->getNumInits() != 2)
899 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
900 StructuredIndex);
901
902 // This is an extension in C. (The builtin _Complex type does not exist
903 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000904 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000905 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
906 << IList->getSourceRange();
907
908 // Initialize the complex number.
909 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
910 InitializedEntity ElementEntity =
911 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
912
913 for (unsigned i = 0; i < 2; ++i) {
914 ElementEntity.setElementIndex(Index);
915 CheckSubElementType(ElementEntity, IList, elementType, Index,
916 StructuredList, StructuredIndex);
917 }
918}
919
920
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000921void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000922 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000923 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000924 InitListExpr *StructuredList,
925 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000926 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000927 if (!VerifyOnly)
928 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000929 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000930 diag::warn_cxx98_compat_empty_scalar_initializer :
931 diag::err_empty_scalar_initializer)
932 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000933 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000934 ++Index;
935 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000936 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000937 }
John McCallb934c2d2010-11-11 00:46:36 +0000938
939 Expr *expr = IList->getInit(Index);
940 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000941 if (!VerifyOnly)
942 SemaRef.Diag(SubIList->getLocStart(),
943 diag::warn_many_braces_around_scalar_init)
944 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000945
946 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
947 StructuredIndex);
948 return;
949 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000950 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000951 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000952 diag::err_designator_for_scalar_init)
953 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000954 hadError = true;
955 ++Index;
956 ++StructuredIndex;
957 return;
958 }
959
Sebastian Redl14b0c192011-09-24 17:48:00 +0000960 if (VerifyOnly) {
961 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
962 hadError = true;
963 ++Index;
964 return;
965 }
966
John McCallb934c2d2010-11-11 00:46:36 +0000967 ExprResult Result =
968 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000969 SemaRef.Owned(expr),
970 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000971
972 Expr *ResultExpr = 0;
973
974 if (Result.isInvalid())
975 hadError = true; // types weren't compatible.
976 else {
977 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
John McCallb934c2d2010-11-11 00:46:36 +0000979 if (ResultExpr != expr) {
980 // The type was promoted, update initializer list.
981 IList->setInit(Index, ResultExpr);
982 }
983 }
984 if (hadError)
985 ++StructuredIndex;
986 else
987 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
988 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000989}
990
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000991void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
992 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000993 unsigned &Index,
994 InitListExpr *StructuredList,
995 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000996 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000997 // FIXME: It would be wonderful if we could point at the actual member. In
998 // general, it would be useful to pass location information down the stack,
999 // so that we know the location (or decl) of the "current object" being
1000 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001001 if (!VerifyOnly)
1002 SemaRef.Diag(IList->getLocStart(),
1003 diag::err_init_reference_member_uninitialized)
1004 << DeclType
1005 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001006 hadError = true;
1007 ++Index;
1008 ++StructuredIndex;
1009 return;
1010 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001011
1012 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001013 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001014 if (!VerifyOnly)
1015 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1016 << DeclType << IList->getSourceRange();
1017 hadError = true;
1018 ++Index;
1019 ++StructuredIndex;
1020 return;
1021 }
1022
1023 if (VerifyOnly) {
1024 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1025 hadError = true;
1026 ++Index;
1027 return;
1028 }
1029
1030 ExprResult Result =
1031 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1032 SemaRef.Owned(expr),
1033 /*TopLevelOfInitList=*/true);
1034
1035 if (Result.isInvalid())
1036 hadError = true;
1037
1038 expr = Result.takeAs<Expr>();
1039 IList->setInit(Index, expr);
1040
1041 if (hadError)
1042 ++StructuredIndex;
1043 else
1044 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1045 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001046}
1047
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001048void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001049 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001050 unsigned &Index,
1051 InitListExpr *StructuredList,
1052 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001053 const VectorType *VT = DeclType->getAs<VectorType>();
1054 unsigned maxElements = VT->getNumElements();
1055 unsigned numEltsInit = 0;
1056 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001057
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001058 if (Index >= IList->getNumInits()) {
1059 // Make sure the element type can be value-initialized.
1060 if (VerifyOnly)
1061 CheckValueInitializable(
1062 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1063 return;
1064 }
1065
David Blaikie4e4d0842012-03-11 07:00:24 +00001066 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001067 // If the initializing element is a vector, try to copy-initialize
1068 // instead of breaking it apart (which is doomed to failure anyway).
1069 Expr *Init = IList->getInit(Index);
1070 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001071 if (VerifyOnly) {
1072 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1073 hadError = true;
1074 ++Index;
1075 return;
1076 }
1077
John McCall20e047a2010-10-30 00:11:39 +00001078 ExprResult Result =
1079 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001080 SemaRef.Owned(Init),
1081 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001082
1083 Expr *ResultExpr = 0;
1084 if (Result.isInvalid())
1085 hadError = true; // types weren't compatible.
1086 else {
1087 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 if (ResultExpr != Init) {
1090 // The type was promoted, update initializer list.
1091 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001092 }
1093 }
John McCall20e047a2010-10-30 00:11:39 +00001094 if (hadError)
1095 ++StructuredIndex;
1096 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001097 UpdateStructuredListElement(StructuredList, StructuredIndex,
1098 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001099 ++Index;
1100 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCall20e047a2010-10-30 00:11:39 +00001103 InitializedEntity ElementEntity =
1104 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105
John McCall20e047a2010-10-30 00:11:39 +00001106 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1107 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001108 if (Index >= IList->getNumInits()) {
1109 if (VerifyOnly)
1110 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001111 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001112 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001113
John McCall20e047a2010-10-30 00:11:39 +00001114 ElementEntity.setElementIndex(Index);
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 }
1118 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001119 }
John McCall20e047a2010-10-30 00:11:39 +00001120
1121 InitializedEntity ElementEntity =
1122 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001123
John McCall20e047a2010-10-30 00:11:39 +00001124 // OpenCL initializers allows vectors to be constructed from vectors.
1125 for (unsigned i = 0; i < maxElements; ++i) {
1126 // Don't attempt to go past the end of the init list
1127 if (Index >= IList->getNumInits())
1128 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001129
John McCall20e047a2010-10-30 00:11:39 +00001130 ElementEntity.setElementIndex(Index);
1131
1132 QualType IType = IList->getInit(Index)->getType();
1133 if (!IType->isVectorType()) {
1134 CheckSubElementType(ElementEntity, IList, elementType, Index,
1135 StructuredList, StructuredIndex);
1136 ++numEltsInit;
1137 } else {
1138 QualType VecType;
1139 const VectorType *IVT = IType->getAs<VectorType>();
1140 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001141
John McCall20e047a2010-10-30 00:11:39 +00001142 if (IType->isExtVectorType())
1143 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1144 else
1145 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001146 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001147 CheckSubElementType(ElementEntity, IList, VecType, Index,
1148 StructuredList, StructuredIndex);
1149 numEltsInit += numIElts;
1150 }
1151 }
1152
1153 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001154 if (numEltsInit != maxElements) {
1155 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001156 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001157 diag::err_vector_incorrect_num_initializers)
1158 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1159 hadError = true;
1160 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001161}
1162
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001163void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001164 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001165 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001166 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001167 unsigned &Index,
1168 InitListExpr *StructuredList,
1169 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001170 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1171
Steve Naroff0cca7492008-05-01 22:18:59 +00001172 // Check for the special-case of initializing an array with a string.
1173 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001174 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001175 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001176 // We place the string literal directly into the resulting
1177 // initializer list. This is the only place where the structure
1178 // of the structured initializer list doesn't match exactly,
1179 // because doing so would involve allocating one character
1180 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001181 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001182 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001183 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1184 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1185 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001186 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001187 return;
1188 }
1189 }
John McCallce6c9b72011-02-21 07:22:22 +00001190 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001191 // Check for VLAs; in standard C it would be possible to check this
1192 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1193 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001194 if (!VerifyOnly)
1195 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1196 diag::err_variable_object_no_init)
1197 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001198 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001199 ++Index;
1200 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001201 return;
1202 }
1203
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001205 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1206 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001207 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001208 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001209 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001210 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001211 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001212 maxElementsKnown = true;
1213 }
1214
John McCallce6c9b72011-02-21 07:22:22 +00001215 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001216 while (Index < IList->getNumInits()) {
1217 Expr *Init = IList->getInit(Index);
1218 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001219 // If we're not the subobject that matches up with the '{' for
1220 // the designator, we shouldn't be handling the
1221 // designator. Return immediately.
1222 if (!SubobjectIsDesignatorContext)
1223 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001224
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001225 // Handle this designated initializer. elementIndex will be
1226 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001227 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001228 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001229 StructuredList, StructuredIndex, true,
1230 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001231 hadError = true;
1232 continue;
1233 }
1234
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001235 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001236 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001237 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001238 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001239 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001240
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001241 // If the array is of incomplete type, keep track of the number of
1242 // elements in the initializer.
1243 if (!maxElementsKnown && elementIndex > maxElements)
1244 maxElements = elementIndex;
1245
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246 continue;
1247 }
1248
1249 // If we know the maximum number of elements, and we've already
1250 // hit it, stop consuming elements in the initializer list.
1251 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001252 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001253
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001254 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001255 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001256 Entity);
1257 // Check this element.
1258 CheckSubElementType(ElementEntity, IList, elementType, Index,
1259 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001260 ++elementIndex;
1261
1262 // If the array is of incomplete type, keep track of the number of
1263 // elements in the initializer.
1264 if (!maxElementsKnown && elementIndex > maxElements)
1265 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001266 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001267 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001268 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001269 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001270 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001272 // Sizing an array implicitly to zero is not allowed by ISO C,
1273 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001274 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001275 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001276 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001279 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001280 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001281 if (!hadError && VerifyOnly) {
1282 // Check if there are any members of the array that get value-initialized.
1283 // If so, check if doing that is possible.
1284 // FIXME: This needs to detect holes left by designated initializers too.
1285 if (maxElementsKnown && elementIndex < maxElements)
1286 CheckValueInitializable(InitializedEntity::InitializeElement(
1287 SemaRef.Context, 0, Entity));
1288 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001289}
1290
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001291bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1292 Expr *InitExpr,
1293 FieldDecl *Field,
1294 bool TopLevelObject) {
1295 // Handle GNU flexible array initializers.
1296 unsigned FlexArrayDiag;
1297 if (isa<InitListExpr>(InitExpr) &&
1298 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1299 // Empty flexible array init always allowed as an extension
1300 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001301 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001302 // Disallow flexible array init in C++; it is not required for gcc
1303 // compatibility, and it needs work to IRGen correctly in general.
1304 FlexArrayDiag = diag::err_flexible_array_init;
1305 } else if (!TopLevelObject) {
1306 // Disallow flexible array init on non-top-level object
1307 FlexArrayDiag = diag::err_flexible_array_init;
1308 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1309 // Disallow flexible array init on anything which is not a variable.
1310 FlexArrayDiag = diag::err_flexible_array_init;
1311 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1312 // Disallow flexible array init on local variables.
1313 FlexArrayDiag = diag::err_flexible_array_init;
1314 } else {
1315 // Allow other cases.
1316 FlexArrayDiag = diag::ext_flexible_array_init;
1317 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001318
1319 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001320 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001321 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001322 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001323 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1324 << Field;
1325 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001326
1327 return FlexArrayDiag != diag::ext_flexible_array_init;
1328}
1329
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001330void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001331 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001332 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001333 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001334 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001335 unsigned &Index,
1336 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001337 unsigned &StructuredIndex,
1338 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001339 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Eli Friedmanb85f7072008-05-19 19:16:24 +00001341 // If the record is invalid, some of it's members are invalid. To avoid
1342 // confusion, we forgo checking the intializer for the entire record.
1343 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001344 // Assume it was supposed to consume a single initializer.
1345 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001346 hadError = true;
1347 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001349
1350 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001351 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001352
1353 // If there's a default initializer, use it.
1354 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1355 if (VerifyOnly)
1356 return;
1357 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1358 Field != FieldEnd; ++Field) {
1359 if (Field->hasInClassInitializer()) {
1360 StructuredList->setInitializedFieldInUnion(*Field);
1361 // FIXME: Actually build a CXXDefaultInitExpr?
1362 return;
1363 }
1364 }
1365 }
1366
1367 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001368 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1369 Field != FieldEnd; ++Field) {
1370 if (Field->getDeclName()) {
1371 if (VerifyOnly)
1372 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001373 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001374 else
David Blaikie581deb32012-06-06 20:45:41 +00001375 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001376 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001377 }
1378 }
1379 return;
1380 }
1381
Douglas Gregor05c13a32009-01-22 00:58:24 +00001382 // If structDecl is a forward declaration, this loop won't do
1383 // anything except look at designated initializers; That's okay,
1384 // because an error should get printed out elsewhere. It might be
1385 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001386 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001387 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001388 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001389 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001390 while (Index < IList->getNumInits()) {
1391 Expr *Init = IList->getInit(Index);
1392
1393 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001394 // If we're not the subobject that matches up with the '{' for
1395 // the designator, we shouldn't be handling the
1396 // designator. Return immediately.
1397 if (!SubobjectIsDesignatorContext)
1398 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001399
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 // Handle this designated initializer. Field will be updated to
1401 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001402 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 StructuredList, StructuredIndex,
1405 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 hadError = true;
1407
Douglas Gregordfb5e592009-02-12 19:00:39 +00001408 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001409
1410 // Disable check for missing fields when designators are used.
1411 // This matches gcc behaviour.
1412 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001413 continue;
1414 }
1415
1416 if (Field == FieldEnd) {
1417 // We've run out of fields. We're done.
1418 break;
1419 }
1420
Douglas Gregordfb5e592009-02-12 19:00:39 +00001421 // We've already initialized a member of a union. We're done.
1422 if (InitializedSomething && DeclType->isUnionType())
1423 break;
1424
Douglas Gregor44b43212008-12-11 16:49:14 +00001425 // If we've hit the flexible array member at the end, we're done.
1426 if (Field->getType()->isIncompleteArrayType())
1427 break;
1428
Douglas Gregor0bb76892009-01-29 16:53:55 +00001429 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001431 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001432 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001433 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001434
Douglas Gregor54001c12011-06-29 21:51:31 +00001435 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001436 bool InvalidUse;
1437 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001438 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001439 else
David Blaikie581deb32012-06-06 20:45:41 +00001440 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001441 IList->getInit(Index)->getLocStart());
1442 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001443 ++Index;
1444 ++Field;
1445 hadError = true;
1446 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001447 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001448
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001449 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001450 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001451 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1452 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001453 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001454
Sebastian Redl14b0c192011-09-24 17:48:00 +00001455 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001456 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001457 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001458 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001459
1460 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001461 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001462
John McCall80639de2010-03-11 19:32:38 +00001463 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001464 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1465 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1466 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001467 // It is possible we have one or more unnamed bitfields remaining.
1468 // Find first (if any) named field and emit warning.
1469 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1470 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001471 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001472 SemaRef.Diag(IList->getSourceRange().getEnd(),
1473 diag::warn_missing_field_initializers) << it->getName();
1474 break;
1475 }
1476 }
1477 }
1478
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001479 // Check that any remaining fields can be value-initialized.
1480 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1481 !Field->getType()->isIncompleteArrayType()) {
1482 // FIXME: Should check for holes left by designated initializers too.
1483 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001484 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001485 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001486 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001487 }
1488 }
1489
Mike Stump1eb44332009-09-09 15:08:12 +00001490 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001491 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 return;
1493
David Blaikie581deb32012-06-06 20:45:41 +00001494 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001495 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001496 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001497 ++Index;
1498 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001499 }
1500
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001501 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001502 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001504 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001505 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001506 StructuredList, StructuredIndex);
1507 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001508 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001509 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001510}
Steve Naroff0cca7492008-05-01 22:18:59 +00001511
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001512/// \brief Expand a field designator that refers to a member of an
1513/// anonymous struct or union into a series of field designators that
1514/// refers to the field within the appropriate subobject.
1515///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001516static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001517 DesignatedInitExpr *DIE,
1518 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001519 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001520 typedef DesignatedInitExpr::Designator Designator;
1521
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001522 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001523 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001524 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1525 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1526 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001527 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001528 DIE->getDesignator(DesigIdx)->getDotLoc(),
1529 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1530 else
1531 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1532 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001533 assert(isa<FieldDecl>(*PI));
1534 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001535 }
1536
1537 // Expand the current designator into the set of replacement
1538 // designators, so we have a full subobject path down to where the
1539 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001540 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001541 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001542}
Mike Stump1eb44332009-09-09 15:08:12 +00001543
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001545/// corresponds to FieldName.
1546static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1547 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001548 if (!FieldName)
1549 return 0;
1550
Francois Picheta0e27f02010-12-22 03:46:10 +00001551 assert(AnonField->isAnonymousStructOrUnion());
1552 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001553 while (IndirectFieldDecl *IF =
1554 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001555 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001556 return IF;
1557 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001558 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001559 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001560}
1561
Sebastian Redl14b0c192011-09-24 17:48:00 +00001562static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1563 DesignatedInitExpr *DIE) {
1564 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1565 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1566 for (unsigned I = 0; I < NumIndexExprs; ++I)
1567 IndexExprs[I] = DIE->getSubExpr(I + 1);
1568 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001569 DIE->size(), IndexExprs,
1570 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001571 DIE->usesGNUSyntax(), DIE->getInit());
1572}
1573
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001574namespace {
1575
1576// Callback to only accept typo corrections that are for field members of
1577// the given struct or union.
1578class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1579 public:
1580 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1581 : Record(RD) {}
1582
1583 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1584 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1585 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1586 }
1587
1588 private:
1589 RecordDecl *Record;
1590};
1591
1592}
1593
Douglas Gregor05c13a32009-01-22 00:58:24 +00001594/// @brief Check the well-formedness of a C99 designated initializer.
1595///
1596/// Determines whether the designated initializer @p DIE, which
1597/// resides at the given @p Index within the initializer list @p
1598/// IList, is well-formed for a current object of type @p DeclType
1599/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001600/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001601/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001602///
1603/// @param IList The initializer list in which this designated
1604/// initializer occurs.
1605///
Douglas Gregor71199712009-04-15 04:56:10 +00001606/// @param DIE The designated initializer expression.
1607///
1608/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001609///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001610/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001611/// into which the designation in @p DIE should refer.
1612///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001613/// @param NextField If non-NULL and the first designator in @p DIE is
1614/// a field, this will be set to the field declaration corresponding
1615/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001616///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617/// @param NextElementIndex If non-NULL and the first designator in @p
1618/// DIE is an array designator or GNU array-range designator, this
1619/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620///
1621/// @param Index Index into @p IList where the designated initializer
1622/// @p DIE occurs.
1623///
Douglas Gregor4c678342009-01-28 21:54:33 +00001624/// @param StructuredList The initializer list expression that
1625/// describes all of the subobject initializers in the order they'll
1626/// actually be initialized.
1627///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001628/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001629bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001630InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001631 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001632 DesignatedInitExpr *DIE,
1633 unsigned DesigIdx,
1634 QualType &CurrentObjectType,
1635 RecordDecl::field_iterator *NextField,
1636 llvm::APSInt *NextElementIndex,
1637 unsigned &Index,
1638 InitListExpr *StructuredList,
1639 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001640 bool FinishSubobjectInit,
1641 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001642 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 // Check the actual initialization for the designated object type.
1644 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001645
1646 // Temporarily remove the designator expression from the
1647 // initializer list that the child calls see, so that we don't try
1648 // to re-process the designator.
1649 unsigned OldIndex = Index;
1650 IList->setInit(OldIndex, DIE->getInit());
1651
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001652 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001653 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001654
1655 // Restore the designated initializer expression in the syntactic
1656 // form of the initializer list.
1657 if (IList->getInit(OldIndex) != DIE->getInit())
1658 DIE->setInit(IList->getInit(OldIndex));
1659 IList->setInit(OldIndex, DIE);
1660
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001661 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001662 }
1663
Douglas Gregor71199712009-04-15 04:56:10 +00001664 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001665 bool IsFirstDesignator = (DesigIdx == 0);
1666 if (!VerifyOnly) {
1667 assert((IsFirstDesignator || StructuredList) &&
1668 "Need a non-designated initializer list to start from");
1669
1670 // Determine the structural initializer list that corresponds to the
1671 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001672 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001673 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1674 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001675 SourceRange(D->getLocStart(),
1676 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001677 assert(StructuredList && "Expected a structured initializer list");
1678 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001679
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001680 if (D->isFieldDesignator()) {
1681 // C99 6.7.8p7:
1682 //
1683 // If a designator has the form
1684 //
1685 // . identifier
1686 //
1687 // then the current object (defined below) shall have
1688 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001689 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001691 if (!RT) {
1692 SourceLocation Loc = D->getDotLoc();
1693 if (Loc.isInvalid())
1694 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 if (!VerifyOnly)
1696 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001697 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001698 ++Index;
1699 return true;
1700 }
1701
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 // Note: we perform a linear search of the fields here, despite
1703 // the fact that we have a faster lookup method, because we always
1704 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001705 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001707 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001708 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001709 Field = RT->getDecl()->field_begin(),
1710 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 for (; Field != FieldEnd; ++Field) {
1712 if (Field->isUnnamedBitfield())
1713 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001714
Francois Picheta0e27f02010-12-22 03:46:10 +00001715 // If we find a field representing an anonymous field, look in the
1716 // IndirectFieldDecl that follow for the designated initializer.
1717 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1718 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001719 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001720 // In verify mode, don't modify the original.
1721 if (VerifyOnly)
1722 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001723 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1724 D = DIE->getDesignator(DesigIdx);
1725 break;
1726 }
1727 }
David Blaikie581deb32012-06-06 20:45:41 +00001728 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001729 break;
1730 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 break;
1732
1733 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001734 }
1735
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001737 if (VerifyOnly) {
1738 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001739 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001740 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001741
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001742 // There was no normal field in the struct with the designated
1743 // name. Perform another lookup for this name, which may find
1744 // something that we can't designate (e.g., a member function),
1745 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001746 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001747 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001748 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001749 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001750 // Name lookup didn't find anything. Determine whether this
1751 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001752 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001753 TypoCorrection Corrected = SemaRef.CorrectTypo(
1754 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001755 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001756 RT->getDecl());
1757 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001758 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001759 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001760 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001762 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001764 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001765 << FieldName << CurrentObjectType << CorrectedQuotedStr
1766 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001768 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001769 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001770 } else {
1771 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1772 << FieldName << CurrentObjectType;
1773 ++Index;
1774 return true;
1775 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001778 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001780 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001782 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001783 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001784 ++Index;
1785 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001786 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001787
Francois Picheta0e27f02010-12-22 03:46:10 +00001788 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001789 // The replacement field comes from typo correction; find it
1790 // in the list of fields.
1791 FieldIndex = 0;
1792 Field = RT->getDecl()->field_begin();
1793 for (; Field != FieldEnd; ++Field) {
1794 if (Field->isUnnamedBitfield())
1795 continue;
1796
David Blaikie581deb32012-06-06 20:45:41 +00001797 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001798 Field->getIdentifier() == ReplacementField->getIdentifier())
1799 break;
1800
1801 ++FieldIndex;
1802 }
1803 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001804 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001805
1806 // All of the fields of a union are located at the same place in
1807 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001808 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001810 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001811 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001812 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001813
Douglas Gregor54001c12011-06-29 21:51:31 +00001814 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001815 bool InvalidUse;
1816 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001817 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001818 else
David Blaikie581deb32012-06-06 20:45:41 +00001819 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001820 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001821 ++Index;
1822 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001823 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001824
Sebastian Redl14b0c192011-09-24 17:48:00 +00001825 if (!VerifyOnly) {
1826 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001827 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Sebastian Redl14b0c192011-09-24 17:48:00 +00001829 // Make sure that our non-designated initializer list has space
1830 // for a subobject corresponding to this field.
1831 if (FieldIndex >= StructuredList->getNumInits())
1832 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1833 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001834
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001835 // This designator names a flexible array member.
1836 if (Field->getType()->isIncompleteArrayType()) {
1837 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001838 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001839 // We can't designate an object within the flexible array
1840 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001841 if (!VerifyOnly) {
1842 DesignatedInitExpr::Designator *NextD
1843 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001844 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001845 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001846 << SourceRange(NextD->getLocStart(),
1847 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001848 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001849 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001850 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001851 Invalid = true;
1852 }
1853
Chris Lattner9046c222010-10-10 17:49:49 +00001854 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1855 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001856 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001857 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001858 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001859 diag::err_flexible_array_init_needs_braces)
1860 << DIE->getInit()->getSourceRange();
1861 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001862 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001863 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001864 Invalid = true;
1865 }
1866
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001867 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001868 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001869 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001870 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001871
1872 if (Invalid) {
1873 ++Index;
1874 return true;
1875 }
1876
1877 // Initialize the array.
1878 bool prevHadError = hadError;
1879 unsigned newStructuredIndex = FieldIndex;
1880 unsigned OldIndex = Index;
1881 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001882
1883 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001884 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001885 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001886 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001887
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001888 IList->setInit(OldIndex, DIE);
1889 if (hadError && !prevHadError) {
1890 ++Field;
1891 ++FieldIndex;
1892 if (NextField)
1893 *NextField = Field;
1894 StructuredIndex = FieldIndex;
1895 return true;
1896 }
1897 } else {
1898 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001899 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001900 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001901
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001902 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001903 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001904 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1905 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001906 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001907 true, false))
1908 return true;
1909 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001910
1911 // Find the position of the next field to be initialized in this
1912 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001913 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001914 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001915
1916 // If this the first designator, our caller will continue checking
1917 // the rest of this struct/class/union subobject.
1918 if (IsFirstDesignator) {
1919 if (NextField)
1920 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001921 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001922 return false;
1923 }
1924
Douglas Gregor34e79462009-01-28 23:36:17 +00001925 if (!FinishSubobjectInit)
1926 return false;
1927
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001928 // We've already initialized something in the union; we're done.
1929 if (RT->getDecl()->isUnion())
1930 return hadError;
1931
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001932 // Check the remaining fields within this class/struct/union subobject.
1933 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001934
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001935 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001936 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001937 return hadError && !prevHadError;
1938 }
1939
1940 // C99 6.7.8p6:
1941 //
1942 // If a designator has the form
1943 //
1944 // [ constant-expression ]
1945 //
1946 // then the current object (defined below) shall have array
1947 // type and the expression shall be an integer constant
1948 // expression. If the array is of unknown size, any
1949 // nonnegative value is valid.
1950 //
1951 // Additionally, cope with the GNU extension that permits
1952 // designators of the form
1953 //
1954 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001955 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001956 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001957 if (!VerifyOnly)
1958 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1959 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001960 ++Index;
1961 return true;
1962 }
1963
1964 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001965 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1966 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001967 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001968 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001969 DesignatedEndIndex = DesignatedStartIndex;
1970 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001971 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001972
Mike Stump1eb44332009-09-09 15:08:12 +00001973 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001974 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001975 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001976 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001977 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001978
Chris Lattnere0fd8322011-02-19 22:28:58 +00001979 // Codegen can't handle evaluating array range designators that have side
1980 // effects, because we replicate the AST value for each initialized element.
1981 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1982 // elements with something that has a side effect, so codegen can emit an
1983 // "error unsupported" error instead of miscompiling the app.
1984 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001985 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001986 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001987 }
1988
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001989 if (isa<ConstantArrayType>(AT)) {
1990 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001991 DesignatedStartIndex
1992 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001993 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001994 DesignatedEndIndex
1995 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001996 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1997 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001998 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001999 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002000 diag::err_array_designator_too_large)
2001 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2002 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002003 ++Index;
2004 return true;
2005 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002006 } else {
2007 // Make sure the bit-widths and signedness match.
2008 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002009 DesignatedEndIndex
2010 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002011 else if (DesignatedStartIndex.getBitWidth() <
2012 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002013 DesignatedStartIndex
2014 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002015 DesignatedStartIndex.setIsUnsigned(true);
2016 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Douglas Gregor4c678342009-01-28 21:54:33 +00002019 // Make sure that our non-designated initializer list has space
2020 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002021 if (!VerifyOnly &&
2022 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002023 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002024 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002025
Douglas Gregor34e79462009-01-28 23:36:17 +00002026 // Repeatedly perform subobject initializations in the range
2027 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002028
Douglas Gregor34e79462009-01-28 23:36:17 +00002029 // Move to the next designator
2030 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2031 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002033 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002034 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002035
Douglas Gregor34e79462009-01-28 23:36:17 +00002036 while (DesignatedStartIndex <= DesignatedEndIndex) {
2037 // Recurse to check later designated subobjects.
2038 QualType ElementType = AT->getElementType();
2039 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002041 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002042 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2043 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002044 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002045 (DesignatedStartIndex == DesignatedEndIndex),
2046 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002047 return true;
2048
2049 // Move to the next index in the array that we'll be initializing.
2050 ++DesignatedStartIndex;
2051 ElementIndex = DesignatedStartIndex.getZExtValue();
2052 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002053
2054 // If this the first designator, our caller will continue checking
2055 // the rest of this array subobject.
2056 if (IsFirstDesignator) {
2057 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002058 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002059 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002060 return false;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Douglas Gregor34e79462009-01-28 23:36:17 +00002063 if (!FinishSubobjectInit)
2064 return false;
2065
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002066 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002067 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002069 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002071 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002072}
2073
Douglas Gregor4c678342009-01-28 21:54:33 +00002074// Get the structured initializer list for a subobject of type
2075// @p CurrentObjectType.
2076InitListExpr *
2077InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2078 QualType CurrentObjectType,
2079 InitListExpr *StructuredList,
2080 unsigned StructuredIndex,
2081 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002082 if (VerifyOnly)
2083 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002084 Expr *ExistingInit = 0;
2085 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002086 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002087 else if (StructuredIndex < StructuredList->getNumInits())
2088 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor4c678342009-01-28 21:54:33 +00002090 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2091 return Result;
2092
2093 if (ExistingInit) {
2094 // We are creating an initializer list that initializes the
2095 // subobjects of the current object, but there was already an
2096 // initialization that completely initialized the current
2097 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002098 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002099 // struct X { int a, b; };
2100 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002101 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002102 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2103 // designated initializer re-initializes the whole
2104 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002105 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002106 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002107 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002108 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002109 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002110 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002111 << ExistingInit->getSourceRange();
2112 }
2113
Mike Stump1eb44332009-09-09 15:08:12 +00002114 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002115 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002116 InitRange.getBegin(), MultiExprArg(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00002117 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002118
Eli Friedman5c89c392012-02-23 02:25:10 +00002119 QualType ResultType = CurrentObjectType;
2120 if (!ResultType->isArrayType())
2121 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2122 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002123
Douglas Gregorfa219202009-03-20 23:58:33 +00002124 // Pre-allocate storage for the structured initializer list.
2125 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002126 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002127 bool GotNumInits = false;
2128 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002129 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002130 GotNumInits = true;
2131 } else if (Index < IList->getNumInits()) {
2132 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002133 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002134 GotNumInits = true;
2135 }
Douglas Gregor08457732009-03-21 18:13:52 +00002136 }
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002139 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2140 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2141 NumElements = CAType->getSize().getZExtValue();
2142 // Simple heuristic so that we don't allocate a very large
2143 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002144 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002145 NumElements = 0;
2146 }
John McCall183700f2009-09-21 23:43:11 +00002147 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002148 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002149 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002150 RecordDecl *RDecl = RType->getDecl();
2151 if (RDecl->isUnion())
2152 NumElements = 1;
2153 else
Mike Stump1eb44332009-09-09 15:08:12 +00002154 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002155 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002156 }
2157
Ted Kremenek709210f2010-04-13 23:39:13 +00002158 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002159
Douglas Gregor4c678342009-01-28 21:54:33 +00002160 // Link this new initializer list into the structured initializer
2161 // lists.
2162 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002163 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002164 else {
2165 Result->setSyntacticForm(IList);
2166 SyntacticToSemantic[IList] = Result;
2167 }
2168
2169 return Result;
2170}
2171
2172/// Update the initializer at index @p StructuredIndex within the
2173/// structured initializer list to the value @p expr.
2174void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2175 unsigned &StructuredIndex,
2176 Expr *expr) {
2177 // No structured initializer list to update
2178 if (!StructuredList)
2179 return;
2180
Ted Kremenek709210f2010-04-13 23:39:13 +00002181 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2182 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002183 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002184 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002185 diag::warn_initializer_overrides)
2186 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002187 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002188 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002189 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002190 << PrevInit->getSourceRange();
2191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Douglas Gregor4c678342009-01-28 21:54:33 +00002193 ++StructuredIndex;
2194}
2195
Douglas Gregor05c13a32009-01-22 00:58:24 +00002196/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002197/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002198/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002199/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002200/// failure. Returns the index expression, possibly with an implicit cast
2201/// added, on success. If everything went okay, Value will receive the
2202/// value of the constant expression.
2203static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002204CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002205 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002206
2207 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002208 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2209 if (Result.isInvalid())
2210 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002211
Chris Lattner3bf68932009-04-25 21:59:05 +00002212 if (Value.isSigned() && Value.isNegative())
2213 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002214 << Value.toString(10) << Index->getSourceRange();
2215
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002216 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002217 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002218}
2219
John McCall60d7b3a2010-08-24 06:29:42 +00002220ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002221 SourceLocation Loc,
2222 bool GNUSyntax,
2223 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002224 typedef DesignatedInitExpr::Designator ASTDesignator;
2225
2226 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002227 SmallVector<ASTDesignator, 32> Designators;
2228 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002229
2230 // Build designators and check array designator expressions.
2231 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2232 const Designator &D = Desig.getDesignator(Idx);
2233 switch (D.getKind()) {
2234 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002235 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002236 D.getFieldLoc()));
2237 break;
2238
2239 case Designator::ArrayDesignator: {
2240 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2241 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002242 if (!Index->isTypeDependent() && !Index->isValueDependent())
2243 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2244 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002245 Invalid = true;
2246 else {
2247 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002248 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002249 D.getRBracketLoc()));
2250 InitExpressions.push_back(Index);
2251 }
2252 break;
2253 }
2254
2255 case Designator::ArrayRangeDesignator: {
2256 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2257 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2258 llvm::APSInt StartValue;
2259 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002260 bool StartDependent = StartIndex->isTypeDependent() ||
2261 StartIndex->isValueDependent();
2262 bool EndDependent = EndIndex->isTypeDependent() ||
2263 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002264 if (!StartDependent)
2265 StartIndex =
2266 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2267 if (!EndDependent)
2268 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2269
2270 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002271 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002272 else {
2273 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002274 if (StartDependent || EndDependent) {
2275 // Nothing to compute.
2276 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002277 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002278 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002279 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002280
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002281 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002282 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002283 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002284 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2285 Invalid = true;
2286 } else {
2287 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002288 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002289 D.getEllipsisLoc(),
2290 D.getRBracketLoc()));
2291 InitExpressions.push_back(StartIndex);
2292 InitExpressions.push_back(EndIndex);
2293 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002294 }
2295 break;
2296 }
2297 }
2298 }
2299
2300 if (Invalid || Init.isInvalid())
2301 return ExprError();
2302
2303 // Clear out the expressions within the designation.
2304 Desig.ClearExprs(*this);
2305
2306 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002307 = DesignatedInitExpr::Create(Context,
2308 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002309 InitExpressions, Loc, GNUSyntax,
2310 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002311
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002313 Diag(DIE->getLocStart(), diag::ext_designated_init)
2314 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002315
Douglas Gregor05c13a32009-01-22 00:58:24 +00002316 return Owned(DIE);
2317}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002318
Douglas Gregor20093b42009-12-09 23:02:17 +00002319//===----------------------------------------------------------------------===//
2320// Initialization entity
2321//===----------------------------------------------------------------------===//
2322
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002323InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002324 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002325 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002326{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002327 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2328 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002329 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002330 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002331 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002332 Type = VT->getElementType();
2333 } else {
2334 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2335 assert(CT && "Unexpected type");
2336 Kind = EK_ComplexElement;
2337 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002338 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002339}
2340
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002342 CXXBaseSpecifier *Base,
2343 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002344{
2345 InitializedEntity Result;
2346 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002347 Result.Base = reinterpret_cast<uintptr_t>(Base);
2348 if (IsInheritedVirtualBase)
2349 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350
Douglas Gregord6542d82009-12-22 15:35:07 +00002351 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002352 return Result;
2353}
2354
Douglas Gregor99a2e602009-12-16 01:38:02 +00002355DeclarationName InitializedEntity::getName() const {
2356 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002357 case EK_Parameter: {
2358 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2359 return (D ? D->getDeclName() : DeclarationName());
2360 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002361
2362 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002363 case EK_Member:
2364 return VariableOrMember->getDeclName();
2365
Douglas Gregor47736542012-02-15 16:57:26 +00002366 case EK_LambdaCapture:
2367 return Capture.Var->getDeclName();
2368
Douglas Gregor99a2e602009-12-16 01:38:02 +00002369 case EK_Result:
2370 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002371 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002372 case EK_Temporary:
2373 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002374 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002375 case EK_ArrayElement:
2376 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002377 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002378 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002379 return DeclarationName();
2380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002381
David Blaikie7530c032012-01-17 06:56:22 +00002382 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002383}
2384
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002385DeclaratorDecl *InitializedEntity::getDecl() const {
2386 switch (getKind()) {
2387 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002388 case EK_Member:
2389 return VariableOrMember;
2390
John McCallf85e1932011-06-15 23:02:42 +00002391 case EK_Parameter:
2392 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2393
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002394 case EK_Result:
2395 case EK_Exception:
2396 case EK_New:
2397 case EK_Temporary:
2398 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002399 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002400 case EK_ArrayElement:
2401 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002402 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002403 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002404 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002405 return 0;
2406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002407
David Blaikie7530c032012-01-17 06:56:22 +00002408 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002409}
2410
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002411bool InitializedEntity::allowsNRVO() const {
2412 switch (getKind()) {
2413 case EK_Result:
2414 case EK_Exception:
2415 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002417 case EK_Variable:
2418 case EK_Parameter:
2419 case EK_Member:
2420 case EK_New:
2421 case EK_Temporary:
2422 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002423 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002424 case EK_ArrayElement:
2425 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002426 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002427 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002428 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002429 break;
2430 }
2431
2432 return false;
2433}
2434
Douglas Gregor20093b42009-12-09 23:02:17 +00002435//===----------------------------------------------------------------------===//
2436// Initialization sequence
2437//===----------------------------------------------------------------------===//
2438
2439void InitializationSequence::Step::Destroy() {
2440 switch (Kind) {
2441 case SK_ResolveAddressOfOverloadedFunction:
2442 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002443 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002444 case SK_CastDerivedToBaseLValue:
2445 case SK_BindReference:
2446 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002447 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002448 case SK_UserConversion:
2449 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002450 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002451 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002452 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002453 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002454 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002455 case SK_UnwrapInitList:
2456 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002457 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002458 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002459 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002460 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002461 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002462 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002463 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002464 case SK_PassByIndirectCopyRestore:
2465 case SK_PassByIndirectRestore:
2466 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002467 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002468 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002469 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 case SK_ConversionSequence:
2473 delete ICS;
2474 }
2475}
2476
Douglas Gregorb70cf442010-03-26 20:14:36 +00002477bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002478 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002479}
2480
2481bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002482 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002483 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002484
Douglas Gregorb70cf442010-03-26 20:14:36 +00002485 switch (getFailureKind()) {
2486 case FK_TooManyInitsForReference:
2487 case FK_ArrayNeedsInitList:
2488 case FK_ArrayNeedsInitListOrStringLiteral:
2489 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2490 case FK_NonConstLValueReferenceBindingToTemporary:
2491 case FK_NonConstLValueReferenceBindingToUnrelated:
2492 case FK_RValueReferenceBindingToLValue:
2493 case FK_ReferenceInitDropsQualifiers:
2494 case FK_ReferenceInitFailed:
2495 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002496 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002497 case FK_TooManyInitsForScalar:
2498 case FK_ReferenceBindingToInitList:
2499 case FK_InitListBadDestinationType:
2500 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002501 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002502 case FK_ArrayTypeMismatch:
2503 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002504 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002505 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002506 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002507 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002508 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002509 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002510
Douglas Gregorb70cf442010-03-26 20:14:36 +00002511 case FK_ReferenceInitOverloadFailed:
2512 case FK_UserConversionOverloadFailed:
2513 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002514 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002515 return FailedOverloadResult == OR_Ambiguous;
2516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002517
David Blaikie7530c032012-01-17 06:56:22 +00002518 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002519}
2520
Douglas Gregord6e44a32010-04-16 22:09:46 +00002521bool InitializationSequence::isConstructorInitialization() const {
2522 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2523}
2524
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002525void
2526InitializationSequence
2527::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2528 DeclAccessPair Found,
2529 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 Step S;
2531 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2532 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002533 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002534 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002535 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 Steps.push_back(S);
2537}
2538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002540 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002542 switch (VK) {
2543 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2544 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2545 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002546 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002547 S.Type = BaseType;
2548 Steps.push_back(S);
2549}
2550
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 bool BindingTemporary) {
2553 Step S;
2554 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2555 S.Type = T;
2556 Steps.push_back(S);
2557}
2558
Douglas Gregor523d46a2010-04-18 07:40:54 +00002559void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2560 Step S;
2561 S.Kind = SK_ExtraneousCopyToTemporary;
2562 S.Type = T;
2563 Steps.push_back(S);
2564}
2565
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002566void
2567InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2568 DeclAccessPair FoundDecl,
2569 QualType T,
2570 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002571 Step S;
2572 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002573 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002574 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002575 S.Function.Function = Function;
2576 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002577 Steps.push_back(S);
2578}
2579
2580void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002581 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002582 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002583 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002584 switch (VK) {
2585 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002586 S.Kind = SK_QualificationConversionRValue;
2587 break;
John McCall5baba9d2010-08-25 10:28:54 +00002588 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002589 S.Kind = SK_QualificationConversionXValue;
2590 break;
John McCall5baba9d2010-08-25 10:28:54 +00002591 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002592 S.Kind = SK_QualificationConversionLValue;
2593 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002594 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002595 S.Type = Ty;
2596 Steps.push_back(S);
2597}
2598
Jordan Rose1fd1e282013-04-11 00:58:58 +00002599void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2600 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2601
2602 Step S;
2603 S.Kind = SK_LValueToRValue;
2604 S.Type = Ty;
2605 Steps.push_back(S);
2606}
2607
Douglas Gregor20093b42009-12-09 23:02:17 +00002608void InitializationSequence::AddConversionSequenceStep(
2609 const ImplicitConversionSequence &ICS,
2610 QualType T) {
2611 Step S;
2612 S.Kind = SK_ConversionSequence;
2613 S.Type = T;
2614 S.ICS = new ImplicitConversionSequence(ICS);
2615 Steps.push_back(S);
2616}
2617
Douglas Gregord87b61f2009-12-10 17:56:55 +00002618void InitializationSequence::AddListInitializationStep(QualType T) {
2619 Step S;
2620 S.Kind = SK_ListInitialization;
2621 S.Type = T;
2622 Steps.push_back(S);
2623}
2624
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002626InitializationSequence
2627::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2628 AccessSpecifier Access,
2629 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002630 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002631 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002632 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002633 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2634 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002635 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002636 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002637 S.Function.Function = Constructor;
2638 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002639 Steps.push_back(S);
2640}
2641
Douglas Gregor71d17402009-12-15 00:01:57 +00002642void InitializationSequence::AddZeroInitializationStep(QualType T) {
2643 Step S;
2644 S.Kind = SK_ZeroInitialization;
2645 S.Type = T;
2646 Steps.push_back(S);
2647}
2648
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002649void InitializationSequence::AddCAssignmentStep(QualType T) {
2650 Step S;
2651 S.Kind = SK_CAssignment;
2652 S.Type = T;
2653 Steps.push_back(S);
2654}
2655
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002656void InitializationSequence::AddStringInitStep(QualType T) {
2657 Step S;
2658 S.Kind = SK_StringInit;
2659 S.Type = T;
2660 Steps.push_back(S);
2661}
2662
Douglas Gregor569c3162010-08-07 11:51:51 +00002663void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2664 Step S;
2665 S.Kind = SK_ObjCObjectConversion;
2666 S.Type = T;
2667 Steps.push_back(S);
2668}
2669
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002670void InitializationSequence::AddArrayInitStep(QualType T) {
2671 Step S;
2672 S.Kind = SK_ArrayInit;
2673 S.Type = T;
2674 Steps.push_back(S);
2675}
2676
Richard Smith0f163e92012-02-15 22:38:09 +00002677void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2678 Step S;
2679 S.Kind = SK_ParenthesizedArrayInit;
2680 S.Type = T;
2681 Steps.push_back(S);
2682}
2683
John McCallf85e1932011-06-15 23:02:42 +00002684void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2685 bool shouldCopy) {
2686 Step s;
2687 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2688 : SK_PassByIndirectRestore);
2689 s.Type = type;
2690 Steps.push_back(s);
2691}
2692
2693void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2694 Step S;
2695 S.Kind = SK_ProduceObjCObject;
2696 S.Type = T;
2697 Steps.push_back(S);
2698}
2699
Sebastian Redl2b916b82012-01-17 22:49:42 +00002700void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2701 Step S;
2702 S.Kind = SK_StdInitializerList;
2703 S.Type = T;
2704 Steps.push_back(S);
2705}
2706
Guy Benyei21f18c42013-02-07 10:55:47 +00002707void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2708 Step S;
2709 S.Kind = SK_OCLSamplerInit;
2710 S.Type = T;
2711 Steps.push_back(S);
2712}
2713
Guy Benyeie6b9d802013-01-20 12:31:11 +00002714void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2715 Step S;
2716 S.Kind = SK_OCLZeroEvent;
2717 S.Type = T;
2718 Steps.push_back(S);
2719}
2720
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002721void InitializationSequence::RewrapReferenceInitList(QualType T,
2722 InitListExpr *Syntactic) {
2723 assert(Syntactic->getNumInits() == 1 &&
2724 "Can only rewrap trivial init lists.");
2725 Step S;
2726 S.Kind = SK_UnwrapInitList;
2727 S.Type = Syntactic->getInit(0)->getType();
2728 Steps.insert(Steps.begin(), S);
2729
2730 S.Kind = SK_RewrapInitList;
2731 S.Type = T;
2732 S.WrappingSyntacticList = Syntactic;
2733 Steps.push_back(S);
2734}
2735
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002737 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002738 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002739 this->Failure = Failure;
2740 this->FailedOverloadResult = Result;
2741}
2742
2743//===----------------------------------------------------------------------===//
2744// Attempt initialization
2745//===----------------------------------------------------------------------===//
2746
John McCallf85e1932011-06-15 23:02:42 +00002747static void MaybeProduceObjCObject(Sema &S,
2748 InitializationSequence &Sequence,
2749 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002750 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002751
2752 /// When initializing a parameter, produce the value if it's marked
2753 /// __attribute__((ns_consumed)).
2754 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2755 if (!Entity.isParameterConsumed())
2756 return;
2757
2758 assert(Entity.getType()->isObjCRetainableType() &&
2759 "consuming an object of unretainable type?");
2760 Sequence.AddProduceObjCObjectStep(Entity.getType());
2761
2762 /// When initializing a return value, if the return type is a
2763 /// retainable type, then returns need to immediately retain the
2764 /// object. If an autorelease is required, it will be done at the
2765 /// last instant.
2766 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2767 if (!Entity.getType()->isObjCRetainableType())
2768 return;
2769
2770 Sequence.AddProduceObjCObjectStep(Entity.getType());
2771 }
2772}
2773
Richard Smithf4bb8d02012-07-05 08:39:21 +00002774/// \brief When initializing from init list via constructor, handle
2775/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002776///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002777/// \return true if we have handled initialization of an object of type
2778/// std::initializer_list<T>, false otherwise.
2779static bool TryInitializerListConstruction(Sema &S,
2780 InitListExpr *List,
2781 QualType DestType,
2782 InitializationSequence &Sequence) {
2783 QualType E;
2784 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002785 return false;
2786
Richard Smithf4bb8d02012-07-05 08:39:21 +00002787 // Check that each individual element can be copy-constructed. But since we
2788 // have no place to store further information, we'll recalculate everything
2789 // later.
2790 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2791 S.Context.getConstantArrayType(E,
2792 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2793 List->getNumInits()),
2794 ArrayType::Normal, 0));
2795 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2796 0, HiddenArray);
2797 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2798 Element.setElementIndex(i);
2799 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2800 Sequence.SetFailed(
2801 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002802 return true;
2803 }
2804 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002805 Sequence.AddStdInitializerListConstructionStep(DestType);
2806 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002807}
2808
Sebastian Redl96715b22012-02-04 21:27:39 +00002809static OverloadingResult
2810ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2811 Expr **Args, unsigned NumArgs,
2812 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002813 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002814 OverloadCandidateSet::iterator &Best,
2815 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002816 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002817 CandidateSet.clear();
2818
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002819 for (ArrayRef<NamedDecl *>::iterator
2820 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002821 NamedDecl *D = *Con;
2822 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2823 bool SuppressUserConversions = false;
2824
2825 // Find the constructor (which may be a template).
2826 CXXConstructorDecl *Constructor = 0;
2827 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2828 if (ConstructorTmpl)
2829 Constructor = cast<CXXConstructorDecl>(
2830 ConstructorTmpl->getTemplatedDecl());
2831 else {
2832 Constructor = cast<CXXConstructorDecl>(D);
2833
2834 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002835 // suppress user-defined conversions on the arguments. We do the same for
2836 // move constructors.
2837 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2838 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002839 SuppressUserConversions = true;
2840 }
2841
2842 if (!Constructor->isInvalidDecl() &&
2843 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002844 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002845 if (ConstructorTmpl)
2846 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2847 /*ExplicitArgs*/ 0,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002848 llvm::makeArrayRef(Args, NumArgs),
2849 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002850 else {
2851 // C++ [over.match.copy]p1:
2852 // - When initializing a temporary to be bound to the first parameter
2853 // of a constructor that takes a reference to possibly cv-qualified
2854 // T as its first argument, called with a single argument in the
2855 // context of direct-initialization, explicit conversion functions
2856 // are also considered.
2857 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2858 NumArgs == 1 &&
2859 Constructor->isCopyOrMoveConstructor();
Sebastian Redl96715b22012-02-04 21:27:39 +00002860 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002861 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002862 SuppressUserConversions,
2863 /*PartialOverloading=*/false,
2864 /*AllowExplicit=*/AllowExplicitConv);
2865 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002866 }
2867 }
2868
2869 // Perform overload resolution and return the result.
2870 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2871}
2872
Sebastian Redl10f04a62011-12-22 14:44:04 +00002873/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2874/// enumerates the constructors of the initialized entity and performs overload
2875/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002876/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002877/// class type.
2878static void TryConstructorInitialization(Sema &S,
2879 const InitializedEntity &Entity,
2880 const InitializationKind &Kind,
2881 Expr **Args, unsigned NumArgs,
2882 QualType DestType,
2883 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002884 bool InitListSyntax = false) {
2885 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2886 "InitListSyntax must come with a single initializer list argument.");
2887
Sebastian Redl10f04a62011-12-22 14:44:04 +00002888 // The type we're constructing needs to be complete.
2889 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002890 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002891 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002892 }
2893
2894 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2895 assert(DestRecordType && "Constructor initialization requires record type");
2896 CXXRecordDecl *DestRecordDecl
2897 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2898
Sebastian Redl96715b22012-02-04 21:27:39 +00002899 // Build the candidate set directly in the initialization sequence
2900 // structure, so that it will persist if we fail.
2901 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2902
2903 // Determine whether we are allowed to call explicit constructors or
2904 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002905 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002906 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002907
Sebastian Redl10f04a62011-12-22 14:44:04 +00002908 // - Otherwise, if T is a class type, constructors are considered. The
2909 // applicable constructors are enumerated, and the best one is chosen
2910 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002911 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002912 // The container holding the constructors can under certain conditions
2913 // be changed while iterating (e.g. because of deserialization).
2914 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002915 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002916
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002917 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002918 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002919 bool AsInitializerList = false;
2920
2921 // C++11 [over.match.list]p1:
2922 // When objects of non-aggregate type T are list-initialized, overload
2923 // resolution selects the constructor in two phases:
2924 // - Initially, the candidate functions are the initializer-list
2925 // constructors of the class T and the argument list consists of the
2926 // initializer list as a single argument.
2927 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002928 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002929 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002930
2931 // If the initializer list has no elements and T has a default constructor,
2932 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00002933 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00002934 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002935 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002936 CopyInitialization, AllowExplicit,
2937 /*OnlyListConstructor=*/true,
2938 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002939
2940 // Time to unwrap the init list.
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002941 Args = ILE->getInits();
2942 NumArgs = ILE->getNumInits();
2943 }
2944
2945 // C++11 [over.match.list]p1:
2946 // - If no viable initializer-list constructor is found, overload resolution
2947 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002948 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002949 // elements of the initializer list.
2950 if (Result == OR_No_Viable_Function) {
2951 AsInitializerList = false;
2952 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002953 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002954 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002955 /*OnlyListConstructors=*/false,
2956 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002957 }
2958 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002959 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002960 InitializationSequence::FK_ListConstructorOverloadFailed :
2961 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002962 Result);
2963 return;
2964 }
2965
Richard Smithf4bb8d02012-07-05 08:39:21 +00002966 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002967 // If a program calls for the default initialization of an object
2968 // of a const-qualified type T, T shall be a class type with a
2969 // user-provided default constructor.
2970 if (Kind.getKind() == InitializationKind::IK_Default &&
2971 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002972 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002973 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2974 return;
2975 }
2976
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002977 // C++11 [over.match.list]p1:
2978 // In copy-list-initialization, if an explicit constructor is chosen, the
2979 // initializer is ill-formed.
2980 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2981 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2982 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2983 return;
2984 }
2985
Sebastian Redl10f04a62011-12-22 14:44:04 +00002986 // Add the constructor initialization step. Any cv-qualification conversion is
2987 // subsumed by the initialization.
2988 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002989 Sequence.AddConstructorInitializationStep(CtorDecl,
2990 Best->FoundDecl.getAccess(),
2991 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002992 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002993}
2994
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002995static bool
2996ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2997 Expr *Initializer,
2998 QualType &SourceType,
2999 QualType &UnqualifiedSourceType,
3000 QualType UnqualifiedTargetType,
3001 InitializationSequence &Sequence) {
3002 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3003 S.Context.OverloadTy) {
3004 DeclAccessPair Found;
3005 bool HadMultipleCandidates = false;
3006 if (FunctionDecl *Fn
3007 = S.ResolveAddressOfOverloadedFunction(Initializer,
3008 UnqualifiedTargetType,
3009 false, Found,
3010 &HadMultipleCandidates)) {
3011 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3012 HadMultipleCandidates);
3013 SourceType = Fn->getType();
3014 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3015 } else if (!UnqualifiedTargetType->isRecordType()) {
3016 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3017 return true;
3018 }
3019 }
3020 return false;
3021}
3022
3023static void TryReferenceInitializationCore(Sema &S,
3024 const InitializedEntity &Entity,
3025 const InitializationKind &Kind,
3026 Expr *Initializer,
3027 QualType cv1T1, QualType T1,
3028 Qualifiers T1Quals,
3029 QualType cv2T2, QualType T2,
3030 Qualifiers T2Quals,
3031 InitializationSequence &Sequence);
3032
Richard Smithf4bb8d02012-07-05 08:39:21 +00003033static void TryValueInitialization(Sema &S,
3034 const InitializedEntity &Entity,
3035 const InitializationKind &Kind,
3036 InitializationSequence &Sequence,
3037 InitListExpr *InitList = 0);
3038
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003039static void TryListInitialization(Sema &S,
3040 const InitializedEntity &Entity,
3041 const InitializationKind &Kind,
3042 InitListExpr *InitList,
3043 InitializationSequence &Sequence);
3044
3045/// \brief Attempt list initialization of a reference.
3046static void TryReferenceListInitialization(Sema &S,
3047 const InitializedEntity &Entity,
3048 const InitializationKind &Kind,
3049 InitListExpr *InitList,
3050 InitializationSequence &Sequence)
3051{
3052 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003053 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003054 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3055 return;
3056 }
3057
3058 QualType DestType = Entity.getType();
3059 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3060 Qualifiers T1Quals;
3061 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3062
3063 // Reference initialization via an initializer list works thus:
3064 // If the initializer list consists of a single element that is
3065 // reference-related to the referenced type, bind directly to that element
3066 // (possibly creating temporaries).
3067 // Otherwise, initialize a temporary with the initializer list and
3068 // bind to that.
3069 if (InitList->getNumInits() == 1) {
3070 Expr *Initializer = InitList->getInit(0);
3071 QualType cv2T2 = Initializer->getType();
3072 Qualifiers T2Quals;
3073 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3074
3075 // If this fails, creating a temporary wouldn't work either.
3076 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3077 T1, Sequence))
3078 return;
3079
3080 SourceLocation DeclLoc = Initializer->getLocStart();
3081 bool dummy1, dummy2, dummy3;
3082 Sema::ReferenceCompareResult RefRelationship
3083 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3084 dummy2, dummy3);
3085 if (RefRelationship >= Sema::Ref_Related) {
3086 // Try to bind the reference here.
3087 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3088 T1Quals, cv2T2, T2, T2Quals, Sequence);
3089 if (Sequence)
3090 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3091 return;
3092 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003093
3094 // Update the initializer if we've resolved an overloaded function.
3095 if (Sequence.step_begin() != Sequence.step_end())
3096 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003097 }
3098
3099 // Not reference-related. Create a temporary and bind to that.
3100 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3101
3102 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3103 if (Sequence) {
3104 if (DestType->isRValueReferenceType() ||
3105 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3106 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3107 else
3108 Sequence.SetFailed(
3109 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3110 }
3111}
3112
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003113/// \brief Attempt list initialization (C++0x [dcl.init.list])
3114static void TryListInitialization(Sema &S,
3115 const InitializedEntity &Entity,
3116 const InitializationKind &Kind,
3117 InitListExpr *InitList,
3118 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003119 QualType DestType = Entity.getType();
3120
Sebastian Redl14b0c192011-09-24 17:48:00 +00003121 // C++ doesn't allow scalar initialization with more than one argument.
3122 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003123 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003124 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3125 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3126 return;
3127 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003128 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003129 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003130 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003131 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003132 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003133 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003134 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003135 return;
3136 }
3137
Richard Smithf4bb8d02012-07-05 08:39:21 +00003138 // C++11 [dcl.init.list]p3:
3139 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003140 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003141 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003142 // - Otherwise, if the initializer list has no elements and T is a
3143 // class type with a default constructor, the object is
3144 // value-initialized.
3145 if (InitList->getNumInits() == 0) {
3146 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003147 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003148 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3149 return;
3150 }
3151 }
3152
3153 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3154 // an initializer_list object constructed [...]
3155 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3156 return;
3157
3158 // - Otherwise, if T is a class type, constructors are considered.
Sebastian Redld2231c92012-02-19 12:27:43 +00003159 Expr *Arg = InitList;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003160 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3161 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003162 } else
3163 Sequence.SetFailed(
3164 InitializationSequence::FK_InitListBadDestinationType);
3165 return;
3166 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003167 }
3168
Sebastian Redl14b0c192011-09-24 17:48:00 +00003169 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003170 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003171 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003172 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003173 if (CheckInitList.HadError()) {
3174 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3175 return;
3176 }
3177
3178 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003179 Sequence.AddListInitializationStep(DestType);
3180}
Douglas Gregor20093b42009-12-09 23:02:17 +00003181
3182/// \brief Try a reference initialization that involves calling a conversion
3183/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003184static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3185 const InitializedEntity &Entity,
3186 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003187 Expr *Initializer,
3188 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003190 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003191 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3192 QualType T1 = cv1T1.getUnqualifiedType();
3193 QualType cv2T2 = Initializer->getType();
3194 QualType T2 = cv2T2.getUnqualifiedType();
3195
3196 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003197 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003198 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003200 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003201 ObjCConversion,
3202 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003203 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003204 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003205 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003206 (void)ObjCLifetimeConversion;
3207
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 // Build the candidate set directly in the initialization sequence
3209 // structure, so that it will persist if we fail.
3210 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3211 CandidateSet.clear();
3212
3213 // Determine whether we are allowed to call explicit constructors or
3214 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003215 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003216 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3217
Douglas Gregor20093b42009-12-09 23:02:17 +00003218 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003219 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3220 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003221 // The type we're converting to is a class type. Enumerate its constructors
3222 // to see if there is a suitable conversion.
3223 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003224
David Blaikie3bc93e32012-12-19 00:45:41 +00003225 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003226 // The container holding the constructors can under certain conditions
3227 // be changed while iterating (e.g. because of deserialization).
3228 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003229 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003230 for (SmallVector<NamedDecl*, 16>::iterator
3231 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3232 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003233 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3234
Douglas Gregor20093b42009-12-09 23:02:17 +00003235 // Find the constructor (which may be a template).
3236 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003237 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003238 if (ConstructorTmpl)
3239 Constructor = cast<CXXConstructorDecl>(
3240 ConstructorTmpl->getTemplatedDecl());
3241 else
John McCall9aa472c2010-03-19 07:35:19 +00003242 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregor20093b42009-12-09 23:02:17 +00003244 if (!Constructor->isInvalidDecl() &&
3245 Constructor->isConvertingConstructor(AllowExplicit)) {
3246 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003247 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003248 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003249 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003250 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 else
John McCall9aa472c2010-03-19 07:35:19 +00003252 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003253 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003254 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003257 }
John McCall572fc622010-08-17 07:23:57 +00003258 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3259 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003261 const RecordType *T2RecordType = 0;
3262 if ((T2RecordType = T2->getAs<RecordType>()) &&
3263 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 // The type we're converting from is a class type, enumerate its conversion
3265 // functions.
3266 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3267
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003268 std::pair<CXXRecordDecl::conversion_iterator,
3269 CXXRecordDecl::conversion_iterator>
3270 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3271 for (CXXRecordDecl::conversion_iterator
3272 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003273 NamedDecl *D = *I;
3274 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3275 if (isa<UsingShadowDecl>(D))
3276 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277
Douglas Gregor20093b42009-12-09 23:02:17 +00003278 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3279 CXXConversionDecl *Conv;
3280 if (ConvTemplate)
3281 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3282 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003283 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284
Douglas Gregor20093b42009-12-09 23:02:17 +00003285 // If the conversion function doesn't return a reference type,
3286 // it can't be considered for this conversion unless we're allowed to
3287 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288 // FIXME: Do we need to make sure that we only consider conversion
3289 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003290 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003291 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003292 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3293 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003294 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003295 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003296 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003297 else
John McCall9aa472c2010-03-19 07:35:19 +00003298 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003299 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003300 }
3301 }
3302 }
John McCall572fc622010-08-17 07:23:57 +00003303 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3304 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305
Douglas Gregor20093b42009-12-09 23:02:17 +00003306 SourceLocation DeclLoc = Initializer->getLocStart();
3307
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003309 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003311 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003312 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003313
Douglas Gregor20093b42009-12-09 23:02:17 +00003314 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003315 // This is the overload that will be used for this initialization step if we
3316 // use this initialization. Mark it as referenced.
3317 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003318
Eli Friedman03981012009-12-11 02:42:07 +00003319 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 if (isa<CXXConversionDecl>(Function))
3321 T2 = Function->getResultType();
3322 else
3323 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003324
3325 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003326 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003327 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003328 T2.getNonLValueExprType(S.Context),
3329 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003330
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003332 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003333 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003334 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003335 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003336 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003337 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003338
Douglas Gregor20093b42009-12-09 23:02:17 +00003339 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003340 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003341 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003344 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003345 NewDerivedToBase, NewObjCConversion,
3346 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003347 if (NewRefRelationship == Sema::Ref_Incompatible) {
3348 // If the type we've converted to is not reference-related to the
3349 // type we're looking for, then there is another conversion step
3350 // we need to perform to produce a temporary of the right type
3351 // that we'll be binding to.
3352 ImplicitConversionSequence ICS;
3353 ICS.setStandard();
3354 ICS.Standard = Best->FinalConversion;
3355 T2 = ICS.Standard.getToType(2);
3356 Sequence.AddConversionSequenceStep(ICS, T2);
3357 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003358 Sequence.AddDerivedToBaseCastStep(
3359 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003361 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003362 else if (NewObjCConversion)
3363 Sequence.AddObjCObjectConversionStep(
3364 S.Context.getQualifiedType(T1,
3365 T2.getNonReferenceType().getQualifiers()));
3366
Douglas Gregor20093b42009-12-09 23:02:17 +00003367 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003368 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3371 return OR_Success;
3372}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
Richard Smith83da2e72011-10-19 16:55:56 +00003374static void CheckCXX98CompatAccessibleCopy(Sema &S,
3375 const InitializedEntity &Entity,
3376 Expr *CurInitExpr);
3377
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3379static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003380 const InitializedEntity &Entity,
3381 const InitializationKind &Kind,
3382 Expr *Initializer,
3383 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003384 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003386 Qualifiers T1Quals;
3387 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003388 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003389 Qualifiers T2Quals;
3390 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003391
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 // If the initializer is the address of an overloaded function, try
3393 // to resolve the overloaded function. If all goes well, T2 is the
3394 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003395 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3396 T1, Sequence))
3397 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003398
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003399 // Delegate everything else to a subfunction.
3400 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3401 T1Quals, cv2T2, T2, T2Quals, Sequence);
3402}
3403
Jordan Rose1fd1e282013-04-11 00:58:58 +00003404/// Converts the target of reference initialization so that it has the
3405/// appropriate qualifiers and value kind.
3406///
3407/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3408/// \code
3409/// int x;
3410/// const int &r = x;
3411/// \endcode
3412///
3413/// In this case the reference is binding to a bitfield lvalue, which isn't
3414/// valid. Perform a load to create a lifetime-extended temporary instead.
3415/// \code
3416/// const int &r = someStruct.bitfield;
3417/// \endcode
3418static ExprValueKind
3419convertQualifiersAndValueKindIfNecessary(Sema &S,
3420 InitializationSequence &Sequence,
3421 Expr *Initializer,
3422 QualType cv1T1,
3423 Qualifiers T1Quals,
3424 Qualifiers T2Quals,
3425 bool IsLValueRef) {
3426 bool IsNonAddressableType = Initializer->getBitField() ||
3427 Initializer->refersToVectorElement();
3428
3429 if (IsNonAddressableType) {
3430 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3431 // lvalue reference to a non-volatile const type, or the reference shall be
3432 // an rvalue reference.
3433 //
3434 // If not, we can't make a temporary and bind to that. Give up and allow the
3435 // error to be diagnosed later.
3436 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3437 assert(Initializer->isGLValue());
3438 return Initializer->getValueKind();
3439 }
3440
3441 // Force a load so we can materialize a temporary.
3442 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3443 return VK_RValue;
3444 }
3445
3446 if (T1Quals != T2Quals) {
3447 Sequence.AddQualificationConversionStep(cv1T1,
3448 Initializer->getValueKind());
3449 }
3450
3451 return Initializer->getValueKind();
3452}
3453
3454
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003455/// \brief Reference initialization without resolving overloaded functions.
3456static void TryReferenceInitializationCore(Sema &S,
3457 const InitializedEntity &Entity,
3458 const InitializationKind &Kind,
3459 Expr *Initializer,
3460 QualType cv1T1, QualType T1,
3461 Qualifiers T1Quals,
3462 QualType cv2T2, QualType T2,
3463 Qualifiers T2Quals,
3464 InitializationSequence &Sequence) {
3465 QualType DestType = Entity.getType();
3466 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003467 // Compute some basic properties of the types and the initializer.
3468 bool isLValueRef = DestType->isLValueReferenceType();
3469 bool isRValueRef = !isLValueRef;
3470 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003471 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003472 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003473 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003474 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003475 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003476 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003477
Douglas Gregor20093b42009-12-09 23:02:17 +00003478 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003480 // "cv2 T2" as follows:
3481 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003483 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003484 // Note the analogous bullet points for rvlaue refs to functions. Because
3485 // there are no function rvalues in C++, rvalue refs to functions are treated
3486 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003488 bool T1Function = T1->isFunctionType();
3489 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003490 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003491 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003493 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003494 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 // reference-compatible with "cv2 T2," or
3496 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003498 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003499 // can occur. However, we do pay attention to whether it is a bit-field
3500 // to decide whether we're actually binding to a temporary created from
3501 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003502 if (DerivedToBase)
3503 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003505 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003506 else if (ObjCConversion)
3507 Sequence.AddObjCObjectConversionStep(
3508 S.Context.getQualifiedType(T1, T2Quals));
3509
Jordan Rose1fd1e282013-04-11 00:58:58 +00003510 ExprValueKind ValueKind =
3511 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3512 cv1T1, T1Quals, T2Quals,
3513 isLValueRef);
3514 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003515 return;
3516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003517
3518 // - has a class type (i.e., T2 is a class type), where T1 is not
3519 // reference-related to T2, and can be implicitly converted to an
3520 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3521 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003522 // applicable conversion functions (13.3.1.6) and choosing the best
3523 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003524 // If we have an rvalue ref to function type here, the rhs must be
3525 // an rvalue.
3526 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3527 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003528 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003530 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 Sequence);
3532 if (ConvOvlResult == OR_Success)
3533 return;
John McCall1d318332010-01-12 00:44:57 +00003534 if (ConvOvlResult != OR_No_Viable_Function) {
3535 Sequence.SetOverloadFailure(
3536 InitializationSequence::FK_ReferenceInitOverloadFailed,
3537 ConvOvlResult);
3538 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 }
3540 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003541
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003542 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003543 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003544 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003545 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003546 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3547 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3548 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003549 Sequence.SetOverloadFailure(
3550 InitializationSequence::FK_ReferenceInitOverloadFailed,
3551 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003552 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003553 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003554 ? (RefRelationship == Sema::Ref_Related
3555 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3556 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3557 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003558
Douglas Gregor20093b42009-12-09 23:02:17 +00003559 return;
3560 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003561
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003562 // - If the initializer expression
3563 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3564 // "cv1 T1" is reference-compatible with "cv2 T2"
3565 // Note: functions are handled below.
3566 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003567 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003569 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003570 (InitCategory.isXValue() ||
3571 (InitCategory.isPRValue() && T2->isRecordType()) ||
3572 (InitCategory.isPRValue() && T2->isArrayType()))) {
3573 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3574 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003575 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3576 // compiler the freedom to perform a copy here or bind to the
3577 // object, while C++0x requires that we bind directly to the
3578 // object. Hence, we always bind to the object without making an
3579 // extra copy. However, in C++03 requires that we check for the
3580 // presence of a suitable copy constructor:
3581 //
3582 // The constructor that would be used to make the copy shall
3583 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003584 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003585 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003586 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003587 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003588 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003589
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003590 if (DerivedToBase)
3591 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3592 ValueKind);
3593 else if (ObjCConversion)
3594 Sequence.AddObjCObjectConversionStep(
3595 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Jordan Rose1fd1e282013-04-11 00:58:58 +00003597 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3598 Initializer, cv1T1,
3599 T1Quals, T2Quals,
3600 isLValueRef);
3601
3602 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003603 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003604 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605
3606 // - has a class type (i.e., T2 is a class type), where T1 is not
3607 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003608 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3609 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003610 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003611 if (RefRelationship == Sema::Ref_Incompatible) {
3612 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3613 Kind, Initializer,
3614 /*AllowRValues=*/true,
3615 Sequence);
3616 if (ConvOvlResult)
3617 Sequence.SetOverloadFailure(
3618 InitializationSequence::FK_ReferenceInitOverloadFailed,
3619 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620
Douglas Gregor20093b42009-12-09 23:02:17 +00003621 return;
3622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003623
Douglas Gregordefa32e2013-03-26 23:59:23 +00003624 if ((RefRelationship == Sema::Ref_Compatible ||
3625 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3626 isRValueRef && InitCategory.isLValue()) {
3627 Sequence.SetFailed(
3628 InitializationSequence::FK_RValueReferenceBindingToLValue);
3629 return;
3630 }
3631
Douglas Gregor20093b42009-12-09 23:02:17 +00003632 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3633 return;
3634 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003635
3636 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003637 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003638 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003640
Douglas Gregor20093b42009-12-09 23:02:17 +00003641 // Determine whether we are allowed to call explicit constructors or
3642 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003643 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003644
3645 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3646
John McCallf85e1932011-06-15 23:02:42 +00003647 ImplicitConversionSequence ICS
3648 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003649 /*SuppressUserConversions*/ false,
3650 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003651 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003652 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3653 /*AllowObjCWritebackConversion=*/false);
3654
3655 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003656 // FIXME: Use the conversion function set stored in ICS to turn
3657 // this into an overloading ambiguity diagnostic. However, we need
3658 // to keep that set as an OverloadCandidateSet rather than as some
3659 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003660 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3661 Sequence.SetOverloadFailure(
3662 InitializationSequence::FK_ReferenceInitOverloadFailed,
3663 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003664 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3665 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003666 else
3667 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003668 return;
John McCallf85e1932011-06-15 23:02:42 +00003669 } else {
3670 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003671 }
3672
3673 // [...] If T1 is reference-related to T2, cv1 must be the
3674 // same cv-qualification as, or greater cv-qualification
3675 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003676 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3677 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003679 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003680 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3681 return;
3682 }
3683
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003685 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003686 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003687 InitCategory.isLValue()) {
3688 Sequence.SetFailed(
3689 InitializationSequence::FK_RValueReferenceBindingToLValue);
3690 return;
3691 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692
Douglas Gregor20093b42009-12-09 23:02:17 +00003693 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3694 return;
3695}
3696
3697/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698/// (C++ [dcl.init.string], C99 6.7.8).
3699static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003700 const InitializedEntity &Entity,
3701 const InitializationKind &Kind,
3702 Expr *Initializer,
3703 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003704 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003705}
3706
Douglas Gregor71d17402009-12-15 00:01:57 +00003707/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003709 const InitializedEntity &Entity,
3710 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003711 InitializationSequence &Sequence,
3712 InitListExpr *InitList) {
3713 assert((!InitList || InitList->getNumInits() == 0) &&
3714 "Shouldn't use value-init for non-empty init lists");
3715
Richard Smith1d0c9a82012-02-14 21:14:13 +00003716 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003717 //
3718 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003719 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003720
Douglas Gregor71d17402009-12-15 00:01:57 +00003721 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003722 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723
Douglas Gregor71d17402009-12-15 00:01:57 +00003724 if (const RecordType *RT = T->getAs<RecordType>()) {
3725 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003726 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003727 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003728 // C++98:
3729 // -- if T is a class type (clause 9) with a user-declared constructor
3730 // (12.1), then the default constructor for T is called (and the
3731 // initialization is ill-formed if T has no accessible default
3732 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003733 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003734 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003735 } else {
3736 // C++11:
3737 // -- if T is a class type (clause 9) with either no default constructor
3738 // (12.1 [class.ctor]) or a default constructor that is user-provided
3739 // or deleted, then the object is default-initialized;
3740 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3741 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003742 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003743 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003744
Richard Smith1d0c9a82012-02-14 21:14:13 +00003745 // -- if T is a (possibly cv-qualified) non-union class type without a
3746 // user-provided or deleted default constructor, then the object is
3747 // zero-initialized and, if T has a non-trivial default constructor,
3748 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003749 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3750 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003751 if (NeedZeroInitialization)
3752 Sequence.AddZeroInitializationStep(Entity.getType());
3753
Richard Smithd5bc8672012-12-08 02:01:17 +00003754 // C++03:
3755 // -- if T is a non-union class type without a user-declared constructor,
3756 // then every non-static data member and base class component of T is
3757 // value-initialized;
3758 // [...] A program that calls for [...] value-initialization of an
3759 // entity of reference type is ill-formed.
3760 //
3761 // C++11 doesn't need this handling, because value-initialization does not
3762 // occur recursively there, and the implicit default constructor is
3763 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003764 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003765 ClassDecl->hasUninitializedReferenceMember()) {
3766 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3767 return;
3768 }
3769
Richard Smithf4bb8d02012-07-05 08:39:21 +00003770 // If this is list-value-initialization, pass the empty init list on when
3771 // building the constructor call. This affects the semantics of a few
3772 // things (such as whether an explicit default constructor can be called).
3773 Expr *InitListAsExpr = InitList;
3774 Expr **Args = InitList ? &InitListAsExpr : 0;
3775 unsigned NumArgs = InitList ? 1 : 0;
3776 bool InitListSyntax = InitList;
3777
3778 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3779 Sequence, InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003780 }
3781 }
3782
Douglas Gregord6542d82009-12-22 15:35:07 +00003783 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003784}
3785
Douglas Gregor99a2e602009-12-16 01:38:02 +00003786/// \brief Attempt default initialization (C++ [dcl.init]p6).
3787static void TryDefaultInitialization(Sema &S,
3788 const InitializedEntity &Entity,
3789 const InitializationKind &Kind,
3790 InitializationSequence &Sequence) {
3791 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor99a2e602009-12-16 01:38:02 +00003793 // C++ [dcl.init]p6:
3794 // To default-initialize an object of type T means:
3795 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003796 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3797
Douglas Gregor99a2e602009-12-16 01:38:02 +00003798 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3799 // constructor for T is called (and the initialization is ill-formed if
3800 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003801 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003802 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3803 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003804 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805
Douglas Gregor99a2e602009-12-16 01:38:02 +00003806 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807
Douglas Gregor99a2e602009-12-16 01:38:02 +00003808 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003810 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003811 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003812 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003813 return;
3814 }
3815
3816 // If the destination type has a lifetime property, zero-initialize it.
3817 if (DestType.getQualifiers().hasObjCLifetime()) {
3818 Sequence.AddZeroInitializationStep(Entity.getType());
3819 return;
3820 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003821}
3822
Douglas Gregor20093b42009-12-09 23:02:17 +00003823/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3824/// which enumerates all conversion functions and performs overload resolution
3825/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003827 const InitializedEntity &Entity,
3828 const InitializationKind &Kind,
3829 Expr *Initializer,
3830 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003831 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003832 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3833 QualType SourceType = Initializer->getType();
3834 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3835 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836
Douglas Gregor4a520a22009-12-14 17:27:33 +00003837 // Build the candidate set directly in the initialization sequence
3838 // structure, so that it will persist if we fail.
3839 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3840 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003841
Douglas Gregor4a520a22009-12-14 17:27:33 +00003842 // Determine whether we are allowed to call explicit constructors or
3843 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003844 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003845
Douglas Gregor4a520a22009-12-14 17:27:33 +00003846 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3847 // The type we're converting to is a class type. Enumerate its constructors
3848 // to see if there is a suitable conversion.
3849 CXXRecordDecl *DestRecordDecl
3850 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003852 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003853 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003854 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003855 // The container holding the constructors can under certain conditions
3856 // be changed while iterating. To be safe we copy the lookup results
3857 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003858 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003859 for (SmallVector<NamedDecl*, 8>::iterator
3860 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003861 Con != ConEnd; ++Con) {
3862 NamedDecl *D = *Con;
3863 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003865 // Find the constructor (which may be a template).
3866 CXXConstructorDecl *Constructor = 0;
3867 FunctionTemplateDecl *ConstructorTmpl
3868 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003869 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003870 Constructor = cast<CXXConstructorDecl>(
3871 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003872 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003873 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003875 if (!Constructor->isInvalidDecl() &&
3876 Constructor->isConvertingConstructor(AllowExplicit)) {
3877 if (ConstructorTmpl)
3878 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3879 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003880 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003881 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003882 else
3883 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003884 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003885 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003888 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003889 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003890
3891 SourceLocation DeclLoc = Initializer->getLocStart();
3892
Douglas Gregor4a520a22009-12-14 17:27:33 +00003893 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3894 // The type we're converting from is a class type, enumerate its conversion
3895 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003896
Eli Friedman33c2da92009-12-20 22:12:03 +00003897 // We can only enumerate the conversion functions for a complete type; if
3898 // the type isn't complete, simply skip this step.
3899 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3900 CXXRecordDecl *SourceRecordDecl
3901 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003903 std::pair<CXXRecordDecl::conversion_iterator,
3904 CXXRecordDecl::conversion_iterator>
3905 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3906 for (CXXRecordDecl::conversion_iterator
3907 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003908 NamedDecl *D = *I;
3909 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3910 if (isa<UsingShadowDecl>(D))
3911 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003912
Eli Friedman33c2da92009-12-20 22:12:03 +00003913 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3914 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003915 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003916 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003917 else
John McCall32daa422010-03-31 01:36:47 +00003918 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003919
Eli Friedman33c2da92009-12-20 22:12:03 +00003920 if (AllowExplicit || !Conv->isExplicit()) {
3921 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003922 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003923 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003924 CandidateSet);
3925 else
John McCall9aa472c2010-03-19 07:35:19 +00003926 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003927 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003928 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003929 }
3930 }
3931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932
3933 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003934 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003935 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003936 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003937 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003939 Result);
3940 return;
3941 }
John McCall1d318332010-01-12 00:44:57 +00003942
Douglas Gregor4a520a22009-12-14 17:27:33 +00003943 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003944 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003945 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003946
Douglas Gregor4a520a22009-12-14 17:27:33 +00003947 if (isa<CXXConstructorDecl>(Function)) {
3948 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003949 // subsumed by the initialization. Per DR5, the created temporary is of the
3950 // cv-unqualified type of the destination.
3951 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3952 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003953 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003954 return;
3955 }
3956
3957 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003958 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003959 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003960 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003961 // the resulting temporary object (possible to create an object of
3962 // a base class type). That copy is not a separate conversion, so
3963 // we just make a note of the actual destination type (possibly a
3964 // base class of the type returned by the conversion function) and
3965 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003966 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3967 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003968 return;
3969 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003970
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003971 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3972 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003974 // If the conversion following the call to the conversion function
3975 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003976 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3977 Best->FinalConversion.Third) {
3978 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003979 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003980 ICS.Standard = Best->FinalConversion;
3981 Sequence.AddConversionSequenceStep(ICS, DestType);
3982 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003983}
3984
John McCallf85e1932011-06-15 23:02:42 +00003985/// The non-zero enum values here are indexes into diagnostic alternatives.
3986enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3987
3988/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003989static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003990 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00003991 // Skip parens.
3992 e = e->IgnoreParens();
3993
3994 // Skip address-of nodes.
3995 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3996 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003997 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
3998 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003999
4000 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004001 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4002 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004003 case CK_Dependent:
4004 case CK_BitCast:
4005 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004006 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004007 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004008
4009 case CK_ArrayToPointerDecay:
4010 return IIK_nonscalar;
4011
4012 case CK_NullToPointer:
4013 return IIK_okay;
4014
4015 default:
4016 break;
4017 }
4018
4019 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004020 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004021 // set isWeakAccess to true, to mean that there will be an implicit
4022 // load which requires a cleanup.
4023 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4024 isWeakAccess = true;
4025
John McCallc03fa492011-06-27 23:59:58 +00004026 if (!isAddressOf) return IIK_nonlocal;
4027
John McCallf4b88a42012-03-10 09:33:50 +00004028 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4029 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004030
4031 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004032
4033 // If we have a conditional operator, check both sides.
4034 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004035 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4036 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004037 return iik;
4038
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004039 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004040
4041 // These are never scalar.
4042 } else if (isa<ArraySubscriptExpr>(e)) {
4043 return IIK_nonscalar;
4044
4045 // Otherwise, it needs to be a null pointer constant.
4046 } else {
4047 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4048 ? IIK_okay : IIK_nonlocal);
4049 }
4050
4051 return IIK_nonlocal;
4052}
4053
4054/// Check whether the given expression is a valid operand for an
4055/// indirect copy/restore.
4056static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4057 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004058 bool isWeakAccess = false;
4059 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4060 // If isWeakAccess to true, there will be an implicit
4061 // load which requires a cleanup.
4062 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4063 S.ExprNeedsCleanups = true;
4064
John McCallf85e1932011-06-15 23:02:42 +00004065 if (iik == IIK_okay) return;
4066
4067 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4068 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4069 << src->getSourceRange();
4070}
4071
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004072/// \brief Determine whether we have compatible array types for the
4073/// purposes of GNU by-copy array initialization.
4074static bool hasCompatibleArrayTypes(ASTContext &Context,
4075 const ArrayType *Dest,
4076 const ArrayType *Source) {
4077 // If the source and destination array types are equivalent, we're
4078 // done.
4079 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4080 return true;
4081
4082 // Make sure that the element types are the same.
4083 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4084 return false;
4085
4086 // The only mismatch we allow is when the destination is an
4087 // incomplete array type and the source is a constant array type.
4088 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4089}
4090
John McCallf85e1932011-06-15 23:02:42 +00004091static bool tryObjCWritebackConversion(Sema &S,
4092 InitializationSequence &Sequence,
4093 const InitializedEntity &Entity,
4094 Expr *Initializer) {
4095 bool ArrayDecay = false;
4096 QualType ArgType = Initializer->getType();
4097 QualType ArgPointee;
4098 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4099 ArrayDecay = true;
4100 ArgPointee = ArgArrayType->getElementType();
4101 ArgType = S.Context.getPointerType(ArgPointee);
4102 }
4103
4104 // Handle write-back conversion.
4105 QualType ConvertedArgType;
4106 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4107 ConvertedArgType))
4108 return false;
4109
4110 // We should copy unless we're passing to an argument explicitly
4111 // marked 'out'.
4112 bool ShouldCopy = true;
4113 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4114 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4115
4116 // Do we need an lvalue conversion?
4117 if (ArrayDecay || Initializer->isGLValue()) {
4118 ImplicitConversionSequence ICS;
4119 ICS.setStandard();
4120 ICS.Standard.setAsIdentityConversion();
4121
4122 QualType ResultType;
4123 if (ArrayDecay) {
4124 ICS.Standard.First = ICK_Array_To_Pointer;
4125 ResultType = S.Context.getPointerType(ArgPointee);
4126 } else {
4127 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4128 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4129 }
4130
4131 Sequence.AddConversionSequenceStep(ICS, ResultType);
4132 }
4133
4134 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4135 return true;
4136}
4137
Guy Benyei21f18c42013-02-07 10:55:47 +00004138static bool TryOCLSamplerInitialization(Sema &S,
4139 InitializationSequence &Sequence,
4140 QualType DestType,
4141 Expr *Initializer) {
4142 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4143 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4144 return false;
4145
4146 Sequence.AddOCLSamplerInitStep(DestType);
4147 return true;
4148}
4149
Guy Benyeie6b9d802013-01-20 12:31:11 +00004150//
4151// OpenCL 1.2 spec, s6.12.10
4152//
4153// The event argument can also be used to associate the
4154// async_work_group_copy with a previous async copy allowing
4155// an event to be shared by multiple async copies; otherwise
4156// event should be zero.
4157//
4158static bool TryOCLZeroEventInitialization(Sema &S,
4159 InitializationSequence &Sequence,
4160 QualType DestType,
4161 Expr *Initializer) {
4162 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4163 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4164 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4165 return false;
4166
4167 Sequence.AddOCLZeroEventStep(DestType);
4168 return true;
4169}
4170
Douglas Gregor20093b42009-12-09 23:02:17 +00004171InitializationSequence::InitializationSequence(Sema &S,
4172 const InitializedEntity &Entity,
4173 const InitializationKind &Kind,
4174 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00004175 unsigned NumArgs)
4176 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004177 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
John McCall76da55d2013-04-16 07:28:30 +00004179 // Eliminate non-overload placeholder types in the arguments. We
4180 // need to do this before checking whether types are dependent
4181 // because lowering a pseudo-object expression might well give us
4182 // something of dependent type.
4183 for (unsigned I = 0; I != NumArgs; ++I)
4184 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4185 // FIXME: should we be doing this here?
4186 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4187 if (result.isInvalid()) {
4188 SetFailed(FK_PlaceholderType);
4189 return;
4190 }
4191 Args[I] = result.take();
4192 }
4193
Douglas Gregor20093b42009-12-09 23:02:17 +00004194 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004195 // The semantics of initializers are as follows. The destination type is
4196 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004198 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004200 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004201
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004202 if (DestType->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +00004203 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004204 SequenceKind = DependentSequence;
4205 return;
4206 }
4207
Sebastian Redl7491c492011-06-05 13:59:11 +00004208 // Almost everything is a normal sequence.
4209 setSequenceKind(NormalSequence);
4210
Douglas Gregor20093b42009-12-09 23:02:17 +00004211 QualType SourceType;
4212 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004213 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004214 Initializer = Args[0];
4215 if (!isa<InitListExpr>(Initializer))
4216 SourceType = Initializer->getType();
4217 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004218
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004219 // - If the initializer is a (non-parenthesized) braced-init-list, the
4220 // object is list-initialized (8.5.4).
4221 if (Kind.getKind() != InitializationKind::IK_Direct) {
4222 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4223 TryListInitialization(S, Entity, Kind, InitList, *this);
4224 return;
4225 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227
Douglas Gregor20093b42009-12-09 23:02:17 +00004228 // - If the destination type is a reference type, see 8.5.3.
4229 if (DestType->isReferenceType()) {
4230 // C++0x [dcl.init.ref]p1:
4231 // A variable declared to be a T& or T&&, that is, "reference to type T"
4232 // (8.3.2), shall be initialized by an object, or function, of type T or
4233 // by an object that can be converted into a T.
4234 // (Therefore, multiple arguments are not permitted.)
4235 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004236 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004237 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004238 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004239 return;
4240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004241
Douglas Gregor20093b42009-12-09 23:02:17 +00004242 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004243 if (Kind.getKind() == InitializationKind::IK_Value ||
4244 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004245 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004246 return;
4247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004248
Douglas Gregor99a2e602009-12-16 01:38:02 +00004249 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004250 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004251 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004252 return;
4253 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004254
John McCallce6c9b72011-02-21 07:22:22 +00004255 // - If the destination type is an array of characters, an array of
4256 // char16_t, an array of char32_t, or an array of wchar_t, and the
4257 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004259 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004260 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004261 if (Initializer && isa<VariableArrayType>(DestAT)) {
4262 SetFailed(FK_VariableLengthArrayHasInitializer);
4263 return;
4264 }
4265
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004266 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004267 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004268 return;
4269 }
4270
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004271 // Note: as an GNU C extension, we allow initialization of an
4272 // array from a compound literal that creates an array of the same
4273 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004274 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004275 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4276 Initializer->getType()->isArrayType()) {
4277 const ArrayType *SourceAT
4278 = Context.getAsArrayType(Initializer->getType());
4279 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004280 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004281 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004282 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004283 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004284 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004285 }
Richard Smith0f163e92012-02-15 22:38:09 +00004286 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004287 // Note: as a GNU C++ extension, we allow list-initialization of a
4288 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004289 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004290 Entity.getKind() == InitializedEntity::EK_Member &&
4291 Initializer && isa<InitListExpr>(Initializer)) {
4292 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4293 *this);
4294 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004295 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004296 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004297 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004298 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004299
Douglas Gregor20093b42009-12-09 23:02:17 +00004300 return;
4301 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004302
John McCallf85e1932011-06-15 23:02:42 +00004303 // Determine whether we should consider writeback conversions for
4304 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004305 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004306 Entity.getKind() == InitializedEntity::EK_Parameter;
4307
4308 // We're at the end of the line for C: it's either a write-back conversion
4309 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004310 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004311 // If allowed, check whether this is an Objective-C writeback conversion.
4312 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004313 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004314 return;
4315 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004316
4317 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4318 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004319
4320 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4321 return;
4322
John McCallf85e1932011-06-15 23:02:42 +00004323 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004324 AddCAssignmentStep(DestType);
4325 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004326 return;
4327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004328
David Blaikie4e4d0842012-03-11 07:00:24 +00004329 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004330
Douglas Gregor20093b42009-12-09 23:02:17 +00004331 // - If the destination type is a (possibly cv-qualified) class type:
4332 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004333 // - If the initialization is direct-initialization, or if it is
4334 // copy-initialization where the cv-unqualified version of the
4335 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004336 // class of the destination, constructors are considered. [...]
4337 if (Kind.getKind() == InitializationKind::IK_Direct ||
4338 (Kind.getKind() == InitializationKind::IK_Copy &&
4339 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4340 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004341 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004342 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004344 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004345 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004346 // used) to a derived class thereof are enumerated as described in
4347 // 13.3.1.4, and the best one is chosen through overload resolution
4348 // (13.3).
4349 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004350 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004351 return;
4352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353
Douglas Gregor99a2e602009-12-16 01:38:02 +00004354 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004355 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004356 return;
4357 }
4358 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359
4360 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004361 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004362 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004363 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4364 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004365 return;
4366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004367
Douglas Gregor20093b42009-12-09 23:02:17 +00004368 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004369 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004370 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004371 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004372 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004373
4374 ImplicitConversionSequence ICS
4375 = S.TryImplicitConversion(Initializer, Entity.getType(),
4376 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004377 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004378 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004379 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4380 allowObjCWritebackConversion);
4381
4382 if (ICS.isStandard() &&
4383 ICS.Standard.Second == ICK_Writeback_Conversion) {
4384 // Objective-C ARC writeback conversion.
4385
4386 // We should copy unless we're passing to an argument explicitly
4387 // marked 'out'.
4388 bool ShouldCopy = true;
4389 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4390 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4391
4392 // If there was an lvalue adjustment, add it as a separate conversion.
4393 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4394 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4395 ImplicitConversionSequence LvalueICS;
4396 LvalueICS.setStandard();
4397 LvalueICS.Standard.setAsIdentityConversion();
4398 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4399 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004400 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004401 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004402
4403 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004404 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004405 DeclAccessPair dap;
4406 if (Initializer->getType() == Context.OverloadTy &&
4407 !S.ResolveAddressOfOverloadedFunction(Initializer
4408 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004409 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004410 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004411 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004412 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004413 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004414
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004415 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004416 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004417}
4418
4419InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004420 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004421 StepEnd = Steps.end();
4422 Step != StepEnd; ++Step)
4423 Step->Destroy();
4424}
4425
4426//===----------------------------------------------------------------------===//
4427// Perform initialization
4428//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004429static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004430getAssignmentAction(const InitializedEntity &Entity) {
4431 switch(Entity.getKind()) {
4432 case InitializedEntity::EK_Variable:
4433 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004434 case InitializedEntity::EK_Exception:
4435 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004436 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004437 return Sema::AA_Initializing;
4438
4439 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004440 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004441 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4442 return Sema::AA_Sending;
4443
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004444 return Sema::AA_Passing;
4445
4446 case InitializedEntity::EK_Result:
4447 return Sema::AA_Returning;
4448
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004449 case InitializedEntity::EK_Temporary:
4450 // FIXME: Can we tell apart casting vs. converting?
4451 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004452
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004453 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004454 case InitializedEntity::EK_ArrayElement:
4455 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004456 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004457 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004458 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004459 return Sema::AA_Initializing;
4460 }
4461
David Blaikie7530c032012-01-17 06:56:22 +00004462 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004463}
4464
Richard Smith774d8b42013-01-08 00:08:23 +00004465/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004466/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004467static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004468 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004469 case InitializedEntity::EK_ArrayElement:
4470 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004471 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004472 case InitializedEntity::EK_New:
4473 case InitializedEntity::EK_Variable:
4474 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004475 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004476 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004477 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004478 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004479 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004480 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004481 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004483 case InitializedEntity::EK_Parameter:
4484 case InitializedEntity::EK_Temporary:
4485 return true;
4486 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004488 llvm_unreachable("missed an InitializedEntity kind?");
4489}
4490
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004491/// \brief Whether the given entity, when initialized with an object
4492/// created for that initialization, requires destruction.
4493static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4494 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004495 case InitializedEntity::EK_Result:
4496 case InitializedEntity::EK_New:
4497 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004498 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004499 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004500 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004501 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004502 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004503 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504
Richard Smith774d8b42013-01-08 00:08:23 +00004505 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004506 case InitializedEntity::EK_Variable:
4507 case InitializedEntity::EK_Parameter:
4508 case InitializedEntity::EK_Temporary:
4509 case InitializedEntity::EK_ArrayElement:
4510 case InitializedEntity::EK_Exception:
4511 return true;
4512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513
4514 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004515}
4516
Richard Smith83da2e72011-10-19 16:55:56 +00004517/// \brief Look for copy and move constructors and constructor templates, for
4518/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4519static void LookupCopyAndMoveConstructors(Sema &S,
4520 OverloadCandidateSet &CandidateSet,
4521 CXXRecordDecl *Class,
4522 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004523 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004524 // The container holding the constructors can under certain conditions
4525 // be changed while iterating (e.g. because of deserialization).
4526 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004527 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004528 for (SmallVector<NamedDecl*, 16>::iterator
4529 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4530 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004531 CXXConstructorDecl *Constructor = 0;
4532
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004533 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004534 // Handle copy/moveconstructors, only.
4535 if (!Constructor || Constructor->isInvalidDecl() ||
4536 !Constructor->isCopyOrMoveConstructor() ||
4537 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4538 continue;
4539
4540 DeclAccessPair FoundDecl
4541 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4542 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004543 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004544 continue;
4545 }
4546
4547 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004548 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004549 if (ConstructorTmpl->isInvalidDecl())
4550 continue;
4551
4552 Constructor = cast<CXXConstructorDecl>(
4553 ConstructorTmpl->getTemplatedDecl());
4554 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4555 continue;
4556
4557 // FIXME: Do we need to limit this to copy-constructor-like
4558 // candidates?
4559 DeclAccessPair FoundDecl
4560 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4561 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004562 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004563 }
4564}
4565
4566/// \brief Get the location at which initialization diagnostics should appear.
4567static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4568 Expr *Initializer) {
4569 switch (Entity.getKind()) {
4570 case InitializedEntity::EK_Result:
4571 return Entity.getReturnLoc();
4572
4573 case InitializedEntity::EK_Exception:
4574 return Entity.getThrowLoc();
4575
4576 case InitializedEntity::EK_Variable:
4577 return Entity.getDecl()->getLocation();
4578
Douglas Gregor47736542012-02-15 16:57:26 +00004579 case InitializedEntity::EK_LambdaCapture:
4580 return Entity.getCaptureLoc();
4581
Richard Smith83da2e72011-10-19 16:55:56 +00004582 case InitializedEntity::EK_ArrayElement:
4583 case InitializedEntity::EK_Member:
4584 case InitializedEntity::EK_Parameter:
4585 case InitializedEntity::EK_Temporary:
4586 case InitializedEntity::EK_New:
4587 case InitializedEntity::EK_Base:
4588 case InitializedEntity::EK_Delegating:
4589 case InitializedEntity::EK_VectorElement:
4590 case InitializedEntity::EK_ComplexElement:
4591 case InitializedEntity::EK_BlockElement:
4592 return Initializer->getLocStart();
4593 }
4594 llvm_unreachable("missed an InitializedEntity kind?");
4595}
4596
Douglas Gregor523d46a2010-04-18 07:40:54 +00004597/// \brief Make a (potentially elidable) temporary copy of the object
4598/// provided by the given initializer by calling the appropriate copy
4599/// constructor.
4600///
4601/// \param S The Sema object used for type-checking.
4602///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004603/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004604/// the type of the initializer expression or a superclass thereof.
4605///
James Dennett1dfbd922012-06-14 21:40:34 +00004606/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004607///
4608/// \param CurInit The initializer expression.
4609///
4610/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4611/// is permitted in C++03 (but not C++0x) when binding a reference to
4612/// an rvalue.
4613///
4614/// \returns An expression that copies the initializer expression into
4615/// a temporary object, or an error expression if a copy could not be
4616/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004617static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004618 QualType T,
4619 const InitializedEntity &Entity,
4620 ExprResult CurInit,
4621 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004622 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004623 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004624 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004625 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004626 Class = cast<CXXRecordDecl>(Record->getDecl());
4627 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004628 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004629
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004630 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004631 // When certain criteria are met, an implementation is allowed to
4632 // omit the copy/move construction of a class object, even if the
4633 // copy/move constructor and/or destructor for the object have
4634 // side effects. [...]
4635 // - when a temporary class object that has not been bound to a
4636 // reference (12.2) would be copied/moved to a class object
4637 // with the same cv-unqualified type, the copy/move operation
4638 // can be omitted by constructing the temporary object
4639 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004641 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004642 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004643 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004644 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004645 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004646 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004649 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004650 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004651
Douglas Gregorcc15f012011-01-21 19:38:21 +00004652 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004653 // Only consider constructors and constructor templates. Per
4654 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4655 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004656 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004657 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004659 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4660
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004661 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004662 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004663 case OR_Success:
4664 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004665
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004666 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004667 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4668 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4669 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004670 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004671 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004672 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004673 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004674 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004675 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004677 case OR_Ambiguous:
4678 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004679 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004680 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004681 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004682 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004683
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004684 case OR_Deleted:
4685 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004686 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004687 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004689 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004690 }
4691
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004692 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004693 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004694 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004695
Anders Carlsson9a68a672010-04-21 18:47:17 +00004696 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004697 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004698
4699 if (IsExtraneousCopy) {
4700 // If this is a totally extraneous copy for C++03 reference
4701 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004702 // expression. We don't generate an (elided) copy operation here
4703 // because doing so would require us to pass down a flag to avoid
4704 // infinite recursion, where each step adds another extraneous,
4705 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004706
Douglas Gregor2559a702010-04-18 07:57:34 +00004707 // Instantiate the default arguments of any extra parameters in
4708 // the selected copy constructor, as if we were going to create a
4709 // proper call to the copy constructor.
4710 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4711 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4712 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004713 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004714 break;
4715
4716 // Build the default argument expression; we don't actually care
4717 // if this succeeds or not, because this routine will complain
4718 // if there was a problem.
4719 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4720 }
4721
Douglas Gregor523d46a2010-04-18 07:40:54 +00004722 return S.Owned(CurInitExpr);
4723 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004724
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004725 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004726 // constructor call (we might have derived-to-base conversions, or
4727 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004728 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004729 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004730 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004731
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004732 // Actually perform the constructor call.
4733 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004734 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004735 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004736 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004737 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004738 CXXConstructExpr::CK_Complete,
4739 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004740
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004741 // If we're supposed to bind temporaries, do so.
4742 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4743 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004744 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004745}
Douglas Gregor20093b42009-12-09 23:02:17 +00004746
Richard Smith83da2e72011-10-19 16:55:56 +00004747/// \brief Check whether elidable copy construction for binding a reference to
4748/// a temporary would have succeeded if we were building in C++98 mode, for
4749/// -Wc++98-compat.
4750static void CheckCXX98CompatAccessibleCopy(Sema &S,
4751 const InitializedEntity &Entity,
4752 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004753 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004754
4755 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4756 if (!Record)
4757 return;
4758
4759 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4760 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4761 == DiagnosticsEngine::Ignored)
4762 return;
4763
4764 // Find constructors which would have been considered.
4765 OverloadCandidateSet CandidateSet(Loc);
4766 LookupCopyAndMoveConstructors(
4767 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4768
4769 // Perform overload resolution.
4770 OverloadCandidateSet::iterator Best;
4771 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4772
4773 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4774 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4775 << CurInitExpr->getSourceRange();
4776
4777 switch (OR) {
4778 case OR_Success:
4779 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004780 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004781 // FIXME: Check default arguments as far as that's possible.
4782 break;
4783
4784 case OR_No_Viable_Function:
4785 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004786 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004787 break;
4788
4789 case OR_Ambiguous:
4790 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004791 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004792 break;
4793
4794 case OR_Deleted:
4795 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004796 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004797 break;
4798 }
4799}
4800
Douglas Gregora41a8c52010-04-22 00:20:18 +00004801void InitializationSequence::PrintInitLocationNote(Sema &S,
4802 const InitializedEntity &Entity) {
4803 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4804 if (Entity.getDecl()->getLocation().isInvalid())
4805 return;
4806
4807 if (Entity.getDecl()->getDeclName())
4808 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4809 << Entity.getDecl()->getDeclName();
4810 else
4811 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4812 }
4813}
4814
Sebastian Redl3b802322011-07-14 19:07:55 +00004815static bool isReferenceBinding(const InitializationSequence::Step &s) {
4816 return s.Kind == InitializationSequence::SK_BindReference ||
4817 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4818}
4819
Sebastian Redl10f04a62011-12-22 14:44:04 +00004820static ExprResult
4821PerformConstructorInitialization(Sema &S,
4822 const InitializedEntity &Entity,
4823 const InitializationKind &Kind,
4824 MultiExprArg Args,
4825 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004826 bool &ConstructorInitRequiresZeroInit,
4827 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004828 unsigned NumArgs = Args.size();
4829 CXXConstructorDecl *Constructor
4830 = cast<CXXConstructorDecl>(Step.Function.Function);
4831 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4832
4833 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004834 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004835 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4836 ? Kind.getEqualLoc()
4837 : Kind.getLocation();
4838
4839 if (Kind.getKind() == InitializationKind::IK_Default) {
4840 // Force even a trivial, implicit default constructor to be
4841 // semantically checked. We do this explicitly because we don't build
4842 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004843 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004844 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004845 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004846 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4847 }
4848
4849 ExprResult CurInit = S.Owned((Expr *)0);
4850
Douglas Gregored878af2012-02-24 23:56:31 +00004851 // C++ [over.match.copy]p1:
4852 // - When initializing a temporary to be bound to the first parameter
4853 // of a constructor that takes a reference to possibly cv-qualified
4854 // T as its first argument, called with a single argument in the
4855 // context of direct-initialization, explicit conversion functions
4856 // are also considered.
4857 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4858 Args.size() == 1 &&
4859 Constructor->isCopyOrMoveConstructor();
4860
Sebastian Redl10f04a62011-12-22 14:44:04 +00004861 // Determine the arguments required to actually perform the constructor
4862 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004863 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004864 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004865 AllowExplicitConv,
4866 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004867 return ExprError();
4868
4869
4870 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004871 (Kind.getKind() == InitializationKind::IK_DirectList ||
4872 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4873 (Kind.getKind() == InitializationKind::IK_Direct ||
4874 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004875 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004876 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004877 S.DiagnoseUseOfDecl(Constructor, Loc);
4878
4879 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4880 if (!TSInfo)
4881 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004882 SourceRange ParenRange;
4883 if (Kind.getKind() != InitializationKind::IK_DirectList)
4884 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004885
Richard Smithc83c2302012-12-19 01:39:02 +00004886 CurInit = S.Owned(
4887 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4888 TSInfo, ConstructorArgs,
4889 ParenRange, IsListInitialization,
4890 HadMultipleCandidates,
4891 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004892 } else {
4893 CXXConstructExpr::ConstructionKind ConstructKind =
4894 CXXConstructExpr::CK_Complete;
4895
4896 if (Entity.getKind() == InitializedEntity::EK_Base) {
4897 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4898 CXXConstructExpr::CK_VirtualBase :
4899 CXXConstructExpr::CK_NonVirtualBase;
4900 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4901 ConstructKind = CXXConstructExpr::CK_Delegating;
4902 }
4903
4904 // Only get the parenthesis range if it is a direct construction.
4905 SourceRange parenRange =
4906 Kind.getKind() == InitializationKind::IK_Direct ?
4907 Kind.getParenRange() : SourceRange();
4908
4909 // If the entity allows NRVO, mark the construction as elidable
4910 // unconditionally.
4911 if (Entity.allowsNRVO())
4912 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4913 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004914 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004915 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004916 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004917 ConstructorInitRequiresZeroInit,
4918 ConstructKind,
4919 parenRange);
4920 else
4921 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4922 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004923 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004924 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004925 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004926 ConstructorInitRequiresZeroInit,
4927 ConstructKind,
4928 parenRange);
4929 }
4930 if (CurInit.isInvalid())
4931 return ExprError();
4932
4933 // Only check access if all of that succeeded.
4934 S.CheckConstructorAccess(Loc, Constructor, Entity,
4935 Step.Function.FoundDecl.getAccess());
4936 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4937
4938 if (shouldBindAsTemporary(Entity))
4939 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4940
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004941 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004942}
4943
Richard Smith36d02af2012-06-04 22:27:30 +00004944/// Determine whether the specified InitializedEntity definitely has a lifetime
4945/// longer than the current full-expression. Conservatively returns false if
4946/// it's unclear.
4947static bool
4948InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4949 const InitializedEntity *Top = &Entity;
4950 while (Top->getParent())
4951 Top = Top->getParent();
4952
4953 switch (Top->getKind()) {
4954 case InitializedEntity::EK_Variable:
4955 case InitializedEntity::EK_Result:
4956 case InitializedEntity::EK_Exception:
4957 case InitializedEntity::EK_Member:
4958 case InitializedEntity::EK_New:
4959 case InitializedEntity::EK_Base:
4960 case InitializedEntity::EK_Delegating:
4961 return true;
4962
4963 case InitializedEntity::EK_ArrayElement:
4964 case InitializedEntity::EK_VectorElement:
4965 case InitializedEntity::EK_BlockElement:
4966 case InitializedEntity::EK_ComplexElement:
4967 // Could not determine what the full initialization is. Assume it might not
4968 // outlive the full-expression.
4969 return false;
4970
4971 case InitializedEntity::EK_Parameter:
4972 case InitializedEntity::EK_Temporary:
4973 case InitializedEntity::EK_LambdaCapture:
4974 // The entity being initialized might not outlive the full-expression.
4975 return false;
4976 }
4977
4978 llvm_unreachable("unknown entity kind");
4979}
4980
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004981ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004982InitializationSequence::Perform(Sema &S,
4983 const InitializedEntity &Entity,
4984 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004985 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004986 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004987 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004988 unsigned NumArgs = Args.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004989 Diagnose(S, Entity, Kind, Args.data(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004990 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004992
Sebastian Redl7491c492011-06-05 13:59:11 +00004993 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004994 // If the declaration is a non-dependent, incomplete array type
4995 // that has an initializer, then its type will be completed once
4996 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004997 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004998 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004999 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005000 if (const IncompleteArrayType *ArrayT
5001 = S.Context.getAsIncompleteArrayType(DeclType)) {
5002 // FIXME: We don't currently have the ability to accurately
5003 // compute the length of an initializer list without
5004 // performing full type-checking of the initializer list
5005 // (since we have to determine where braces are implicitly
5006 // introduced and such). So, we fall back to making the array
5007 // type a dependently-sized array type with no specified
5008 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005009 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005010 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005011
Douglas Gregord87b61f2009-12-10 17:56:55 +00005012 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005013 if (DeclaratorDecl *DD = Entity.getDecl()) {
5014 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5015 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005016 if (IncompleteArrayTypeLoc ArrayLoc =
5017 TL.getAs<IncompleteArrayTypeLoc>())
5018 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005019 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005020 }
5021
5022 *ResultType
5023 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5024 /*NumElts=*/0,
5025 ArrayT->getSizeModifier(),
5026 ArrayT->getIndexTypeCVRQualifiers(),
5027 Brackets);
5028 }
5029
5030 }
5031 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005032 if (Kind.getKind() == InitializationKind::IK_Direct &&
5033 !Kind.isExplicitCast()) {
5034 // Rebuild the ParenListExpr.
5035 SourceRange ParenRange = Kind.getParenRange();
5036 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005037 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005038 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005039 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005040 Kind.isExplicitCast() ||
5041 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005042 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005043 }
5044
Sebastian Redl7491c492011-06-05 13:59:11 +00005045 // No steps means no initialization.
5046 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005047 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048
Richard Smith80ad52f2013-01-02 11:42:31 +00005049 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005050 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005051 Entity.getKind() != InitializedEntity::EK_Parameter) {
5052 // Produce a C++98 compatibility warning if we are initializing a reference
5053 // from an initializer list. For parameters, we produce a better warning
5054 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005055 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005056 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5057 << Init->getSourceRange();
5058 }
5059
Richard Smith36d02af2012-06-04 22:27:30 +00005060 // Diagnose cases where we initialize a pointer to an array temporary, and the
5061 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005062 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005063 Entity.getType()->isPointerType() &&
5064 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005065 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005066 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5067 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5068 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5069 << Init->getSourceRange();
5070 }
5071
Douglas Gregord6542d82009-12-22 15:35:07 +00005072 QualType DestType = Entity.getType().getNonReferenceType();
5073 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005074 // the same as Entity.getDecl()->getType() in cases involving type merging,
5075 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005076 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005077 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005078 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005079
John McCall60d7b3a2010-08-24 06:29:42 +00005080 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005081
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005083 // grab the only argument out the Args and place it into the "current"
5084 // initializer.
5085 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005086 case SK_ResolveAddressOfOverloadedFunction:
5087 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005088 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005089 case SK_CastDerivedToBaseLValue:
5090 case SK_BindReference:
5091 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005092 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005093 case SK_UserConversion:
5094 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005095 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005096 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005097 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005098 case SK_ConversionSequence:
5099 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005100 case SK_UnwrapInitList:
5101 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005102 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005103 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005104 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005105 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005106 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005107 case SK_PassByIndirectCopyRestore:
5108 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005109 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005110 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005111 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005112 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005113 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005114 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005115 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005116 break;
John McCallf6a16482010-12-04 03:47:34 +00005117 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005119 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005120 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005121 case SK_ZeroInitialization:
5122 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005124
5125 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005126 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005127 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005128 for (step_iterator Step = step_begin(), StepEnd = step_end();
5129 Step != StepEnd; ++Step) {
5130 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005131 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132
John Wiegley429bb272011-04-08 18:41:53 +00005133 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
Douglas Gregor20093b42009-12-09 23:02:17 +00005135 switch (Step->Kind) {
5136 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005138 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005139 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00005140 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005141 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005142 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005143 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005144 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Douglas Gregor20093b42009-12-09 23:02:17 +00005146 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005147 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005148 case SK_CastDerivedToBaseLValue: {
5149 // We have a derived-to-base cast that produces either an rvalue or an
5150 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005151
John McCallf871d0c2010-08-07 06:22:56 +00005152 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005153
Douglas Gregor20093b42009-12-09 23:02:17 +00005154 // Casts to inaccessible base classes are allowed with C-style casts.
5155 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5156 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005157 CurInit.get()->getLocStart(),
5158 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005159 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005160 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005161
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005162 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5163 QualType T = SourceType;
5164 if (const PointerType *Pointer = T->getAs<PointerType>())
5165 T = Pointer->getPointeeType();
5166 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005167 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005168 cast<CXXRecordDecl>(RecordTy->getDecl()));
5169 }
5170
John McCall5baba9d2010-08-25 10:28:54 +00005171 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005172 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005173 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005174 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005175 VK_XValue :
5176 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005177 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5178 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005179 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005180 CurInit.get(),
5181 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005182 break;
5183 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005184
Douglas Gregor20093b42009-12-09 23:02:17 +00005185 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005186 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005187 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5188 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005189 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005190 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005191 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005192 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005193 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005194 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005195
John Wiegley429bb272011-04-08 18:41:53 +00005196 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005197 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005198 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5199 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005200 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005201 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005202 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005204
Douglas Gregor20093b42009-12-09 23:02:17 +00005205 // Reference binding does not have any corresponding ASTs.
5206
5207 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005208 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005209 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005210
Douglas Gregor20093b42009-12-09 23:02:17 +00005211 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005212
Douglas Gregor20093b42009-12-09 23:02:17 +00005213 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005214 // Make sure the "temporary" is actually an rvalue.
5215 assert(CurInit.get()->isRValue() && "not a temporary");
5216
Douglas Gregor20093b42009-12-09 23:02:17 +00005217 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005218 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005219 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005220
Douglas Gregor03e80032011-06-21 17:03:29 +00005221 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005222 CurInit = new (S.Context) MaterializeTemporaryExpr(
5223 Entity.getType().getNonReferenceType(),
5224 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005225 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005226
5227 // If we're binding to an Objective-C object that has lifetime, we
5228 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005229 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005230 CurInit.get()->getType()->isObjCLifetimeType())
5231 S.ExprNeedsCleanups = true;
5232
Douglas Gregor20093b42009-12-09 23:02:17 +00005233 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005234
Douglas Gregor523d46a2010-04-18 07:40:54 +00005235 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005236 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005237 /*IsExtraneousCopy=*/true);
5238 break;
5239
Douglas Gregor20093b42009-12-09 23:02:17 +00005240 case SK_UserConversion: {
5241 // We have a user-defined conversion that invokes either a constructor
5242 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005243 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005244 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005245 FunctionDecl *Fn = Step->Function.Function;
5246 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005247 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005248 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005249 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005250 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005251 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005252 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005253 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005254
Douglas Gregor20093b42009-12-09 23:02:17 +00005255 // Determine the arguments required to actually perform the constructor
5256 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005257 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005258 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005259 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005260 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005261 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005263 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005264 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005265 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005266 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005267 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005268 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005269 CXXConstructExpr::CK_Complete,
5270 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005271 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005272 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005273
Anders Carlsson9a68a672010-04-21 18:47:17 +00005274 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005275 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005276 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005277
John McCall2de56d12010-08-25 11:45:40 +00005278 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005279 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5280 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5281 S.IsDerivedFrom(SourceType, Class))
5282 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005283
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005284 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005285 } else {
5286 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005287 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005288 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005289 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005290 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005291
5292 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005293 // derived-to-base conversion? I believe the answer is "no", because
5294 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005295 ExprResult CurInitExprRes =
5296 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5297 FoundFn, Conversion);
5298 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005299 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005300 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005301
Douglas Gregor20093b42009-12-09 23:02:17 +00005302 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005303 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5304 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005305 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005306 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005307
John McCall2de56d12010-08-25 11:45:40 +00005308 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005309
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005310 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005312
Sebastian Redl3b802322011-07-14 19:07:55 +00005313 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005314 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5315
5316 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005317 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005318 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005319 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005320 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005321 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005322 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005323 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005324 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005325 }
5326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005327
John McCallf871d0c2010-08-07 06:22:56 +00005328 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005329 CurInit.get()->getType(),
5330 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005331 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005332 if (MaybeBindToTemp)
5333 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005334 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005335 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005336 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005337 break;
5338 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005339
Douglas Gregor20093b42009-12-09 23:02:17 +00005340 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005341 case SK_QualificationConversionXValue:
5342 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005343 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005344 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005345 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005346 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005347 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005348 VK_XValue :
5349 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005350 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005351 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005352 }
5353
Jordan Rose1fd1e282013-04-11 00:58:58 +00005354 case SK_LValueToRValue: {
5355 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5356 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5357 CK_LValueToRValue,
5358 CurInit.take(),
5359 /*BasePath=*/0,
5360 VK_RValue));
5361 break;
5362 }
5363
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005364 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005365 Sema::CheckedConversionKind CCK
5366 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5367 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005368 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005369 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005370 ExprResult CurInitExprRes =
5371 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005372 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005373 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005374 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005375 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005376 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005377 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005378
Douglas Gregord87b61f2009-12-10 17:56:55 +00005379 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005380 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005381 // Hack: We must pass *ResultType if available in order to set the type
5382 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5383 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5384 // temporary, not a reference, so we should pass Ty.
5385 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5386 // Since this step is never used for a reference directly, we explicitly
5387 // unwrap references here and rewrap them afterwards.
5388 // We also need to create a InitializeTemporary entity for this.
5389 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005390 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005391 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005392 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5393 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005394 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005395 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005396 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005397 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005398 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005399
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005400 if (ResultType) {
5401 if ((*ResultType)->isRValueReferenceType())
5402 Ty = S.Context.getRValueReferenceType(Ty);
5403 else if ((*ResultType)->isLValueReferenceType())
5404 Ty = S.Context.getLValueReferenceType(Ty,
5405 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5406 *ResultType = Ty;
5407 }
5408
5409 InitListExpr *StructuredInitList =
5410 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005411 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005412 CurInit = shouldBindAsTemporary(InitEntity)
5413 ? S.MaybeBindToTemporary(StructuredInitList)
5414 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005415 break;
5416 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005417
Sebastian Redl10f04a62011-12-22 14:44:04 +00005418 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005419 // When an initializer list is passed for a parameter of type "reference
5420 // to object", we don't get an EK_Temporary entity, but instead an
5421 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005422 // FIXME: This is a hack. What we really should do is create a user
5423 // conversion step for this case, but this makes it considerably more
5424 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005425 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5426 Entity.getType().getNonReferenceType());
5427 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005428 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005429 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005430 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5431 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005432 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005433 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5434 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005435 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005436 ConstructorInitRequiresZeroInit,
5437 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005438 break;
5439 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005440
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005441 case SK_UnwrapInitList:
5442 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5443 break;
5444
5445 case SK_RewrapInitList: {
5446 Expr *E = CurInit.take();
5447 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5448 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005449 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005450 ILE->setSyntacticForm(Syntactic);
5451 ILE->setType(E->getType());
5452 ILE->setValueKind(E->getValueKind());
5453 CurInit = S.Owned(ILE);
5454 break;
5455 }
5456
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005457 case SK_ConstructorInitialization: {
5458 // When an initializer list is passed for a parameter of type "reference
5459 // to object", we don't get an EK_Temporary entity, but instead an
5460 // EK_Parameter entity with reference type.
5461 // FIXME: This is a hack. What we really should do is create a user
5462 // conversion step for this case, but this makes it considerably more
5463 // complicated. For now, this will do.
5464 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5465 Entity.getType().getNonReferenceType());
5466 bool UseTemporary = Entity.getType()->isReferenceType();
5467 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5468 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005469 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005470 ConstructorInitRequiresZeroInit,
5471 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005472 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005474
Douglas Gregor71d17402009-12-15 00:01:57 +00005475 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005476 step_iterator NextStep = Step;
5477 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005478 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005479 (NextStep->Kind == SK_ConstructorInitialization ||
5480 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005481 // The need for zero-initialization is recorded directly into
5482 // the call to the object's constructor within the next step.
5483 ConstructorInitRequiresZeroInit = true;
5484 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005485 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005486 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005487 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5488 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005489 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005490 Kind.getRange().getBegin());
5491
5492 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5493 TSInfo->getType().getNonLValueExprType(S.Context),
5494 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005495 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005496 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005497 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005498 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005499 break;
5500 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005501
5502 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005503 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005504 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005505 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005506 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5507 if (Result.isInvalid())
5508 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005509 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005510
5511 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005512 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005513 if (ConvTy != Sema::Compatible &&
5514 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005515 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005516 == Sema::Compatible)
5517 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005518 if (CurInitExprRes.isInvalid())
5519 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005520 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005521
Douglas Gregora41a8c52010-04-22 00:20:18 +00005522 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005523 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5524 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005525 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005526 getAssignmentAction(Entity),
5527 &Complained)) {
5528 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005529 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005530 } else if (Complained)
5531 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005532 break;
5533 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005534
5535 case SK_StringInit: {
5536 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005537 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005538 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005539 break;
5540 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005541
5542 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005543 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005544 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005545 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005546 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005547
5548 case SK_ArrayInit:
5549 // Okay: we checked everything before creating this step. Note that
5550 // this is a GNU extension.
5551 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005552 << Step->Type << CurInit.get()->getType()
5553 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005554
5555 // If the destination type is an incomplete array type, update the
5556 // type accordingly.
5557 if (ResultType) {
5558 if (const IncompleteArrayType *IncompleteDest
5559 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5560 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005561 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005562 *ResultType = S.Context.getConstantArrayType(
5563 IncompleteDest->getElementType(),
5564 ConstantSource->getSize(),
5565 ArrayType::Normal, 0);
5566 }
5567 }
5568 }
John McCallf85e1932011-06-15 23:02:42 +00005569 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005570
Richard Smith0f163e92012-02-15 22:38:09 +00005571 case SK_ParenthesizedArrayInit:
5572 // Okay: we checked everything before creating this step. Note that
5573 // this is a GNU extension.
5574 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5575 << CurInit.get()->getSourceRange();
5576 break;
5577
John McCallf85e1932011-06-15 23:02:42 +00005578 case SK_PassByIndirectCopyRestore:
5579 case SK_PassByIndirectRestore:
5580 checkIndirectCopyRestoreSource(S, CurInit.get());
5581 CurInit = S.Owned(new (S.Context)
5582 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5583 Step->Kind == SK_PassByIndirectCopyRestore));
5584 break;
5585
5586 case SK_ProduceObjCObject:
5587 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005588 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005589 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005590 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005591
5592 case SK_StdInitializerList: {
5593 QualType Dest = Step->Type;
5594 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005595 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005596 (void)Success;
5597 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005598
5599 // If the element type has a destructor, check it.
5600 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5601 if (!RD->hasIrrelevantDestructor()) {
5602 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5603 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5604 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5605 S.PDiag(diag::err_access_dtor_temp) << E);
5606 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5607 }
5608 }
5609 }
5610
Sebastian Redl2b916b82012-01-17 22:49:42 +00005611 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005612 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5613 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005614 unsigned NumInits = ILE->getNumInits();
5615 SmallVector<Expr*, 16> Converted(NumInits);
5616 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5617 S.Context.getConstantArrayType(E,
5618 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5619 NumInits),
5620 ArrayType::Normal, 0));
5621 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5622 0, HiddenArray);
5623 for (unsigned i = 0; i < NumInits; ++i) {
5624 Element.setElementIndex(i);
5625 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005626 ExprResult Res = S.PerformCopyInitialization(
5627 Element, Init.get()->getExprLoc(), Init,
5628 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005629 assert(!Res.isInvalid() && "Result changed since try phase.");
5630 Converted[i] = Res.take();
5631 }
5632 InitListExpr *Semantic = new (S.Context)
5633 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005634 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005635 Semantic->setSyntacticForm(ILE);
5636 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005637 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005638 CurInit = S.Owned(Semantic);
5639 break;
5640 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005641 case SK_OCLSamplerInit: {
5642 assert(Step->Type->isSamplerT() &&
5643 "Sampler initialization on non sampler type.");
5644
5645 QualType SourceType = CurInit.get()->getType();
5646 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5647
5648 if (EntityKind == InitializedEntity::EK_Parameter) {
5649 if (!SourceType->isSamplerT())
5650 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5651 << SourceType;
5652 } else if (EntityKind != InitializedEntity::EK_Variable) {
5653 llvm_unreachable("Invalid EntityKind!");
5654 }
5655
5656 break;
5657 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005658 case SK_OCLZeroEvent: {
5659 assert(Step->Type->isEventT() &&
5660 "Event initialization on non event type.");
5661
5662 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5663 CK_ZeroToOCLEvent,
5664 CurInit.get()->getValueKind());
5665 break;
5666 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005667 }
5668 }
John McCall15d7d122010-11-11 03:21:53 +00005669
5670 // Diagnose non-fatal problems with the completed initialization.
5671 if (Entity.getKind() == InitializedEntity::EK_Member &&
5672 cast<FieldDecl>(Entity.getDecl())->isBitField())
5673 S.CheckBitFieldInitialization(Kind.getLocation(),
5674 cast<FieldDecl>(Entity.getDecl()),
5675 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005676
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005677 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005678}
5679
Richard Smithd5bc8672012-12-08 02:01:17 +00005680/// Somewhere within T there is an uninitialized reference subobject.
5681/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005682static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5683 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005684 if (T->isReferenceType()) {
5685 S.Diag(Loc, diag::err_reference_without_init)
5686 << T.getNonReferenceType();
5687 return true;
5688 }
5689
5690 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5691 if (!RD || !RD->hasUninitializedReferenceMember())
5692 return false;
5693
5694 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5695 FE = RD->field_end(); FI != FE; ++FI) {
5696 if (FI->isUnnamedBitfield())
5697 continue;
5698
5699 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5700 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5701 return true;
5702 }
5703 }
5704
5705 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5706 BE = RD->bases_end();
5707 BI != BE; ++BI) {
5708 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5709 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5710 return true;
5711 }
5712 }
5713
5714 return false;
5715}
5716
5717
Douglas Gregor20093b42009-12-09 23:02:17 +00005718//===----------------------------------------------------------------------===//
5719// Diagnose initialization failures
5720//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005721
5722/// Emit notes associated with an initialization that failed due to a
5723/// "simple" conversion failure.
5724static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5725 Expr *op) {
5726 QualType destType = entity.getType();
5727 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5728 op->getType()->isObjCObjectPointerType()) {
5729
5730 // Emit a possible note about the conversion failing because the
5731 // operand is a message send with a related result type.
5732 S.EmitRelatedResultTypeNote(op);
5733
5734 // Emit a possible note about a return failing because we're
5735 // expecting a related result type.
5736 if (entity.getKind() == InitializedEntity::EK_Result)
5737 S.EmitRelatedResultTypeNoteForReturn(destType);
5738 }
5739}
5740
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005741bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005742 const InitializedEntity &Entity,
5743 const InitializationKind &Kind,
5744 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005745 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005746 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005747
Douglas Gregord6542d82009-12-22 15:35:07 +00005748 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005749 switch (Failure) {
5750 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005751 // FIXME: Customize for the initialized entity?
Richard Smithd5bc8672012-12-08 02:01:17 +00005752 if (NumArgs == 0) {
5753 // Dig out the reference subobject which is uninitialized and diagnose it.
5754 // If this is value-initialization, this could be nested some way within
5755 // the target type.
5756 assert(Kind.getKind() == InitializationKind::IK_Value ||
5757 DestType->isReferenceType());
5758 bool Diagnosed =
5759 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5760 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5761 (void)Diagnosed;
5762 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005763 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5764 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005765 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766
Douglas Gregor20093b42009-12-09 23:02:17 +00005767 case FK_ArrayNeedsInitList:
5768 case FK_ArrayNeedsInitListOrStringLiteral:
5769 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5770 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5771 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005772
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005773 case FK_ArrayTypeMismatch:
5774 case FK_NonConstantArrayInit:
5775 S.Diag(Kind.getLocation(),
5776 (Failure == FK_ArrayTypeMismatch
5777 ? diag::err_array_init_different_type
5778 : diag::err_array_init_non_constant_array))
5779 << DestType.getNonReferenceType()
5780 << Args[0]->getType()
5781 << Args[0]->getSourceRange();
5782 break;
5783
John McCall73076432012-01-05 00:13:19 +00005784 case FK_VariableLengthArrayHasInitializer:
5785 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5786 << Args[0]->getSourceRange();
5787 break;
5788
John McCall6bb80172010-03-30 21:47:33 +00005789 case FK_AddressOfOverloadFailed: {
5790 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005791 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005792 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005793 true,
5794 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005795 break;
John McCall6bb80172010-03-30 21:47:33 +00005796 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005797
Douglas Gregor20093b42009-12-09 23:02:17 +00005798 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005799 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005800 switch (FailedOverloadResult) {
5801 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005802 if (Failure == FK_UserConversionOverloadFailed)
5803 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5804 << Args[0]->getType() << DestType
5805 << Args[0]->getSourceRange();
5806 else
5807 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5808 << DestType << Args[0]->getType()
5809 << Args[0]->getSourceRange();
5810
Ahmed Charles13a140c2012-02-25 11:00:22 +00005811 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5812 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005813 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005814
Douglas Gregor20093b42009-12-09 23:02:17 +00005815 case OR_No_Viable_Function:
5816 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5817 << Args[0]->getType() << DestType.getNonReferenceType()
5818 << Args[0]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005819 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5820 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005821 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005822
Douglas Gregor20093b42009-12-09 23:02:17 +00005823 case OR_Deleted: {
5824 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5825 << Args[0]->getType() << DestType.getNonReferenceType()
5826 << Args[0]->getSourceRange();
5827 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005828 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005829 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5830 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005831 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005832 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005833 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005834 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005835 }
5836 break;
5837 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005838
Douglas Gregor20093b42009-12-09 23:02:17 +00005839 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005840 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005841 }
5842 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843
Douglas Gregor20093b42009-12-09 23:02:17 +00005844 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005845 if (isa<InitListExpr>(Args[0])) {
5846 S.Diag(Kind.getLocation(),
5847 diag::err_lvalue_reference_bind_to_initlist)
5848 << DestType.getNonReferenceType().isVolatileQualified()
5849 << DestType.getNonReferenceType()
5850 << Args[0]->getSourceRange();
5851 break;
5852 }
5853 // Intentional fallthrough
5854
Douglas Gregor20093b42009-12-09 23:02:17 +00005855 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005856 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005857 Failure == FK_NonConstLValueReferenceBindingToTemporary
5858 ? diag::err_lvalue_reference_bind_to_temporary
5859 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005860 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005861 << DestType.getNonReferenceType()
5862 << Args[0]->getType()
5863 << Args[0]->getSourceRange();
5864 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005865
Douglas Gregor20093b42009-12-09 23:02:17 +00005866 case FK_RValueReferenceBindingToLValue:
5867 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005868 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005869 << Args[0]->getSourceRange();
5870 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005871
Douglas Gregor20093b42009-12-09 23:02:17 +00005872 case FK_ReferenceInitDropsQualifiers:
5873 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5874 << DestType.getNonReferenceType()
5875 << Args[0]->getType()
5876 << Args[0]->getSourceRange();
5877 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005878
Douglas Gregor20093b42009-12-09 23:02:17 +00005879 case FK_ReferenceInitFailed:
5880 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5881 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005882 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005883 << Args[0]->getType()
5884 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00005885 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005886 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005888 case FK_ConversionFailed: {
5889 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005890 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005891 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005892 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005893 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005894 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005895 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005896 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5897 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00005898 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005899 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005900 }
John Wiegley429bb272011-04-08 18:41:53 +00005901
5902 case FK_ConversionFromPropertyFailed:
5903 // No-op. This error has already been reported.
5904 break;
5905
Douglas Gregord87b61f2009-12-10 17:56:55 +00005906 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005907 SourceRange R;
5908
5909 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005910 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005911 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005912 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005913 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005914
Douglas Gregor19311e72010-09-08 21:40:08 +00005915 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5916 if (Kind.isCStyleOrFunctionalCast())
5917 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5918 << R;
5919 else
5920 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5921 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005922 break;
5923 }
5924
5925 case FK_ReferenceBindingToInitList:
5926 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5927 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5928 break;
5929
5930 case FK_InitListBadDestinationType:
5931 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5932 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5933 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005934
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005935 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005936 case FK_ConstructorOverloadFailed: {
5937 SourceRange ArgsRange;
5938 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005939 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005940 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005941
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005942 if (Failure == FK_ListConstructorOverloadFailed) {
5943 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5944 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5945 Args = InitList->getInits();
5946 NumArgs = InitList->getNumInits();
5947 }
5948
Douglas Gregor51c56d62009-12-14 20:49:26 +00005949 // FIXME: Using "DestType" for the entity we're printing is probably
5950 // bad.
5951 switch (FailedOverloadResult) {
5952 case OR_Ambiguous:
5953 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5954 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005955 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005956 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005957 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005958
Douglas Gregor51c56d62009-12-14 20:49:26 +00005959 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005960 if (Kind.getKind() == InitializationKind::IK_Default &&
5961 (Entity.getKind() == InitializedEntity::EK_Base ||
5962 Entity.getKind() == InitializedEntity::EK_Member) &&
5963 isa<CXXConstructorDecl>(S.CurContext)) {
5964 // This is implicit default initialization of a member or
5965 // base within a constructor. If no viable function was
5966 // found, notify the user that she needs to explicitly
5967 // initialize this base/member.
5968 CXXConstructorDecl *Constructor
5969 = cast<CXXConstructorDecl>(S.CurContext);
5970 if (Entity.getKind() == InitializedEntity::EK_Base) {
5971 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005972 << (Constructor->getInheritedConstructor() ? 2 :
5973 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005974 << S.Context.getTypeDeclType(Constructor->getParent())
5975 << /*base=*/0
5976 << Entity.getType();
5977
5978 RecordDecl *BaseDecl
5979 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5980 ->getDecl();
5981 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5982 << S.Context.getTagDeclType(BaseDecl);
5983 } else {
5984 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005985 << (Constructor->getInheritedConstructor() ? 2 :
5986 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005987 << S.Context.getTypeDeclType(Constructor->getParent())
5988 << /*member=*/1
5989 << Entity.getName();
5990 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5991
5992 if (const RecordType *Record
5993 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005994 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005995 diag::note_previous_decl)
5996 << S.Context.getTagDeclType(Record->getDecl());
5997 }
5998 break;
5999 }
6000
Douglas Gregor51c56d62009-12-14 20:49:26 +00006001 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6002 << DestType << ArgsRange;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006003 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
6004 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00006005 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006006
Douglas Gregor51c56d62009-12-14 20:49:26 +00006007 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006008 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006009 OverloadingResult Ovl
6010 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006011 if (Ovl != OR_Deleted) {
6012 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6013 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006014 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006015 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006016 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006017
6018 // If this is a defaulted or implicitly-declared function, then
6019 // it was implicitly deleted. Make it clear that the deletion was
6020 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006021 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006022 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006023 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006024 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006025 else
6026 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6027 << true << DestType << ArgsRange;
6028
6029 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006030 break;
6031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006032
Douglas Gregor51c56d62009-12-14 20:49:26 +00006033 case OR_Success:
6034 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006035 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006036 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006037 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006038
Douglas Gregor99a2e602009-12-16 01:38:02 +00006039 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006040 if (Entity.getKind() == InitializedEntity::EK_Member &&
6041 isa<CXXConstructorDecl>(S.CurContext)) {
6042 // This is implicit default-initialization of a const member in
6043 // a constructor. Complain that it needs to be explicitly
6044 // initialized.
6045 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6046 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006047 << (Constructor->getInheritedConstructor() ? 2 :
6048 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006049 << S.Context.getTypeDeclType(Constructor->getParent())
6050 << /*const=*/1
6051 << Entity.getName();
6052 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6053 << Entity.getName();
6054 } else {
6055 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6056 << DestType << (bool)DestType->getAs<RecordType>();
6057 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006058 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006059
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006060 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006061 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006062 diag::err_init_incomplete_type);
6063 break;
6064
Sebastian Redl14b0c192011-09-24 17:48:00 +00006065 case FK_ListInitializationFailed: {
6066 // Run the init list checker again to emit diagnostics.
6067 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6068 QualType DestType = Entity.getType();
6069 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006070 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006071 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006072 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006073 assert(DiagnoseInitList.HadError() &&
6074 "Inconsistent init list check result.");
6075 break;
6076 }
John McCall5acb0c92011-10-17 18:40:02 +00006077
6078 case FK_PlaceholderType: {
6079 // FIXME: Already diagnosed!
6080 break;
6081 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006082
6083 case FK_InitListElementCopyFailure: {
6084 // Try to perform all copies again.
6085 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6086 unsigned NumInits = InitList->getNumInits();
6087 QualType DestType = Entity.getType();
6088 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006089 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006090 (void)Success;
6091 assert(Success && "Where did the std::initializer_list go?");
6092 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6093 S.Context.getConstantArrayType(E,
6094 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6095 NumInits),
6096 ArrayType::Normal, 0));
6097 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6098 0, HiddenArray);
6099 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6100 // where the init list type is wrong, e.g.
6101 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6102 // FIXME: Emit a note if we hit the limit?
6103 int ErrorCount = 0;
6104 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6105 Element.setElementIndex(i);
6106 ExprResult Init = S.Owned(InitList->getInit(i));
6107 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6108 .isInvalid())
6109 ++ErrorCount;
6110 }
6111 break;
6112 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006113
6114 case FK_ExplicitConstructor: {
6115 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6116 << Args[0]->getSourceRange();
6117 OverloadCandidateSet::iterator Best;
6118 OverloadingResult Ovl
6119 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006120 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006121 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6122 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6123 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6124 break;
6125 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006126 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006127
Douglas Gregora41a8c52010-04-22 00:20:18 +00006128 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006129 return true;
6130}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006131
Chris Lattner5f9e2722011-07-23 10:55:15 +00006132void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006133 switch (SequenceKind) {
6134 case FailedSequence: {
6135 OS << "Failed sequence: ";
6136 switch (Failure) {
6137 case FK_TooManyInitsForReference:
6138 OS << "too many initializers for reference";
6139 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006140
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006141 case FK_ArrayNeedsInitList:
6142 OS << "array requires initializer list";
6143 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006144
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006145 case FK_ArrayNeedsInitListOrStringLiteral:
6146 OS << "array requires initializer list or string literal";
6147 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006148
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006149 case FK_ArrayTypeMismatch:
6150 OS << "array type mismatch";
6151 break;
6152
6153 case FK_NonConstantArrayInit:
6154 OS << "non-constant array initializer";
6155 break;
6156
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006157 case FK_AddressOfOverloadFailed:
6158 OS << "address of overloaded function failed";
6159 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006160
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006161 case FK_ReferenceInitOverloadFailed:
6162 OS << "overload resolution for reference initialization failed";
6163 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006164
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006165 case FK_NonConstLValueReferenceBindingToTemporary:
6166 OS << "non-const lvalue reference bound to temporary";
6167 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006168
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006169 case FK_NonConstLValueReferenceBindingToUnrelated:
6170 OS << "non-const lvalue reference bound to unrelated type";
6171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006172
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006173 case FK_RValueReferenceBindingToLValue:
6174 OS << "rvalue reference bound to an lvalue";
6175 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006176
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006177 case FK_ReferenceInitDropsQualifiers:
6178 OS << "reference initialization drops qualifiers";
6179 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006180
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006181 case FK_ReferenceInitFailed:
6182 OS << "reference initialization failed";
6183 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006184
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006185 case FK_ConversionFailed:
6186 OS << "conversion failed";
6187 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006188
John Wiegley429bb272011-04-08 18:41:53 +00006189 case FK_ConversionFromPropertyFailed:
6190 OS << "conversion from property failed";
6191 break;
6192
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006193 case FK_TooManyInitsForScalar:
6194 OS << "too many initializers for scalar";
6195 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006196
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006197 case FK_ReferenceBindingToInitList:
6198 OS << "referencing binding to initializer list";
6199 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006200
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006201 case FK_InitListBadDestinationType:
6202 OS << "initializer list for non-aggregate, non-scalar type";
6203 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006204
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006205 case FK_UserConversionOverloadFailed:
6206 OS << "overloading failed for user-defined conversion";
6207 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006208
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006209 case FK_ConstructorOverloadFailed:
6210 OS << "constructor overloading failed";
6211 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006212
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006213 case FK_DefaultInitOfConst:
6214 OS << "default initialization of a const variable";
6215 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006216
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006217 case FK_Incomplete:
6218 OS << "initialization of incomplete type";
6219 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006220
6221 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006222 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006223 break;
6224
John McCall73076432012-01-05 00:13:19 +00006225 case FK_VariableLengthArrayHasInitializer:
6226 OS << "variable length array has an initializer";
6227 break;
6228
John McCall5acb0c92011-10-17 18:40:02 +00006229 case FK_PlaceholderType:
6230 OS << "initializer expression isn't contextually valid";
6231 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006232
6233 case FK_ListConstructorOverloadFailed:
6234 OS << "list constructor overloading failed";
6235 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006236
6237 case FK_InitListElementCopyFailure:
6238 OS << "copy construction of initializer list element failed";
6239 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006240
6241 case FK_ExplicitConstructor:
6242 OS << "list copy initialization chose explicit constructor";
6243 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006244 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006245 OS << '\n';
6246 return;
6247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006248
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006249 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006250 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006251 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006252
Sebastian Redl7491c492011-06-05 13:59:11 +00006253 case NormalSequence:
6254 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006255 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006257
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006258 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6259 if (S != step_begin()) {
6260 OS << " -> ";
6261 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006262
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006263 switch (S->Kind) {
6264 case SK_ResolveAddressOfOverloadedFunction:
6265 OS << "resolve address of overloaded function";
6266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006267
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006268 case SK_CastDerivedToBaseRValue:
6269 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6270 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006271
Sebastian Redl906082e2010-07-20 04:20:21 +00006272 case SK_CastDerivedToBaseXValue:
6273 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6274 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006275
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006276 case SK_CastDerivedToBaseLValue:
6277 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6278 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006279
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006280 case SK_BindReference:
6281 OS << "bind reference to lvalue";
6282 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006283
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006284 case SK_BindReferenceToTemporary:
6285 OS << "bind reference to a temporary";
6286 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006287
Douglas Gregor523d46a2010-04-18 07:40:54 +00006288 case SK_ExtraneousCopyToTemporary:
6289 OS << "extraneous C++03 copy to temporary";
6290 break;
6291
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006292 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006293 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006294 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006295
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006296 case SK_QualificationConversionRValue:
6297 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006298 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006299
Sebastian Redl906082e2010-07-20 04:20:21 +00006300 case SK_QualificationConversionXValue:
6301 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006302 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006303
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006304 case SK_QualificationConversionLValue:
6305 OS << "qualification conversion (lvalue)";
6306 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006307
Jordan Rose1fd1e282013-04-11 00:58:58 +00006308 case SK_LValueToRValue:
6309 OS << "load (lvalue to rvalue)";
6310 break;
6311
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006312 case SK_ConversionSequence:
6313 OS << "implicit conversion sequence (";
6314 S->ICS->DebugPrint(); // FIXME: use OS
6315 OS << ")";
6316 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006317
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006318 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006319 OS << "list aggregate initialization";
6320 break;
6321
6322 case SK_ListConstructorCall:
6323 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006324 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006325
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006326 case SK_UnwrapInitList:
6327 OS << "unwrap reference initializer list";
6328 break;
6329
6330 case SK_RewrapInitList:
6331 OS << "rewrap reference initializer list";
6332 break;
6333
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006334 case SK_ConstructorInitialization:
6335 OS << "constructor initialization";
6336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006337
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006338 case SK_ZeroInitialization:
6339 OS << "zero initialization";
6340 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006341
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006342 case SK_CAssignment:
6343 OS << "C assignment";
6344 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006346 case SK_StringInit:
6347 OS << "string initialization";
6348 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006349
6350 case SK_ObjCObjectConversion:
6351 OS << "Objective-C object conversion";
6352 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006353
6354 case SK_ArrayInit:
6355 OS << "array initialization";
6356 break;
John McCallf85e1932011-06-15 23:02:42 +00006357
Richard Smith0f163e92012-02-15 22:38:09 +00006358 case SK_ParenthesizedArrayInit:
6359 OS << "parenthesized array initialization";
6360 break;
6361
John McCallf85e1932011-06-15 23:02:42 +00006362 case SK_PassByIndirectCopyRestore:
6363 OS << "pass by indirect copy and restore";
6364 break;
6365
6366 case SK_PassByIndirectRestore:
6367 OS << "pass by indirect restore";
6368 break;
6369
6370 case SK_ProduceObjCObject:
6371 OS << "Objective-C object retension";
6372 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006373
6374 case SK_StdInitializerList:
6375 OS << "std::initializer_list from initializer list";
6376 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006377
Guy Benyei21f18c42013-02-07 10:55:47 +00006378 case SK_OCLSamplerInit:
6379 OS << "OpenCL sampler_t from integer constant";
6380 break;
6381
Guy Benyeie6b9d802013-01-20 12:31:11 +00006382 case SK_OCLZeroEvent:
6383 OS << "OpenCL event_t from zero";
6384 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006385 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006386
6387 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006388 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006389
6390 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006391}
6392
6393void InitializationSequence::dump() const {
6394 dump(llvm::errs());
6395}
6396
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006397static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6398 QualType EntityType,
6399 const Expr *PreInit,
6400 const Expr *PostInit) {
6401 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6402 return;
6403
6404 // A narrowing conversion can only appear as the final implicit conversion in
6405 // an initialization sequence.
6406 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6407 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6408 return;
6409
6410 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6411 const StandardConversionSequence *SCS = 0;
6412 switch (ICS.getKind()) {
6413 case ImplicitConversionSequence::StandardConversion:
6414 SCS = &ICS.Standard;
6415 break;
6416 case ImplicitConversionSequence::UserDefinedConversion:
6417 SCS = &ICS.UserDefined.After;
6418 break;
6419 case ImplicitConversionSequence::AmbiguousConversion:
6420 case ImplicitConversionSequence::EllipsisConversion:
6421 case ImplicitConversionSequence::BadConversion:
6422 return;
6423 }
6424
6425 // Determine the type prior to the narrowing conversion. If a conversion
6426 // operator was used, this may be different from both the type of the entity
6427 // and of the pre-initialization expression.
6428 QualType PreNarrowingType = PreInit->getType();
6429 if (Seq.step_begin() + 1 != Seq.step_end())
6430 PreNarrowingType = Seq.step_end()[-2].Type;
6431
6432 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6433 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006434 QualType ConstantType;
6435 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6436 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006437 case NK_Not_Narrowing:
6438 // No narrowing occurred.
6439 return;
6440
6441 case NK_Type_Narrowing:
6442 // This was a floating-to-integer conversion, which is always considered a
6443 // narrowing conversion even if the value is a constant and can be
6444 // represented exactly as an integer.
6445 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006446 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006447 diag::warn_init_list_type_narrowing
6448 : S.isSFINAEContext()?
6449 diag::err_init_list_type_narrowing_sfinae
6450 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006451 << PostInit->getSourceRange()
6452 << PreNarrowingType.getLocalUnqualifiedType()
6453 << EntityType.getLocalUnqualifiedType();
6454 break;
6455
6456 case NK_Constant_Narrowing:
6457 // A constant value was narrowed.
6458 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006459 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006460 diag::warn_init_list_constant_narrowing
6461 : S.isSFINAEContext()?
6462 diag::err_init_list_constant_narrowing_sfinae
6463 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006464 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006465 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006466 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006467 break;
6468
6469 case NK_Variable_Narrowing:
6470 // A variable's value may have been narrowed.
6471 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006472 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006473 diag::warn_init_list_variable_narrowing
6474 : S.isSFINAEContext()?
6475 diag::err_init_list_variable_narrowing_sfinae
6476 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006477 << PostInit->getSourceRange()
6478 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006479 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006480 break;
6481 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006482
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006483 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006484 llvm::raw_svector_ostream OS(StaticCast);
6485 OS << "static_cast<";
6486 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6487 // It's important to use the typedef's name if there is one so that the
6488 // fixit doesn't break code using types like int64_t.
6489 //
6490 // FIXME: This will break if the typedef requires qualification. But
6491 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006492 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006493 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006494 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006495 else {
6496 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6497 // with a broken cast.
6498 return;
6499 }
6500 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006501 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6502 << PostInit->getSourceRange()
6503 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006504 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006505 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006506}
6507
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006508//===----------------------------------------------------------------------===//
6509// Initialization helper functions
6510//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006511bool
6512Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6513 ExprResult Init) {
6514 if (Init.isInvalid())
6515 return false;
6516
6517 Expr *InitE = Init.get();
6518 assert(InitE && "No initialization expression");
6519
Douglas Gregor3c394c52012-07-31 22:15:04 +00006520 InitializationKind Kind
6521 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Sean Hunt2be7e902011-05-12 22:46:29 +00006522 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006523 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006524}
6525
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006526ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006527Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6528 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006529 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006530 bool TopLevelOfInitList,
6531 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006532 if (Init.isInvalid())
6533 return ExprError();
6534
John McCall15d7d122010-11-11 03:21:53 +00006535 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006536 assert(InitE && "No initialization expression?");
6537
6538 if (EqualLoc.isInvalid())
6539 EqualLoc = InitE->getLocStart();
6540
6541 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006542 EqualLoc,
6543 AllowExplicit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006544 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6545 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006546
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006547 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6548
6549 if (!Result.isInvalid() && TopLevelOfInitList)
6550 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6551 InitE, Result.get());
6552
6553 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006554}