blob: 5fa8486a7f1e15a06add85befe3faac3958060fa [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//
Rafael Espindola12ce0a02011-07-14 22:58:04 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000013//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.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.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
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.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000109 if (S.getLangOptions().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())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike 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;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000198 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000200 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000203 void CheckReferenceType(const InitializedEntity &Entity,
204 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000205 unsigned &Index,
206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000208 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000209 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000212 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000213 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000214 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000215 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000217 unsigned &StructuredIndex,
218 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000220 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000226 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000227 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 RecordDecl::field_iterator *NextField,
230 llvm::APSInt *NextElementIndex,
231 unsigned &Index,
232 InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000234 bool FinishSubobjectInit,
235 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
237 QualType CurrentObjectType,
238 InitListExpr *StructuredList,
239 unsigned StructuredIndex,
240 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000241 void UpdateStructuredListElement(InitListExpr *StructuredList,
242 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000243 Expr *expr);
244 int numArrayElements(QualType DeclType);
245 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000246
Douglas Gregord6d37de2009-12-22 00:05:34 +0000247 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
248 const InitializedEntity &ParentEntity,
249 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000250 void FillInValueInitializations(const InitializedEntity &Entity,
251 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000252 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
253 Expr *InitExpr, FieldDecl *Field,
254 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000255public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 InitListChecker(Sema &S, const InitializedEntity &Entity,
257 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000258 bool HadError() { return hadError; }
259
260 // @brief Retrieves the fully-structured initializer list used for
261 // semantic analysis and code generation.
262 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
263};
Chris Lattner8b419b92009-02-24 22:48:58 +0000264} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000265
Douglas Gregord6d37de2009-12-22 00:05:34 +0000266void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
267 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000268 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000269 bool &RequiresSecondPass) {
270 SourceLocation Loc = ILE->getSourceRange().getBegin();
271 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000273 = InitializedEntity::InitializeMember(Field, &ParentEntity);
274 if (Init >= NumInits || !ILE->getInit(Init)) {
275 // FIXME: We probably don't need to handle references
276 // specially here, since value-initialization of references is
277 // handled in InitializationSequence.
278 if (Field->getType()->isReferenceType()) {
279 // C++ [dcl.init.aggr]p9:
280 // If an incomplete or empty initializer-list leaves a
281 // member of reference type uninitialized, the program is
282 // ill-formed.
283 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
284 << Field->getType()
285 << ILE->getSyntacticForm()->getSourceRange();
286 SemaRef.Diag(Field->getLocation(),
287 diag::note_uninit_reference_member);
288 hadError = true;
289 return;
290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000291
Douglas Gregord6d37de2009-12-22 00:05:34 +0000292 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
293 true);
294 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
295 if (!InitSeq) {
296 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
297 hadError = true;
298 return;
299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000300
John McCall60d7b3a2010-08-24 06:29:42 +0000301 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000302 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000303 if (MemberInit.isInvalid()) {
304 hadError = true;
305 return;
306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000307
Douglas Gregord6d37de2009-12-22 00:05:34 +0000308 if (hadError) {
309 // Do nothing
310 } else if (Init < NumInits) {
311 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000312 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 // Value-initialization requires a constructor call, so
314 // extend the initializer list to include the constructor
315 // call and make a note that we'll need to take another pass
316 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000317 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 RequiresSecondPass = true;
319 }
320 } else if (InitListExpr *InnerILE
321 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000322 FillInValueInitializations(MemberEntity, InnerILE,
323 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324}
325
Douglas Gregor4c678342009-01-28 21:54:33 +0000326/// Recursively replaces NULL values within the given initializer list
327/// with expressions that perform value-initialization of the
328/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000330InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
331 InitListExpr *ILE,
332 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000333 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000334 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000335 SourceLocation Loc = ILE->getSourceRange().getBegin();
336 if (ILE->getSyntacticForm())
337 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek6217b802009-07-29 21:53:49 +0000339 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (RType->getDecl()->isUnion() &&
341 ILE->getInitializedFieldInUnion())
342 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
343 Entity, ILE, RequiresSecondPass);
344 else {
345 unsigned Init = 0;
346 for (RecordDecl::field_iterator
347 Field = RType->getDecl()->field_begin(),
348 FieldEnd = RType->getDecl()->field_end();
349 Field != FieldEnd; ++Field) {
350 if (Field->isUnnamedBitfield())
351 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000352
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000354 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355
356 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000359
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000361
Douglas Gregord6d37de2009-12-22 00:05:34 +0000362 // Only look at the first initialization of a union.
363 if (RType->getDecl()->isUnion())
364 break;
365 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000366 }
367
368 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370
371 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000373 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000374 unsigned NumInits = ILE->getNumInits();
375 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000376 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000377 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
379 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000382 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000383 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000384 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000386 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000387 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000388 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregor87fd7032009-02-02 17:43:21 +0000391 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000392 if (hadError)
393 return;
394
Anders Carlssond3d824d2010-01-23 04:34:47 +0000395 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
396 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 ElementEntity.setElementIndex(Init);
398
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000400 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
401 true);
402 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
403 if (!InitSeq) {
404 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 hadError = true;
406 return;
407 }
408
John McCall60d7b3a2010-08-24 06:29:42 +0000409 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000410 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000411 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000412 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000413 return;
414 }
415
416 if (hadError) {
417 // Do nothing
418 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000419 // For arrays, just set the expression used for value-initialization
420 // of the "holes" in the array.
421 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
422 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
423 else
424 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000425 } else {
426 // For arrays, just set the expression used for value-initialization
427 // of the rest of elements and exit.
428 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
429 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
430 return;
431 }
432
Sebastian Redl7491c492011-06-05 13:59:11 +0000433 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000434 // Value-initialization requires a constructor call, so
435 // extend the initializer list to include the constructor
436 // call and make a note that we'll need to take another pass
437 // through the initializer list.
438 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
439 RequiresSecondPass = true;
440 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000442 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000443 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
444 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 }
446}
447
Chris Lattner68355a52009-01-29 05:10:57 +0000448
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000449InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
450 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000451 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000452 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000453
Eli Friedmanb85f7072008-05-19 19:16:24 +0000454 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000455 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000456 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000457 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000459 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000460 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000461
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000462 if (!hadError) {
463 bool RequiresSecondPass = false;
464 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000465 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000467 RequiresSecondPass);
468 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000469}
470
471int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000472 // FIXME: use a proper constant
473 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000474 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000475 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
477 }
478 return maxElements;
479}
480
481int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000482 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000484 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000485 Field = structDecl->field_begin(),
486 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 Field != FieldEnd; ++Field) {
488 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
489 ++InitializableMembers;
490 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000491 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000492 return std::min(InitializableMembers, 1);
493 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000494}
495
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000496void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000497 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000498 QualType T, unsigned &Index,
499 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000500 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000501 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Steve Naroff0cca7492008-05-01 22:18:59 +0000503 if (T->isArrayType())
504 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000505 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000507 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000508 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000509 else
510 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000511
Eli Friedman402256f2008-05-25 13:49:22 +0000512 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000513 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000514 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000515 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000516 hadError = true;
517 return;
518 }
519
Douglas Gregor4c678342009-01-28 21:54:33 +0000520 // Build a structured initializer list corresponding to this subobject.
521 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000522 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
523 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000524 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
525 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000527
Douglas Gregor4c678342009-01-28 21:54:33 +0000528 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000529 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000531 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000533 StructuredSubobjectInitIndex);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000535 StructuredSubobjectInitList->setType(T);
536
Douglas Gregored8a93d2009-03-01 17:12:46 +0000537 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000538 // range corresponds with the end of the last initializer it used.
539 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
542 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000545 // Warn about missing braces.
546 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000547 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
548 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000549 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000551 "{")
552 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000554 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000555 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000556}
557
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000558void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000559 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 SyntacticToSemantic[IList] = StructuredList;
566 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000569 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
570 IList->setType(ExprTy);
571 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000572 if (hadError)
573 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000574
Eli Friedman638e1442008-05-25 13:22:35 +0000575 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000576 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000577 if (StructuredIndex == 1 &&
578 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000579 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000580 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000581 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000582 hadError = true;
583 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000584 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000586 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000587 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000588 // Don't complain for incomplete types, since we'll get an error
589 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000590 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000591 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000592 CurrentObjectType->isArrayType()? 0 :
593 CurrentObjectType->isVectorType()? 1 :
594 CurrentObjectType->isScalarType()? 2 :
595 CurrentObjectType->isUnionType()? 3 :
596 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000597
598 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (SemaRef.getLangOptions().CPlusPlus) {
600 DK = diag::err_excess_initializers;
601 hadError = true;
602 }
Nate Begeman08634522009-07-07 21:53:06 +0000603 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000607
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000609 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000610 }
611 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000612
Eli Friedman759f2522009-05-16 11:45:48 +0000613 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000614 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000615 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000616 << FixItHint::CreateRemoval(IList->getLocStart())
617 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000618}
619
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000620void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000621 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000623 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000626 unsigned &StructuredIndex,
627 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000628 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 CheckScalarType(Entity, IList, DeclType, Index,
630 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000631 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000633 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000634 } else if (DeclType->isAggregateType()) {
635 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000636 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000637 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 StructuredList, StructuredIndex,
640 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000641 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000642 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000643 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000646 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000650 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
651 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000655 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 } else if (DeclType->isRecordType()) {
657 // C++ [dcl.init]p14:
658 // [...] If the class is an aggregate (8.5.1), and the initializer
659 // is a brace-enclosed list, see 8.5.1.
660 //
661 // Note: 8.5.1 is handled below; here, we diagnose the case where
662 // we have an initializer list and a destination type that is not
663 // an aggregate.
664 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 << DeclType << IList->getSourceRange();
667 hadError = true;
668 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000669 CheckReferenceType(Entity, IList, DeclType, Index,
670 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000671 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000672 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
673 << DeclType;
674 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000675 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000676 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
677 << DeclType;
678 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000679 }
680}
681
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000682void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000683 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 unsigned &Index,
686 InitListExpr *StructuredList,
687 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000688 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000689 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
690 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000692 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000693 = getStructuredSubobjectInit(IList, Index, ElemType,
694 StructuredList, StructuredIndex,
695 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000697 newStructuredList, newStructuredIndex);
698 ++StructuredIndex;
699 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000700 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000701 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000702 return CheckScalarType(Entity, IList, ElemType, Index,
703 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000705 return CheckReferenceType(Entity, IList, ElemType, Index,
706 StructuredList, StructuredIndex);
707 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000708
John McCallfef8b342011-02-21 07:57:55 +0000709 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
710 // arrayType can be incomplete if we're initializing a flexible
711 // array member. There's nothing we can do with the completed
712 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
John McCallfef8b342011-02-21 07:57:55 +0000714 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
715 CheckStringInit(Str, ElemType, arrayType, SemaRef);
716 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000718 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 }
John McCallfef8b342011-02-21 07:57:55 +0000720
721 // Fall through for subaggregate initialization.
722
723 } else if (SemaRef.getLangOptions().CPlusPlus) {
724 // C++ [dcl.init.aggr]p12:
725 // All implicit type conversions (clause 4) are considered when
Rafael Espindola12ce0a02011-07-14 22:58:04 +0000726 // initializing the aggregate member with an ini- tializer from
John McCallfef8b342011-02-21 07:57:55 +0000727 // an initializer-list. If the initializer can initialize a
728 // member, the member is initialized. [...]
729
730 // FIXME: Better EqualLoc?
731 InitializationKind Kind =
732 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
733 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
734
735 if (Seq) {
736 ExprResult Result =
737 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
738 if (Result.isInvalid())
739 hadError = true;
740
741 UpdateStructuredListElement(StructuredList, StructuredIndex,
742 Result.takeAs<Expr>());
743 ++Index;
744 return;
745 }
746
747 // Fall through for subaggregate initialization
748 } else {
749 // C99 6.7.8p13:
750 //
751 // The initializer for a structure or union object that has
752 // automatic storage duration shall be either an initializer
753 // list as described below, or a single expression that has
754 // compatible structure or union type. In the latter case, the
755 // initial value of the object, including unnamed members, is
756 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000757 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000758 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000759 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000760 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000761 if (ExprRes.isInvalid())
762 hadError = true;
763 else {
764 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
765 if (ExprRes.isInvalid())
766 hadError = true;
767 }
768 UpdateStructuredListElement(StructuredList, StructuredIndex,
769 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000770 ++Index;
771 return;
772 }
John Wiegley429bb272011-04-08 18:41:53 +0000773 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000774 // Fall through for subaggregate initialization
775 }
776
777 // C++ [dcl.init.aggr]p12:
778 //
779 // [...] Otherwise, if the member is itself a non-empty
780 // subaggregate, brace elision is assumed and the initializer is
781 // considered for the initialization of the first member of
782 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000783 if (!SemaRef.getLangOptions().OpenCL &&
784 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000785 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
786 StructuredIndex);
787 ++StructuredIndex;
788 } else {
789 // We cannot initialize this element, so let
790 // PerformCopyInitialization produce the appropriate diagnostic.
791 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000792 SemaRef.Owned(expr),
793 /*TopLevelOfInitList=*/true);
John McCallfef8b342011-02-21 07:57:55 +0000794 hadError = true;
795 ++Index;
796 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000798}
799
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000800void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000801 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000802 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000803 InitListExpr *StructuredList,
804 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000805 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000806 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000808 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 ++Index;
810 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 }
John McCallb934c2d2010-11-11 00:46:36 +0000813
814 Expr *expr = IList->getInit(Index);
815 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
816 SemaRef.Diag(SubIList->getLocStart(),
817 diag::warn_many_braces_around_scalar_init)
818 << SubIList->getSourceRange();
819
820 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
821 StructuredIndex);
822 return;
823 } else if (isa<DesignatedInitExpr>(expr)) {
824 SemaRef.Diag(expr->getSourceRange().getBegin(),
825 diag::err_designator_for_scalar_init)
826 << DeclType << expr->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832
833 ExprResult Result =
834 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000835 SemaRef.Owned(expr),
836 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000837
838 Expr *ResultExpr = 0;
839
840 if (Result.isInvalid())
841 hadError = true; // types weren't compatible.
842 else {
843 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000844
John McCallb934c2d2010-11-11 00:46:36 +0000845 if (ResultExpr != expr) {
846 // The type was promoted, update initializer list.
847 IList->setInit(Index, ResultExpr);
848 }
849 }
850 if (hadError)
851 ++StructuredIndex;
852 else
853 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
854 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855}
856
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000857void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
858 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000871 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000872
John McCall60d7b3a2010-08-24 06:29:42 +0000873 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000874 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000877
878 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000880
881 expr = Result.takeAs<Expr>();
882 IList->setInit(Index, expr);
883
Douglas Gregor930d8b52009-01-30 22:09:00 +0000884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000905void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000906 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 unsigned &Index,
908 InitListExpr *StructuredList,
909 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000910 if (Index >= IList->getNumInits())
911 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
John McCall20e047a2010-10-30 00:11:39 +0000913 const VectorType *VT = DeclType->getAs<VectorType>();
914 unsigned maxElements = VT->getNumElements();
915 unsigned numEltsInit = 0;
916 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (!SemaRef.getLangOptions().OpenCL) {
919 // If the initializing element is a vector, try to copy-initialize
920 // instead of breaking it apart (which is doomed to failure anyway).
921 Expr *Init = IList->getInit(Index);
922 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
923 ExprResult Result =
924 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000925 SemaRef.Owned(Init),
926 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +0000927
928 Expr *ResultExpr = 0;
929 if (Result.isInvalid())
930 hadError = true; // types weren't compatible.
931 else {
932 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-10-30 00:11:39 +0000934 if (ResultExpr != Init) {
935 // The type was promoted, update initializer list.
936 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000937 }
938 }
John McCall20e047a2010-10-30 00:11:39 +0000939 if (hadError)
940 ++StructuredIndex;
941 else
942 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
943 ++Index;
944 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCall20e047a2010-10-30 00:11:39 +0000947 InitializedEntity ElementEntity =
948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
John McCall20e047a2010-10-30 00:11:39 +0000950 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
951 // Don't attempt to go past the end of the init list
952 if (Index >= IList->getNumInits())
953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
John McCall20e047a2010-10-30 00:11:39 +0000955 ElementEntity.setElementIndex(Index);
956 CheckSubElementType(ElementEntity, IList, elementType, Index,
957 StructuredList, StructuredIndex);
958 }
959 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000960 }
John McCall20e047a2010-10-30 00:11:39 +0000961
962 InitializedEntity ElementEntity =
963 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000964
John McCall20e047a2010-10-30 00:11:39 +0000965 // OpenCL initializers allows vectors to be constructed from vectors.
966 for (unsigned i = 0; i < maxElements; ++i) {
967 // Don't attempt to go past the end of the init list
968 if (Index >= IList->getNumInits())
969 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000970
John McCall20e047a2010-10-30 00:11:39 +0000971 ElementEntity.setElementIndex(Index);
972
973 QualType IType = IList->getInit(Index)->getType();
974 if (!IType->isVectorType()) {
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
977 ++numEltsInit;
978 } else {
979 QualType VecType;
980 const VectorType *IVT = IType->getAs<VectorType>();
981 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
John McCall20e047a2010-10-30 00:11:39 +0000983 if (IType->isExtVectorType())
984 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
985 else
986 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000987 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000988 CheckSubElementType(ElementEntity, IList, VecType, Index,
989 StructuredList, StructuredIndex);
990 numEltsInit += numIElts;
991 }
992 }
993
994 // OpenCL requires all elements to be initialized.
995 if (numEltsInit != maxElements)
996 if (SemaRef.getLangOptions().OpenCL)
997 SemaRef.Diag(IList->getSourceRange().getBegin(),
998 diag::err_vector_incorrect_num_initializers)
999 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000}
1001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001003 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001006 unsigned &Index,
1007 InitListExpr *StructuredList,
1008 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001009 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1010
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 // Check for the special-case of initializing an array with a string.
1012 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001013 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001014 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001015 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 // We place the string literal directly into the resulting
1017 // initializer list. This is the only place where the structure
1018 // of the structured initializer list doesn't match exactly,
1019 // because doing so would involve allocating one character
1020 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001021 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001022 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001023 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001024 return;
1025 }
1026 }
John McCallce6c9b72011-02-21 07:22:22 +00001027 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001028 // Check for VLAs; in standard C it would be possible to check this
1029 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1030 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001031 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001032 diag::err_variable_object_no_init)
1033 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001034 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001035 ++Index;
1036 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001037 return;
1038 }
1039
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001041 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1042 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001044 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001045 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001046 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001047 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001048 maxElementsKnown = true;
1049 }
1050
John McCallce6c9b72011-02-21 07:22:22 +00001051 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 while (Index < IList->getNumInits()) {
1053 Expr *Init = IList->getInit(Index);
1054 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001055 // If we're not the subobject that matches up with the '{' for
1056 // the designator, we shouldn't be handling the
1057 // designator. Return immediately.
1058 if (!SubobjectIsDesignatorContext)
1059 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001060
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // Handle this designated initializer. elementIndex will be
1062 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001063 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001064 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001065 StructuredList, StructuredIndex, true,
1066 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 hadError = true;
1068 continue;
1069 }
1070
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001071 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001072 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001073 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001074 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001075 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001076
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001077 // If the array is of incomplete type, keep track of the number of
1078 // elements in the initializer.
1079 if (!maxElementsKnown && elementIndex > maxElements)
1080 maxElements = elementIndex;
1081
Douglas Gregor05c13a32009-01-22 00:58:24 +00001082 continue;
1083 }
1084
1085 // If we know the maximum number of elements, and we've already
1086 // hit it, stop consuming elements in the initializer list.
1087 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001090 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001092 Entity);
1093 // Check this element.
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 ++elementIndex;
1097
1098 // If the array is of incomplete type, keep track of the number of
1099 // elements in the initializer.
1100 if (!maxElementsKnown && elementIndex > maxElements)
1101 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001103 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001105 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001106 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001108 // Sizing an array implicitly to zero is not allowed by ISO C,
1109 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001110 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001111 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113
Mike Stump1eb44332009-09-09 15:08:12 +00001114 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001115 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001116 }
1117}
1118
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001119bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1120 Expr *InitExpr,
1121 FieldDecl *Field,
1122 bool TopLevelObject) {
1123 // Handle GNU flexible array initializers.
1124 unsigned FlexArrayDiag;
1125 if (isa<InitListExpr>(InitExpr) &&
1126 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1127 // Empty flexible array init always allowed as an extension
1128 FlexArrayDiag = diag::ext_flexible_array_init;
1129 } else if (SemaRef.getLangOptions().CPlusPlus) {
1130 // Disallow flexible array init in C++; it is not required for gcc
1131 // compatibility, and it needs work to IRGen correctly in general.
1132 FlexArrayDiag = diag::err_flexible_array_init;
1133 } else if (!TopLevelObject) {
1134 // Disallow flexible array init on non-top-level object
1135 FlexArrayDiag = diag::err_flexible_array_init;
1136 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1137 // Disallow flexible array init on anything which is not a variable.
1138 FlexArrayDiag = diag::err_flexible_array_init;
1139 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1140 // Disallow flexible array init on local variables.
1141 FlexArrayDiag = diag::err_flexible_array_init;
1142 } else {
1143 // Allow other cases.
1144 FlexArrayDiag = diag::ext_flexible_array_init;
1145 }
1146
1147 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1148 FlexArrayDiag)
1149 << InitExpr->getSourceRange().getBegin();
1150 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1151 << Field;
1152
1153 return FlexArrayDiag != diag::ext_flexible_array_init;
1154}
1155
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001156void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001157 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001158 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001159 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001160 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001161 unsigned &Index,
1162 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001163 unsigned &StructuredIndex,
1164 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001165 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Eli Friedmanb85f7072008-05-19 19:16:24 +00001167 // If the record is invalid, some of it's members are invalid. To avoid
1168 // confusion, we forgo checking the intializer for the entire record.
1169 if (structDecl->isInvalidDecl()) {
1170 hadError = true;
1171 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001172 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001173
1174 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1175 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001176 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001177 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001178 Field != FieldEnd; ++Field) {
1179 if (Field->getDeclName()) {
1180 StructuredList->setInitializedFieldInUnion(*Field);
1181 break;
1182 }
1183 }
1184 return;
1185 }
1186
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 // If structDecl is a forward declaration, this loop won't do
1188 // anything except look at designated initializers; That's okay,
1189 // because an error should get printed out elsewhere. It might be
1190 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001191 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001192 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001193 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001194 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195 while (Index < IList->getNumInits()) {
1196 Expr *Init = IList->getInit(Index);
1197
1198 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001199 // If we're not the subobject that matches up with the '{' for
1200 // the designator, we shouldn't be handling the
1201 // designator. Return immediately.
1202 if (!SubobjectIsDesignatorContext)
1203 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001205 // Handle this designated initializer. Field will be updated to
1206 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex,
1210 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 hadError = true;
1212
Douglas Gregordfb5e592009-02-12 19:00:39 +00001213 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001214
1215 // Disable check for missing fields when designators are used.
1216 // This matches gcc behaviour.
1217 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001218 continue;
1219 }
1220
1221 if (Field == FieldEnd) {
1222 // We've run out of fields. We're done.
1223 break;
1224 }
1225
Douglas Gregordfb5e592009-02-12 19:00:39 +00001226 // We've already initialized a member of a union. We're done.
1227 if (InitializedSomething && DeclType->isUnionType())
1228 break;
1229
Douglas Gregor44b43212008-12-11 16:49:14 +00001230 // If we've hit the flexible array member at the end, we're done.
1231 if (Field->getType()->isIncompleteArrayType())
1232 break;
1233
Douglas Gregor0bb76892009-01-29 16:53:55 +00001234 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001235 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001236 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001237 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001238 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001239
Douglas Gregor54001c12011-06-29 21:51:31 +00001240 // Make sure we can use this declaration.
1241 if (SemaRef.DiagnoseUseOfDecl(*Field,
1242 IList->getInit(Index)->getLocStart())) {
1243 ++Index;
1244 ++Field;
1245 hadError = true;
1246 continue;
1247 }
1248
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001249 InitializedEntity MemberEntity =
1250 InitializedEntity::InitializeMember(*Field, &Entity);
1251 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1252 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001253 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001254
1255 if (DeclType->isUnionType()) {
1256 // Initialize the first field within the union.
1257 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001258 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001259
1260 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001261 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001262
John McCall80639de2010-03-11 19:32:38 +00001263 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001264 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001265 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1266 // It is possible we have one or more unnamed bitfields remaining.
1267 // Find first (if any) named field and emit warning.
1268 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1269 it != end; ++it) {
1270 if (!it->isUnnamedBitfield()) {
1271 SemaRef.Diag(IList->getSourceRange().getEnd(),
1272 diag::warn_missing_field_initializers) << it->getName();
1273 break;
1274 }
1275 }
1276 }
1277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001279 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001280 return;
1281
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001282 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1283 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001284 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001285 ++Index;
1286 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001287 }
1288
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001289 InitializedEntity MemberEntity =
1290 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001292 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001293 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001294 StructuredList, StructuredIndex);
1295 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001297 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001298}
Steve Naroff0cca7492008-05-01 22:18:59 +00001299
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001300/// \brief Expand a field designator that refers to a member of an
1301/// anonymous struct or union into a series of field designators that
1302/// refers to the field within the appropriate subobject.
1303///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001304static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001305 DesignatedInitExpr *DIE,
1306 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001307 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001308 typedef DesignatedInitExpr::Designator Designator;
1309
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001310 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001311 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001312 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1313 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1314 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001315 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001316 DIE->getDesignator(DesigIdx)->getDotLoc(),
1317 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1318 else
1319 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1320 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001321 assert(isa<FieldDecl>(*PI));
1322 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001323 }
1324
1325 // Expand the current designator into the set of replacement
1326 // designators, so we have a full subobject path down to where the
1327 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001328 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001329 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001330}
Mike Stump1eb44332009-09-09 15:08:12 +00001331
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001332/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001333/// corresponds to FieldName.
1334static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1335 IdentifierInfo *FieldName) {
1336 assert(AnonField->isAnonymousStructOrUnion());
1337 Decl *NextDecl = AnonField->getNextDeclInContext();
1338 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1339 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1340 return IF;
1341 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001342 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001343 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001344}
1345
Douglas Gregor05c13a32009-01-22 00:58:24 +00001346/// @brief Check the well-formedness of a C99 designated initializer.
1347///
1348/// Determines whether the designated initializer @p DIE, which
1349/// resides at the given @p Index within the initializer list @p
1350/// IList, is well-formed for a current object of type @p DeclType
1351/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001352/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001353/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001354///
1355/// @param IList The initializer list in which this designated
1356/// initializer occurs.
1357///
Douglas Gregor71199712009-04-15 04:56:10 +00001358/// @param DIE The designated initializer expression.
1359///
1360/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001361///
1362/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1363/// into which the designation in @p DIE should refer.
1364///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001365/// @param NextField If non-NULL and the first designator in @p DIE is
1366/// a field, this will be set to the field declaration corresponding
1367/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001368///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001369/// @param NextElementIndex If non-NULL and the first designator in @p
1370/// DIE is an array designator or GNU array-range designator, this
1371/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001372///
1373/// @param Index Index into @p IList where the designated initializer
1374/// @p DIE occurs.
1375///
Douglas Gregor4c678342009-01-28 21:54:33 +00001376/// @param StructuredList The initializer list expression that
1377/// describes all of the subobject initializers in the order they'll
1378/// actually be initialized.
1379///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001380/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001381bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001382InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001383 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001384 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001385 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001386 QualType &CurrentObjectType,
1387 RecordDecl::field_iterator *NextField,
1388 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001389 unsigned &Index,
1390 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001391 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001392 bool FinishSubobjectInit,
1393 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001394 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 // Check the actual initialization for the designated object type.
1396 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001397
1398 // Temporarily remove the designator expression from the
1399 // initializer list that the child calls see, so that we don't try
1400 // to re-process the designator.
1401 unsigned OldIndex = Index;
1402 IList->setInit(OldIndex, DIE->getInit());
1403
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001404 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001406
1407 // Restore the designated initializer expression in the syntactic
1408 // form of the initializer list.
1409 if (IList->getInit(OldIndex) != DIE->getInit())
1410 DIE->setInit(IList->getInit(OldIndex));
1411 IList->setInit(OldIndex, DIE);
1412
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001414 }
1415
Douglas Gregor71199712009-04-15 04:56:10 +00001416 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001417 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001418 "Need a non-designated initializer list to start from");
1419
Douglas Gregor71199712009-04-15 04:56:10 +00001420 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001421 // Determine the structural initializer list that corresponds to the
1422 // current subobject.
1423 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001424 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001425 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 SourceRange(D->getStartLocation(),
1427 DIE->getSourceRange().getEnd()));
1428 assert(StructuredList && "Expected a structured initializer list");
1429
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 if (D->isFieldDesignator()) {
1431 // C99 6.7.8p7:
1432 //
1433 // If a designator has the form
1434 //
1435 // . identifier
1436 //
1437 // then the current object (defined below) shall have
1438 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001440 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001441 if (!RT) {
1442 SourceLocation Loc = D->getDotLoc();
1443 if (Loc.isInvalid())
1444 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001445 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1446 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001447 ++Index;
1448 return true;
1449 }
1450
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 // Note: we perform a linear search of the fields here, despite
1452 // the fact that we have a faster lookup method, because we always
1453 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001454 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001455 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001456 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001457 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001458 Field = RT->getDecl()->field_begin(),
1459 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001460 for (; Field != FieldEnd; ++Field) {
1461 if (Field->isUnnamedBitfield())
1462 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463
Francois Picheta0e27f02010-12-22 03:46:10 +00001464 // If we find a field representing an anonymous field, look in the
1465 // IndirectFieldDecl that follow for the designated initializer.
1466 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1467 if (IndirectFieldDecl *IF =
1468 FindIndirectFieldDesignator(*Field, FieldName)) {
1469 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1470 D = DIE->getDesignator(DesigIdx);
1471 break;
1472 }
1473 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001474 if (KnownField && KnownField == *Field)
1475 break;
1476 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001477 break;
1478
1479 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001480 }
1481
Douglas Gregor4c678342009-01-28 21:54:33 +00001482 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001483 // There was no normal field in the struct with the designated
1484 // name. Perform another lookup for this name, which may find
1485 // something that we can't designate (e.g., a member function),
1486 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001489 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001490 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001491 // Name lookup didn't find anything. Determine whether this
1492 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001494 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001495 TypoCorrection Corrected = SemaRef.CorrectTypo(
1496 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1497 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1498 RT->getDecl(), false, Sema::CTC_NoKeywords);
1499 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001500 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001501 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001502 std::string CorrectedStr(
1503 Corrected.getAsString(SemaRef.getLangOptions()));
1504 std::string CorrectedQuotedStr(
1505 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001506 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001507 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001508 << FieldName << CurrentObjectType << CorrectedQuotedStr
1509 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001510 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001511 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001512 } else {
1513 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1514 << FieldName << CurrentObjectType;
1515 ++Index;
1516 return true;
1517 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001520 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001521 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001522 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001523 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001524 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001525 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001526 ++Index;
1527 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001528 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001529
Francois Picheta0e27f02010-12-22 03:46:10 +00001530 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001531 // The replacement field comes from typo correction; find it
1532 // in the list of fields.
1533 FieldIndex = 0;
1534 Field = RT->getDecl()->field_begin();
1535 for (; Field != FieldEnd; ++Field) {
1536 if (Field->isUnnamedBitfield())
1537 continue;
1538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001540 Field->getIdentifier() == ReplacementField->getIdentifier())
1541 break;
1542
1543 ++FieldIndex;
1544 }
1545 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001547
1548 // All of the fields of a union are located at the same place in
1549 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001550 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001551 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001552 StructuredList->setInitializedFieldInUnion(*Field);
1553 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001554
Douglas Gregor54001c12011-06-29 21:51:31 +00001555 // Make sure we can use this declaration.
1556 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1557 ++Index;
1558 return true;
1559 }
1560
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001562 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor4c678342009-01-28 21:54:33 +00001564 // Make sure that our non-designated initializer list has space
1565 // for a subobject corresponding to this field.
1566 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001567 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001568
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001569 // This designator names a flexible array member.
1570 if (Field->getType()->isIncompleteArrayType()) {
1571 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001572 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001573 // We can't designate an object within the flexible array
1574 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001575 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001576 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001577 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001578 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001579 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001580 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001581 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001582 << *Field;
1583 Invalid = true;
1584 }
1585
Chris Lattner9046c222010-10-10 17:49:49 +00001586 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1587 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001588 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001589 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001590 diag::err_flexible_array_init_needs_braces)
1591 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001592 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001593 << *Field;
1594 Invalid = true;
1595 }
1596
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001597 // Check GNU flexible array initializer.
1598 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1599 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001600 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001601
1602 if (Invalid) {
1603 ++Index;
1604 return true;
1605 }
1606
1607 // Initialize the array.
1608 bool prevHadError = hadError;
1609 unsigned newStructuredIndex = FieldIndex;
1610 unsigned OldIndex = Index;
1611 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001612
1613 InitializedEntity MemberEntity =
1614 InitializedEntity::InitializeMember(*Field, &Entity);
1615 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001616 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001617
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001618 IList->setInit(OldIndex, DIE);
1619 if (hadError && !prevHadError) {
1620 ++Field;
1621 ++FieldIndex;
1622 if (NextField)
1623 *NextField = Field;
1624 StructuredIndex = FieldIndex;
1625 return true;
1626 }
1627 } else {
1628 // Recurse to check later designated subobjects.
1629 QualType FieldType = (*Field)->getType();
1630 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001632 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001633 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1635 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001636 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001637 true, false))
1638 return true;
1639 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640
1641 // Find the position of the next field to be initialized in this
1642 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001644 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645
1646 // If this the first designator, our caller will continue checking
1647 // the rest of this struct/class/union subobject.
1648 if (IsFirstDesignator) {
1649 if (NextField)
1650 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001651 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 return false;
1653 }
1654
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 if (!FinishSubobjectInit)
1656 return false;
1657
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001658 // We've already initialized something in the union; we're done.
1659 if (RT->getDecl()->isUnion())
1660 return hadError;
1661
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001662 // Check the remaining fields within this class/struct/union subobject.
1663 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001665 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001667 return hadError && !prevHadError;
1668 }
1669
1670 // C99 6.7.8p6:
1671 //
1672 // If a designator has the form
1673 //
1674 // [ constant-expression ]
1675 //
1676 // then the current object (defined below) shall have array
1677 // type and the expression shall be an integer constant
1678 // expression. If the array is of unknown size, any
1679 // nonnegative value is valid.
1680 //
1681 // Additionally, cope with the GNU extension that permits
1682 // designators of the form
1683 //
1684 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001685 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001686 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001687 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 << CurrentObjectType;
1689 ++Index;
1690 return true;
1691 }
1692
1693 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001694 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1695 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001696 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001697 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001698 DesignatedEndIndex = DesignatedStartIndex;
1699 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001700 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001701
Mike Stump1eb44332009-09-09 15:08:12 +00001702 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001703 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001704 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001705 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001707
Chris Lattnere0fd8322011-02-19 22:28:58 +00001708 // Codegen can't handle evaluating array range designators that have side
1709 // effects, because we replicate the AST value for each initialized element.
1710 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1711 // elements with something that has a side effect, so codegen can emit an
1712 // "error unsupported" error instead of miscompiling the app.
1713 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1714 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001715 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001716 }
1717
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001718 if (isa<ConstantArrayType>(AT)) {
1719 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001720 DesignatedStartIndex
1721 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001722 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001723 DesignatedEndIndex
1724 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001725 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1726 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001727 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001728 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001729 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001730 << IndexExpr->getSourceRange();
1731 ++Index;
1732 return true;
1733 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001734 } else {
1735 // Make sure the bit-widths and signedness match.
1736 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001737 DesignatedEndIndex
1738 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001739 else if (DesignatedStartIndex.getBitWidth() <
1740 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001741 DesignatedStartIndex
1742 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001743 DesignatedStartIndex.setIsUnsigned(true);
1744 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001745 }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor4c678342009-01-28 21:54:33 +00001747 // Make sure that our non-designated initializer list has space
1748 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001749 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001750 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001751 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001752
Douglas Gregor34e79462009-01-28 23:36:17 +00001753 // Repeatedly perform subobject initializations in the range
1754 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001755
Douglas Gregor34e79462009-01-28 23:36:17 +00001756 // Move to the next designator
1757 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1758 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001760 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001761 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001762
Douglas Gregor34e79462009-01-28 23:36:17 +00001763 while (DesignatedStartIndex <= DesignatedEndIndex) {
1764 // Recurse to check later designated subobjects.
1765 QualType ElementType = AT->getElementType();
1766 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001768 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1770 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001771 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001772 (DesignatedStartIndex == DesignatedEndIndex),
1773 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001774 return true;
1775
1776 // Move to the next index in the array that we'll be initializing.
1777 ++DesignatedStartIndex;
1778 ElementIndex = DesignatedStartIndex.getZExtValue();
1779 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001780
1781 // If this the first designator, our caller will continue checking
1782 // the rest of this array subobject.
1783 if (IsFirstDesignator) {
1784 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001785 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001786 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001787 return false;
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor34e79462009-01-28 23:36:17 +00001790 if (!FinishSubobjectInit)
1791 return false;
1792
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001796 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001798 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001799}
1800
Douglas Gregor4c678342009-01-28 21:54:33 +00001801// Get the structured initializer list for a subobject of type
1802// @p CurrentObjectType.
1803InitListExpr *
1804InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1805 QualType CurrentObjectType,
1806 InitListExpr *StructuredList,
1807 unsigned StructuredIndex,
1808 SourceRange InitRange) {
1809 Expr *ExistingInit = 0;
1810 if (!StructuredList)
1811 ExistingInit = SyntacticToSemantic[IList];
1812 else if (StructuredIndex < StructuredList->getNumInits())
1813 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor4c678342009-01-28 21:54:33 +00001815 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1816 return Result;
1817
1818 if (ExistingInit) {
1819 // We are creating an initializer list that initializes the
1820 // subobjects of the current object, but there was already an
1821 // initialization that completely initialized the current
1822 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001823 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001824 // struct X { int a, b; };
1825 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001826 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001827 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1828 // designated initializer re-initializes the whole
1829 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001830 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001831 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001832 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001833 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001834 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001835 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001836 << ExistingInit->getSourceRange();
1837 }
1838
Mike Stump1eb44332009-09-09 15:08:12 +00001839 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001840 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1841 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001842 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001843
Douglas Gregor63982352010-07-13 18:40:04 +00001844 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001845
Douglas Gregorfa219202009-03-20 23:58:33 +00001846 // Pre-allocate storage for the structured initializer list.
1847 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001848 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001849 bool GotNumInits = false;
1850 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001851 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001852 GotNumInits = true;
1853 } else if (Index < IList->getNumInits()) {
1854 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001855 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001856 GotNumInits = true;
1857 }
Douglas Gregor08457732009-03-21 18:13:52 +00001858 }
1859
Mike Stump1eb44332009-09-09 15:08:12 +00001860 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001861 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1862 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1863 NumElements = CAType->getSize().getZExtValue();
1864 // Simple heuristic so that we don't allocate a very large
1865 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001866 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001867 NumElements = 0;
1868 }
John McCall183700f2009-09-21 23:43:11 +00001869 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001870 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001871 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001872 RecordDecl *RDecl = RType->getDecl();
1873 if (RDecl->isUnion())
1874 NumElements = 1;
1875 else
Mike Stump1eb44332009-09-09 15:08:12 +00001876 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001877 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001878 }
1879
Douglas Gregor08457732009-03-21 18:13:52 +00001880 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001881 NumElements = IList->getNumInits();
1882
Ted Kremenek709210f2010-04-13 23:39:13 +00001883 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001884
Douglas Gregor4c678342009-01-28 21:54:33 +00001885 // Link this new initializer list into the structured initializer
1886 // lists.
1887 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001888 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001889 else {
1890 Result->setSyntacticForm(IList);
1891 SyntacticToSemantic[IList] = Result;
1892 }
1893
1894 return Result;
1895}
1896
1897/// Update the initializer at index @p StructuredIndex within the
1898/// structured initializer list to the value @p expr.
1899void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1900 unsigned &StructuredIndex,
1901 Expr *expr) {
1902 // No structured initializer list to update
1903 if (!StructuredList)
1904 return;
1905
Ted Kremenek709210f2010-04-13 23:39:13 +00001906 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1907 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001908 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001909 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001910 diag::warn_initializer_overrides)
1911 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001912 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001913 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001914 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001915 << PrevInit->getSourceRange();
1916 }
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Douglas Gregor4c678342009-01-28 21:54:33 +00001918 ++StructuredIndex;
1919}
1920
Douglas Gregor05c13a32009-01-22 00:58:24 +00001921/// Check that the given Index expression is a valid array designator
1922/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001923/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001924/// and produces a reasonable diagnostic if there is a
1925/// failure. Returns true if there was an error, false otherwise. If
1926/// everything went okay, Value will receive the value of the constant
1927/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001928static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001929CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001930 SourceLocation Loc = Index->getSourceRange().getBegin();
1931
1932 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001933 if (S.VerifyIntegerConstantExpression(Index, &Value))
1934 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935
Chris Lattner3bf68932009-04-25 21:59:05 +00001936 if (Value.isSigned() && Value.isNegative())
1937 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001938 << Value.toString(10) << Index->getSourceRange();
1939
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001940 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001941 return false;
1942}
1943
John McCall60d7b3a2010-08-24 06:29:42 +00001944ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001945 SourceLocation Loc,
1946 bool GNUSyntax,
1947 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001948 typedef DesignatedInitExpr::Designator ASTDesignator;
1949
1950 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 SmallVector<ASTDesignator, 32> Designators;
1952 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001953
1954 // Build designators and check array designator expressions.
1955 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1956 const Designator &D = Desig.getDesignator(Idx);
1957 switch (D.getKind()) {
1958 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001959 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001960 D.getFieldLoc()));
1961 break;
1962
1963 case Designator::ArrayDesignator: {
1964 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1965 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001966 if (!Index->isTypeDependent() &&
1967 !Index->isValueDependent() &&
1968 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001969 Invalid = true;
1970 else {
1971 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001972 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001973 D.getRBracketLoc()));
1974 InitExpressions.push_back(Index);
1975 }
1976 break;
1977 }
1978
1979 case Designator::ArrayRangeDesignator: {
1980 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1981 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1982 llvm::APSInt StartValue;
1983 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001984 bool StartDependent = StartIndex->isTypeDependent() ||
1985 StartIndex->isValueDependent();
1986 bool EndDependent = EndIndex->isTypeDependent() ||
1987 EndIndex->isValueDependent();
1988 if ((!StartDependent &&
1989 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1990 (!EndDependent &&
1991 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001992 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001993 else {
1994 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001995 if (StartDependent || EndDependent) {
1996 // Nothing to compute.
1997 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001998 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001999 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002000 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002001
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002002 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002003 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002004 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002005 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2006 Invalid = true;
2007 } else {
2008 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002009 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002010 D.getEllipsisLoc(),
2011 D.getRBracketLoc()));
2012 InitExpressions.push_back(StartIndex);
2013 InitExpressions.push_back(EndIndex);
2014 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002015 }
2016 break;
2017 }
2018 }
2019 }
2020
2021 if (Invalid || Init.isInvalid())
2022 return ExprError();
2023
2024 // Clear out the expressions within the designation.
2025 Desig.ClearExprs(*this);
2026
2027 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002028 = DesignatedInitExpr::Create(Context,
2029 Designators.data(), Designators.size(),
2030 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002031 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002033 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002034 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2035 << DIE->getSourceRange();
2036 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002037 Diag(DIE->getLocStart(), diag::ext_designated_init)
2038 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002039
Douglas Gregor05c13a32009-01-22 00:58:24 +00002040 return Owned(DIE);
2041}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002042
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002043bool Sema::CheckInitList(const InitializedEntity &Entity,
2044 InitListExpr *&InitList, QualType &DeclType) {
2045 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002046 if (!CheckInitList.HadError())
2047 InitList = CheckInitList.getFullyStructuredList();
2048
2049 return CheckInitList.HadError();
2050}
Douglas Gregor87fd7032009-02-02 17:43:21 +00002051
Douglas Gregor20093b42009-12-09 23:02:17 +00002052//===----------------------------------------------------------------------===//
2053// Initialization entity
2054//===----------------------------------------------------------------------===//
2055
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002056InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002057 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002059{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002060 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2061 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002062 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002063 } else {
2064 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002065 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002066 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002067}
2068
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002069InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002070 CXXBaseSpecifier *Base,
2071 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002072{
2073 InitializedEntity Result;
2074 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002075 Result.Base = reinterpret_cast<uintptr_t>(Base);
2076 if (IsInheritedVirtualBase)
2077 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002078
Douglas Gregord6542d82009-12-22 15:35:07 +00002079 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002080 return Result;
2081}
2082
Douglas Gregor99a2e602009-12-16 01:38:02 +00002083DeclarationName InitializedEntity::getName() const {
2084 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002085 case EK_Parameter: {
2086 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2087 return (D ? D->getDeclName() : DeclarationName());
2088 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002089
2090 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002091 case EK_Member:
2092 return VariableOrMember->getDeclName();
2093
2094 case EK_Result:
2095 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002096 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002097 case EK_Temporary:
2098 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002099 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002100 case EK_ArrayElement:
2101 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002102 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002103 return DeclarationName();
2104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002105
Douglas Gregor99a2e602009-12-16 01:38:02 +00002106 // Silence GCC warning
2107 return DeclarationName();
2108}
2109
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002110DeclaratorDecl *InitializedEntity::getDecl() const {
2111 switch (getKind()) {
2112 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002113 case EK_Member:
2114 return VariableOrMember;
2115
John McCallf85e1932011-06-15 23:02:42 +00002116 case EK_Parameter:
2117 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2118
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002119 case EK_Result:
2120 case EK_Exception:
2121 case EK_New:
2122 case EK_Temporary:
2123 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002124 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002125 case EK_ArrayElement:
2126 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002127 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002128 return 0;
2129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002131 // Silence GCC warning
2132 return 0;
2133}
2134
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002135bool InitializedEntity::allowsNRVO() const {
2136 switch (getKind()) {
2137 case EK_Result:
2138 case EK_Exception:
2139 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002141 case EK_Variable:
2142 case EK_Parameter:
2143 case EK_Member:
2144 case EK_New:
2145 case EK_Temporary:
2146 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002147 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002148 case EK_ArrayElement:
2149 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002150 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002151 break;
2152 }
2153
2154 return false;
2155}
2156
Douglas Gregor20093b42009-12-09 23:02:17 +00002157//===----------------------------------------------------------------------===//
2158// Initialization sequence
2159//===----------------------------------------------------------------------===//
2160
2161void InitializationSequence::Step::Destroy() {
2162 switch (Kind) {
2163 case SK_ResolveAddressOfOverloadedFunction:
2164 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002165 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002166 case SK_CastDerivedToBaseLValue:
2167 case SK_BindReference:
2168 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002169 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002170 case SK_UserConversion:
2171 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002172 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002173 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002174 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002175 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002176 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002177 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002178 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002179 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002180 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002181 case SK_PassByIndirectCopyRestore:
2182 case SK_PassByIndirectRestore:
2183 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185
Douglas Gregor20093b42009-12-09 23:02:17 +00002186 case SK_ConversionSequence:
2187 delete ICS;
2188 }
2189}
2190
Douglas Gregorb70cf442010-03-26 20:14:36 +00002191bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002192 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193}
2194
2195bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002196 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002197 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002198
Douglas Gregorb70cf442010-03-26 20:14:36 +00002199 switch (getFailureKind()) {
2200 case FK_TooManyInitsForReference:
2201 case FK_ArrayNeedsInitList:
2202 case FK_ArrayNeedsInitListOrStringLiteral:
2203 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2204 case FK_NonConstLValueReferenceBindingToTemporary:
2205 case FK_NonConstLValueReferenceBindingToUnrelated:
2206 case FK_RValueReferenceBindingToLValue:
2207 case FK_ReferenceInitDropsQualifiers:
2208 case FK_ReferenceInitFailed:
2209 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002210 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002211 case FK_TooManyInitsForScalar:
2212 case FK_ReferenceBindingToInitList:
2213 case FK_InitListBadDestinationType:
2214 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002215 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002216 case FK_ArrayTypeMismatch:
2217 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002218 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Douglas Gregorb70cf442010-03-26 20:14:36 +00002220 case FK_ReferenceInitOverloadFailed:
2221 case FK_UserConversionOverloadFailed:
2222 case FK_ConstructorOverloadFailed:
2223 return FailedOverloadResult == OR_Ambiguous;
2224 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225
Douglas Gregorb70cf442010-03-26 20:14:36 +00002226 return false;
2227}
2228
Douglas Gregord6e44a32010-04-16 22:09:46 +00002229bool InitializationSequence::isConstructorInitialization() const {
2230 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2231}
2232
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002233bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2234 const Expr *Initializer,
2235 bool *isInitializerConstant,
2236 APValue *ConstantValue) const {
2237 if (Steps.empty() || Initializer->isValueDependent())
2238 return false;
2239
2240 const Step &LastStep = Steps.back();
2241 if (LastStep.Kind != SK_ConversionSequence)
2242 return false;
2243
2244 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2245 const StandardConversionSequence *SCS = NULL;
2246 switch (ICS.getKind()) {
2247 case ImplicitConversionSequence::StandardConversion:
2248 SCS = &ICS.Standard;
2249 break;
2250 case ImplicitConversionSequence::UserDefinedConversion:
2251 SCS = &ICS.UserDefined.After;
2252 break;
2253 case ImplicitConversionSequence::AmbiguousConversion:
2254 case ImplicitConversionSequence::EllipsisConversion:
2255 case ImplicitConversionSequence::BadConversion:
2256 return false;
2257 }
2258
2259 // Check if SCS represents a narrowing conversion, according to C++0x
2260 // [dcl.init.list]p7:
2261 //
2262 // A narrowing conversion is an implicit conversion ...
2263 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2264 QualType FromType = SCS->getToType(0);
2265 QualType ToType = SCS->getToType(1);
2266 switch (PossibleNarrowing) {
2267 // * from a floating-point type to an integer type, or
2268 //
2269 // * from an integer type or unscoped enumeration type to a floating-point
2270 // type, except where the source is a constant expression and the actual
2271 // value after conversion will fit into the target type and will produce
2272 // the original value when converted back to the original type, or
2273 case ICK_Floating_Integral:
2274 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2275 *isInitializerConstant = false;
2276 return true;
2277 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2278 llvm::APSInt IntConstantValue;
2279 if (Initializer &&
2280 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2281 // Convert the integer to the floating type.
2282 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2283 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2284 llvm::APFloat::rmNearestTiesToEven);
2285 // And back.
2286 llvm::APSInt ConvertedValue = IntConstantValue;
2287 bool ignored;
2288 Result.convertToInteger(ConvertedValue,
2289 llvm::APFloat::rmTowardZero, &ignored);
2290 // If the resulting value is different, this was a narrowing conversion.
2291 if (IntConstantValue != ConvertedValue) {
2292 *isInitializerConstant = true;
2293 *ConstantValue = APValue(IntConstantValue);
2294 return true;
2295 }
2296 } else {
2297 // Variables are always narrowings.
2298 *isInitializerConstant = false;
2299 return true;
2300 }
2301 }
2302 return false;
2303
2304 // * from long double to double or float, or from double to float, except
2305 // where the source is a constant expression and the actual value after
2306 // conversion is within the range of values that can be represented (even
2307 // if it cannot be represented exactly), or
2308 case ICK_Floating_Conversion:
2309 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2310 // FromType is larger than ToType.
2311 Expr::EvalResult InitializerValue;
2312 // FIXME: Check whether Initializer is a constant expression according
2313 // to C++0x [expr.const], rather than just whether it can be folded.
2314 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2315 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2316 // Constant! (Except for FIXME above.)
2317 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2318 // Convert the source value into the target type.
2319 bool ignored;
2320 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2321 Ctx.getFloatTypeSemantics(ToType),
2322 llvm::APFloat::rmNearestTiesToEven, &ignored);
2323 // If there was no overflow, the source value is within the range of
2324 // values that can be represented.
2325 if (ConvertStatus & llvm::APFloat::opOverflow) {
2326 *isInitializerConstant = true;
2327 *ConstantValue = InitializerValue.Val;
2328 return true;
2329 }
2330 } else {
2331 *isInitializerConstant = false;
2332 return true;
2333 }
2334 }
2335 return false;
2336
2337 // * from an integer type or unscoped enumeration type to an integer type
2338 // that cannot represent all the values of the original type, except where
2339 // the source is a constant expression and the actual value after
2340 // conversion will fit into the target type and will produce the original
2341 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002342 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002343 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2344 // Boolean conversions can be from pointers and pointers to members
2345 // [conv.bool], and those aren't considered narrowing conversions.
2346 return false;
2347 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002348 case ICK_Integral_Conversion: {
2349 assert(FromType->isIntegralOrUnscopedEnumerationType());
2350 assert(ToType->isIntegralOrUnscopedEnumerationType());
2351 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2352 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2353 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2354 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2355
2356 if (FromWidth > ToWidth ||
2357 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2358 // Not all values of FromType can be represented in ToType.
2359 llvm::APSInt InitializerValue;
2360 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2361 *isInitializerConstant = true;
2362 *ConstantValue = APValue(InitializerValue);
2363
2364 // Add a bit to the InitializerValue so we don't have to worry about
2365 // signed vs. unsigned comparisons.
2366 InitializerValue = InitializerValue.extend(
2367 InitializerValue.getBitWidth() + 1);
2368 // Convert the initializer to and from the target width and signed-ness.
2369 llvm::APSInt ConvertedValue = InitializerValue;
2370 ConvertedValue = ConvertedValue.trunc(ToWidth);
2371 ConvertedValue.setIsSigned(ToSigned);
2372 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2373 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2374 // If the result is different, this was a narrowing conversion.
2375 return ConvertedValue != InitializerValue;
2376 } else {
2377 // Variables are always narrowings.
2378 *isInitializerConstant = false;
2379 return true;
2380 }
2381 }
2382 return false;
2383 }
2384
2385 default:
2386 // Other kinds of conversions are not narrowings.
2387 return false;
2388 }
2389}
2390
Douglas Gregor20093b42009-12-09 23:02:17 +00002391void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002392 FunctionDecl *Function,
2393 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002394 Step S;
2395 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2396 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002397 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002398 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002399 Steps.push_back(S);
2400}
2401
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002402void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002403 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002404 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002405 switch (VK) {
2406 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2407 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2408 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002409 default: llvm_unreachable("No such category");
2410 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 S.Type = BaseType;
2412 Steps.push_back(S);
2413}
2414
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002415void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 bool BindingTemporary) {
2417 Step S;
2418 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2419 S.Type = T;
2420 Steps.push_back(S);
2421}
2422
Douglas Gregor523d46a2010-04-18 07:40:54 +00002423void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2424 Step S;
2425 S.Kind = SK_ExtraneousCopyToTemporary;
2426 S.Type = T;
2427 Steps.push_back(S);
2428}
2429
Eli Friedman03981012009-12-11 02:42:07 +00002430void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002431 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002432 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 Step S;
2434 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002435 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002436 S.Function.Function = Function;
2437 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002438 Steps.push_back(S);
2439}
2440
2441void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002442 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002444 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002445 switch (VK) {
2446 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002447 S.Kind = SK_QualificationConversionRValue;
2448 break;
John McCall5baba9d2010-08-25 10:28:54 +00002449 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002450 S.Kind = SK_QualificationConversionXValue;
2451 break;
John McCall5baba9d2010-08-25 10:28:54 +00002452 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002453 S.Kind = SK_QualificationConversionLValue;
2454 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002455 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002456 S.Type = Ty;
2457 Steps.push_back(S);
2458}
2459
2460void InitializationSequence::AddConversionSequenceStep(
2461 const ImplicitConversionSequence &ICS,
2462 QualType T) {
2463 Step S;
2464 S.Kind = SK_ConversionSequence;
2465 S.Type = T;
2466 S.ICS = new ImplicitConversionSequence(ICS);
2467 Steps.push_back(S);
2468}
2469
Douglas Gregord87b61f2009-12-10 17:56:55 +00002470void InitializationSequence::AddListInitializationStep(QualType T) {
2471 Step S;
2472 S.Kind = SK_ListInitialization;
2473 S.Type = T;
2474 Steps.push_back(S);
2475}
2476
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002478InitializationSequence::AddConstructorInitializationStep(
2479 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002480 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002481 QualType T) {
2482 Step S;
2483 S.Kind = SK_ConstructorInitialization;
2484 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002485 S.Function.Function = Constructor;
2486 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002487 Steps.push_back(S);
2488}
2489
Douglas Gregor71d17402009-12-15 00:01:57 +00002490void InitializationSequence::AddZeroInitializationStep(QualType T) {
2491 Step S;
2492 S.Kind = SK_ZeroInitialization;
2493 S.Type = T;
2494 Steps.push_back(S);
2495}
2496
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002497void InitializationSequence::AddCAssignmentStep(QualType T) {
2498 Step S;
2499 S.Kind = SK_CAssignment;
2500 S.Type = T;
2501 Steps.push_back(S);
2502}
2503
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002504void InitializationSequence::AddStringInitStep(QualType T) {
2505 Step S;
2506 S.Kind = SK_StringInit;
2507 S.Type = T;
2508 Steps.push_back(S);
2509}
2510
Douglas Gregor569c3162010-08-07 11:51:51 +00002511void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2512 Step S;
2513 S.Kind = SK_ObjCObjectConversion;
2514 S.Type = T;
2515 Steps.push_back(S);
2516}
2517
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002518void InitializationSequence::AddArrayInitStep(QualType T) {
2519 Step S;
2520 S.Kind = SK_ArrayInit;
2521 S.Type = T;
2522 Steps.push_back(S);
2523}
2524
John McCallf85e1932011-06-15 23:02:42 +00002525void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2526 bool shouldCopy) {
2527 Step s;
2528 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2529 : SK_PassByIndirectRestore);
2530 s.Type = type;
2531 Steps.push_back(s);
2532}
2533
2534void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2535 Step S;
2536 S.Kind = SK_ProduceObjCObject;
2537 S.Type = T;
2538 Steps.push_back(S);
2539}
2540
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002543 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002544 this->Failure = Failure;
2545 this->FailedOverloadResult = Result;
2546}
2547
2548//===----------------------------------------------------------------------===//
2549// Attempt initialization
2550//===----------------------------------------------------------------------===//
2551
John McCallf85e1932011-06-15 23:02:42 +00002552static void MaybeProduceObjCObject(Sema &S,
2553 InitializationSequence &Sequence,
2554 const InitializedEntity &Entity) {
2555 if (!S.getLangOptions().ObjCAutoRefCount) return;
2556
2557 /// When initializing a parameter, produce the value if it's marked
2558 /// __attribute__((ns_consumed)).
2559 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2560 if (!Entity.isParameterConsumed())
2561 return;
2562
2563 assert(Entity.getType()->isObjCRetainableType() &&
2564 "consuming an object of unretainable type?");
2565 Sequence.AddProduceObjCObjectStep(Entity.getType());
2566
2567 /// When initializing a return value, if the return type is a
2568 /// retainable type, then returns need to immediately retain the
2569 /// object. If an autorelease is required, it will be done at the
2570 /// last instant.
2571 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2572 if (!Entity.getType()->isObjCRetainableType())
2573 return;
2574
2575 Sequence.AddProduceObjCObjectStep(Entity.getType());
2576 }
2577}
2578
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002579/// \brief Attempt list initialization (C++0x [dcl.init.list])
2580static void TryListInitialization(Sema &S,
2581 const InitializedEntity &Entity,
2582 const InitializationKind &Kind,
2583 InitListExpr *InitList,
2584 InitializationSequence &Sequence) {
2585 // FIXME: We only perform rudimentary checking of list
2586 // initializations at this point, then assume that any list
2587 // initialization of an array, aggregate, or scalar will be
2588 // well-formed. When we actually "perform" list initialization, we'll
2589 // do all of the necessary checking. C++0x initializer lists will
2590 // force us to perform more checking here.
2591
2592 QualType DestType = Entity.getType();
2593
2594 // C++ [dcl.init]p13:
2595 // If T is a scalar type, then a declaration of the form
2596 //
2597 // T x = { a };
2598 //
2599 // is equivalent to
2600 //
2601 // T x = a;
2602 if (DestType->isScalarType()) {
2603 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2604 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2605 return;
2606 }
2607
2608 // Assume scalar initialization from a single value works.
2609 } else if (DestType->isAggregateType()) {
2610 // Assume aggregate initialization works.
2611 } else if (DestType->isVectorType()) {
2612 // Assume vector initialization works.
2613 } else if (DestType->isReferenceType()) {
2614 // FIXME: C++0x defines behavior for this.
2615 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2616 return;
2617 } else if (DestType->isRecordType()) {
2618 // FIXME: C++0x defines behavior for this
2619 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2620 }
2621
2622 // Add a general "list initialization" step.
2623 Sequence.AddListInitializationStep(DestType);
2624}
Douglas Gregor20093b42009-12-09 23:02:17 +00002625
2626/// \brief Try a reference initialization that involves calling a conversion
2627/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002628static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2629 const InitializedEntity &Entity,
2630 const InitializationKind &Kind,
2631 Expr *Initializer,
2632 bool AllowRValues,
2633 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002634 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002635 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2636 QualType T1 = cv1T1.getUnqualifiedType();
2637 QualType cv2T2 = Initializer->getType();
2638 QualType T2 = cv2T2.getUnqualifiedType();
2639
2640 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002641 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002642 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002644 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002645 ObjCConversion,
2646 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002648 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002649 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002650 (void)ObjCLifetimeConversion;
2651
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 // Build the candidate set directly in the initialization sequence
2653 // structure, so that it will persist if we fail.
2654 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2655 CandidateSet.clear();
2656
2657 // Determine whether we are allowed to call explicit constructors or
2658 // explicit conversion operators.
2659 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660
Douglas Gregor20093b42009-12-09 23:02:17 +00002661 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002662 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2663 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002664 // The type we're converting to is a class type. Enumerate its constructors
2665 // to see if there is a suitable conversion.
2666 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002667
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002669 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002670 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002671 NamedDecl *D = *Con;
2672 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2673
Douglas Gregor20093b42009-12-09 23:02:17 +00002674 // Find the constructor (which may be a template).
2675 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002676 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002677 if (ConstructorTmpl)
2678 Constructor = cast<CXXConstructorDecl>(
2679 ConstructorTmpl->getTemplatedDecl());
2680 else
John McCall9aa472c2010-03-19 07:35:19 +00002681 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 if (!Constructor->isInvalidDecl() &&
2684 Constructor->isConvertingConstructor(AllowExplicit)) {
2685 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002686 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002687 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002688 &Initializer, 1, CandidateSet,
2689 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002690 else
John McCall9aa472c2010-03-19 07:35:19 +00002691 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002692 &Initializer, 1, CandidateSet,
2693 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002695 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002696 }
John McCall572fc622010-08-17 07:23:57 +00002697 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2698 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002700 const RecordType *T2RecordType = 0;
2701 if ((T2RecordType = T2->getAs<RecordType>()) &&
2702 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002703 // The type we're converting from is a class type, enumerate its conversion
2704 // functions.
2705 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2706
John McCalleec51cf2010-01-20 00:46:10 +00002707 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002708 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002709 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2710 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002711 NamedDecl *D = *I;
2712 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2713 if (isa<UsingShadowDecl>(D))
2714 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715
Douglas Gregor20093b42009-12-09 23:02:17 +00002716 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2717 CXXConversionDecl *Conv;
2718 if (ConvTemplate)
2719 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2720 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002721 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722
Douglas Gregor20093b42009-12-09 23:02:17 +00002723 // If the conversion function doesn't return a reference type,
2724 // it can't be considered for this conversion unless we're allowed to
2725 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726 // FIXME: Do we need to make sure that we only consider conversion
2727 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 // break recursion.
2729 if ((AllowExplicit || !Conv->isExplicit()) &&
2730 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2731 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002732 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002733 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002734 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002735 else
John McCall9aa472c2010-03-19 07:35:19 +00002736 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002737 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002738 }
2739 }
2740 }
John McCall572fc622010-08-17 07:23:57 +00002741 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2742 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002743
Douglas Gregor20093b42009-12-09 23:02:17 +00002744 SourceLocation DeclLoc = Initializer->getLocStart();
2745
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002747 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002748 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002749 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002750 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002751
Douglas Gregor20093b42009-12-09 23:02:17 +00002752 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002753
Chandler Carruth25ca4212011-02-25 19:41:05 +00002754 // This is the overload that will actually be used for the initialization, so
2755 // mark it as used.
2756 S.MarkDeclarationReferenced(DeclLoc, Function);
2757
Eli Friedman03981012009-12-11 02:42:07 +00002758 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002759 if (isa<CXXConversionDecl>(Function))
2760 T2 = Function->getResultType();
2761 else
2762 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002763
2764 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002765 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002766 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002767
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002769 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002770 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002771 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002772 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002773 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002774 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002775
Douglas Gregor20093b42009-12-09 23:02:17 +00002776 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002777 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002778 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002779 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002780 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002781 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002782 NewDerivedToBase, NewObjCConversion,
2783 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002784 if (NewRefRelationship == Sema::Ref_Incompatible) {
2785 // If the type we've converted to is not reference-related to the
2786 // type we're looking for, then there is another conversion step
2787 // we need to perform to produce a temporary of the right type
2788 // that we'll be binding to.
2789 ImplicitConversionSequence ICS;
2790 ICS.setStandard();
2791 ICS.Standard = Best->FinalConversion;
2792 T2 = ICS.Standard.getToType(2);
2793 Sequence.AddConversionSequenceStep(ICS, T2);
2794 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 Sequence.AddDerivedToBaseCastStep(
2796 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002798 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002799 else if (NewObjCConversion)
2800 Sequence.AddObjCObjectConversionStep(
2801 S.Context.getQualifiedType(T1,
2802 T2.getNonReferenceType().getQualifiers()));
2803
Douglas Gregor20093b42009-12-09 23:02:17 +00002804 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002805 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806
Douglas Gregor20093b42009-12-09 23:02:17 +00002807 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2808 return OR_Success;
2809}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810
2811/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2812static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002813 const InitializedEntity &Entity,
2814 const InitializationKind &Kind,
2815 Expr *Initializer,
2816 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002817 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002819 Qualifiers T1Quals;
2820 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002821 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002822 Qualifiers T2Quals;
2823 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002825
Douglas Gregor20093b42009-12-09 23:02:17 +00002826 // If the initializer is the address of an overloaded function, try
2827 // to resolve the overloaded function. If all goes well, T2 is the
2828 // type of the resulting function.
2829 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002830 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002831 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002832 T1,
2833 false,
2834 Found)) {
2835 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2836 cv2T2 = Fn->getType();
2837 T2 = cv2T2.getUnqualifiedType();
2838 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002839 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2840 return;
2841 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002842 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002843
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 // Compute some basic properties of the types and the initializer.
2845 bool isLValueRef = DestType->isLValueReferenceType();
2846 bool isRValueRef = !isLValueRef;
2847 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002848 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002849 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002850 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002852 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002853 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002854
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002857 // "cv2 T2" as follows:
2858 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002860 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002861 // Note the analogous bullet points for rvlaue refs to functions. Because
2862 // there are no function rvalues in C++, rvalue refs to functions are treated
2863 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002864 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002865 bool T1Function = T1->isFunctionType();
2866 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002867 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002868 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002870 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002872 // reference-compatible with "cv2 T2," or
2873 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002875 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002876 // can occur. However, we do pay attention to whether it is a bit-field
2877 // to decide whether we're actually binding to a temporary created from
2878 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002879 if (DerivedToBase)
2880 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002882 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002883 else if (ObjCConversion)
2884 Sequence.AddObjCObjectConversionStep(
2885 S.Context.getQualifiedType(T1, T2Quals));
2886
Chandler Carruth5535c382010-01-12 20:32:25 +00002887 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002888 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002889 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002890 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002891 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 return;
2893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894
2895 // - has a class type (i.e., T2 is a class type), where T1 is not
2896 // reference-related to T2, and can be implicitly converted to an
2897 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2898 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002899 // applicable conversion functions (13.3.1.6) and choosing the best
2900 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002901 // If we have an rvalue ref to function type here, the rhs must be
2902 // an rvalue.
2903 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2904 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002905 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002906 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002908 Sequence);
2909 if (ConvOvlResult == OR_Success)
2910 return;
John McCall1d318332010-01-12 00:44:57 +00002911 if (ConvOvlResult != OR_No_Viable_Function) {
2912 Sequence.SetOverloadFailure(
2913 InitializationSequence::FK_ReferenceInitOverloadFailed,
2914 ConvOvlResult);
2915 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002916 }
2917 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002918
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002920 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002921 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002922 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002923 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2924 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2925 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002926 Sequence.SetOverloadFailure(
2927 InitializationSequence::FK_ReferenceInitOverloadFailed,
2928 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002929 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002930 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002931 ? (RefRelationship == Sema::Ref_Related
2932 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2933 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2934 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002935
Douglas Gregor20093b42009-12-09 23:02:17 +00002936 return;
2937 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002938
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002939 // - If the initializer expression
2940 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2941 // "cv1 T1" is reference-compatible with "cv2 T2"
2942 // Note: functions are handled below.
2943 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002944 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002946 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002947 (InitCategory.isXValue() ||
2948 (InitCategory.isPRValue() && T2->isRecordType()) ||
2949 (InitCategory.isPRValue() && T2->isArrayType()))) {
2950 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2951 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002952 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2953 // compiler the freedom to perform a copy here or bind to the
2954 // object, while C++0x requires that we bind directly to the
2955 // object. Hence, we always bind to the object without making an
2956 // extra copy. However, in C++03 requires that we check for the
2957 // presence of a suitable copy constructor:
2958 //
2959 // The constructor that would be used to make the copy shall
2960 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002961 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002962 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002963 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002964
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002965 if (DerivedToBase)
2966 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2967 ValueKind);
2968 else if (ObjCConversion)
2969 Sequence.AddObjCObjectConversionStep(
2970 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002972 if (T1Quals != T2Quals)
2973 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002975 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978
2979 // - has a class type (i.e., T2 is a class type), where T1 is not
2980 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002981 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2982 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002983 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002984 if (RefRelationship == Sema::Ref_Incompatible) {
2985 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2986 Kind, Initializer,
2987 /*AllowRValues=*/true,
2988 Sequence);
2989 if (ConvOvlResult)
2990 Sequence.SetOverloadFailure(
2991 InitializationSequence::FK_ReferenceInitOverloadFailed,
2992 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002993
Douglas Gregor20093b42009-12-09 23:02:17 +00002994 return;
2995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002996
Douglas Gregor20093b42009-12-09 23:02:17 +00002997 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2998 return;
2999 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003000
3001 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003002 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003003 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003004 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003005
Douglas Gregor20093b42009-12-09 23:02:17 +00003006 // Determine whether we are allowed to call explicit constructors or
3007 // explicit conversion operators.
3008 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003009
3010 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3011
John McCallf85e1932011-06-15 23:02:42 +00003012 ImplicitConversionSequence ICS
3013 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003014 /*SuppressUserConversions*/ false,
3015 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003016 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003017 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3018 /*AllowObjCWritebackConversion=*/false);
3019
3020 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003021 // FIXME: Use the conversion function set stored in ICS to turn
3022 // this into an overloading ambiguity diagnostic. However, we need
3023 // to keep that set as an OverloadCandidateSet rather than as some
3024 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003025 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3026 Sequence.SetOverloadFailure(
3027 InitializationSequence::FK_ReferenceInitOverloadFailed,
3028 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003029 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3030 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003031 else
3032 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003033 return;
John McCallf85e1932011-06-15 23:02:42 +00003034 } else {
3035 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003036 }
3037
3038 // [...] If T1 is reference-related to T2, cv1 must be the
3039 // same cv-qualification as, or greater cv-qualification
3040 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003041 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3042 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003044 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003045 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3046 return;
3047 }
3048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003050 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003052 InitCategory.isLValue()) {
3053 Sequence.SetFailed(
3054 InitializationSequence::FK_RValueReferenceBindingToLValue);
3055 return;
3056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057
Douglas Gregor20093b42009-12-09 23:02:17 +00003058 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3059 return;
3060}
3061
3062/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063/// (C++ [dcl.init.string], C99 6.7.8).
3064static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003065 const InitializedEntity &Entity,
3066 const InitializationKind &Kind,
3067 Expr *Initializer,
3068 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003069 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003070}
3071
Douglas Gregor20093b42009-12-09 23:02:17 +00003072/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3073/// enumerates the constructors of the initialized entity and performs overload
3074/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003075static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003076 const InitializedEntity &Entity,
3077 const InitializationKind &Kind,
3078 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003079 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003080 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003081 // Check constructor arguments for self reference.
3082 if (DeclaratorDecl *DD = Entity.getDecl())
3083 // Parameters arguments are occassionially constructed with itself,
3084 // for instance, in recursive functions. Skip them.
3085 if (!isa<ParmVarDecl>(DD))
3086 for (unsigned i = 0; i < NumArgs; ++i)
3087 S.CheckSelfReference(DD, Args[i]);
3088
Douglas Gregor51c56d62009-12-14 20:49:26 +00003089 // Build the candidate set directly in the initialization sequence
3090 // structure, so that it will persist if we fail.
3091 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3092 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003093
Douglas Gregor51c56d62009-12-14 20:49:26 +00003094 // Determine whether we are allowed to call explicit constructors or
3095 // explicit conversion operators.
3096 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3097 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003098 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003099
3100 // The type we're constructing needs to be complete.
3101 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003102 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003103 return;
3104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003105
Douglas Gregor51c56d62009-12-14 20:49:26 +00003106 // The type we're converting to is a class type. Enumerate its constructors
3107 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003108 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003110 CXXRecordDecl *DestRecordDecl
3111 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregor51c56d62009-12-14 20:49:26 +00003113 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003114 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003115 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003116 NamedDecl *D = *Con;
3117 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003118 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119
Douglas Gregor51c56d62009-12-14 20:49:26 +00003120 // Find the constructor (which may be a template).
3121 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003122 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003123 if (ConstructorTmpl)
3124 Constructor = cast<CXXConstructorDecl>(
3125 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003126 else {
John McCall9aa472c2010-03-19 07:35:19 +00003127 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003128
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003130 // suppress user-defined conversions on the arguments.
3131 // FIXME: Move constructors?
3132 if (Kind.getKind() == InitializationKind::IK_Copy &&
3133 Constructor->isCopyConstructor())
3134 SuppressUserConversions = true;
3135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003136
Douglas Gregor51c56d62009-12-14 20:49:26 +00003137 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003138 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003139 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003140 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003141 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003142 Args, NumArgs, CandidateSet,
3143 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003144 else
John McCall9aa472c2010-03-19 07:35:19 +00003145 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003146 Args, NumArgs, CandidateSet,
3147 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149 }
3150
Douglas Gregor51c56d62009-12-14 20:49:26 +00003151 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152
3153 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003154 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003155 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003156 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003157 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003159 Result);
3160 return;
3161 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003162
3163 // C++0x [dcl.init]p6:
3164 // If a program calls for the default initialization of an object
3165 // of a const-qualified type T, T shall be a class type with a
3166 // user-provided default constructor.
3167 if (Kind.getKind() == InitializationKind::IK_Default &&
3168 Entity.getType().isConstQualified() &&
3169 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3170 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3171 return;
3172 }
3173
Douglas Gregor51c56d62009-12-14 20:49:26 +00003174 // Add the constructor initialization step. Any cv-qualification conversion is
3175 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003176 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003178 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003179 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003180}
3181
Douglas Gregor71d17402009-12-15 00:01:57 +00003182/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003184 const InitializedEntity &Entity,
3185 const InitializationKind &Kind,
3186 InitializationSequence &Sequence) {
3187 // C++ [dcl.init]p5:
3188 //
3189 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003190 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003191
Douglas Gregor71d17402009-12-15 00:01:57 +00003192 // -- if T is an array type, then each element is value-initialized;
3193 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3194 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195
Douglas Gregor71d17402009-12-15 00:01:57 +00003196 if (const RecordType *RT = T->getAs<RecordType>()) {
3197 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3198 // -- if T is a class type (clause 9) with a user-declared
3199 // constructor (12.1), then the default constructor for T is
3200 // called (and the initialization is ill-formed if T has no
3201 // accessible default constructor);
3202 //
3203 // FIXME: we really want to refer to a single subobject of the array,
3204 // but Entity doesn't have a way to capture that (yet).
3205 if (ClassDecl->hasUserDeclaredConstructor())
3206 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207
Douglas Gregor16006c92009-12-16 18:50:27 +00003208 // -- if T is a (possibly cv-qualified) non-union class type
3209 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003210 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003211 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003212 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003213 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003214 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003216 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003217 }
3218 }
3219
Douglas Gregord6542d82009-12-22 15:35:07 +00003220 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003221}
3222
Douglas Gregor99a2e602009-12-16 01:38:02 +00003223/// \brief Attempt default initialization (C++ [dcl.init]p6).
3224static void TryDefaultInitialization(Sema &S,
3225 const InitializedEntity &Entity,
3226 const InitializationKind &Kind,
3227 InitializationSequence &Sequence) {
3228 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229
Douglas Gregor99a2e602009-12-16 01:38:02 +00003230 // C++ [dcl.init]p6:
3231 // To default-initialize an object of type T means:
3232 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003233 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3234
Douglas Gregor99a2e602009-12-16 01:38:02 +00003235 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3236 // constructor for T is called (and the initialization is ill-formed if
3237 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003238 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003239 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3240 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003242
Douglas Gregor99a2e602009-12-16 01:38:02 +00003243 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003244
Douglas Gregor99a2e602009-12-16 01:38:02 +00003245 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003247 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003248 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003249 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003250 return;
3251 }
3252
3253 // If the destination type has a lifetime property, zero-initialize it.
3254 if (DestType.getQualifiers().hasObjCLifetime()) {
3255 Sequence.AddZeroInitializationStep(Entity.getType());
3256 return;
3257 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003258}
3259
Douglas Gregor20093b42009-12-09 23:02:17 +00003260/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3261/// which enumerates all conversion functions and performs overload resolution
3262/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 const InitializedEntity &Entity,
3265 const InitializationKind &Kind,
3266 Expr *Initializer,
3267 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003268 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003269 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3270 QualType SourceType = Initializer->getType();
3271 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3272 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273
Douglas Gregor4a520a22009-12-14 17:27:33 +00003274 // Build the candidate set directly in the initialization sequence
3275 // structure, so that it will persist if we fail.
3276 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3277 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278
Douglas Gregor4a520a22009-12-14 17:27:33 +00003279 // Determine whether we are allowed to call explicit constructors or
3280 // explicit conversion operators.
3281 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003282
Douglas Gregor4a520a22009-12-14 17:27:33 +00003283 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3284 // The type we're converting to is a class type. Enumerate its constructors
3285 // to see if there is a suitable conversion.
3286 CXXRecordDecl *DestRecordDecl
3287 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003289 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003291 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003292 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003293 Con != ConEnd; ++Con) {
3294 NamedDecl *D = *Con;
3295 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003297 // Find the constructor (which may be a template).
3298 CXXConstructorDecl *Constructor = 0;
3299 FunctionTemplateDecl *ConstructorTmpl
3300 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003301 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003302 Constructor = cast<CXXConstructorDecl>(
3303 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003304 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003305 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003306
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003307 if (!Constructor->isInvalidDecl() &&
3308 Constructor->isConvertingConstructor(AllowExplicit)) {
3309 if (ConstructorTmpl)
3310 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3311 /*ExplicitArgs*/ 0,
3312 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003313 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003314 else
3315 S.AddOverloadCandidate(Constructor, FoundDecl,
3316 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003317 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003319 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003320 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003321 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003322
3323 SourceLocation DeclLoc = Initializer->getLocStart();
3324
Douglas Gregor4a520a22009-12-14 17:27:33 +00003325 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3326 // The type we're converting from is a class type, enumerate its conversion
3327 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003328
Eli Friedman33c2da92009-12-20 22:12:03 +00003329 // We can only enumerate the conversion functions for a complete type; if
3330 // the type isn't complete, simply skip this step.
3331 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3332 CXXRecordDecl *SourceRecordDecl
3333 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334
John McCalleec51cf2010-01-20 00:46:10 +00003335 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003336 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003337 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003339 I != E; ++I) {
3340 NamedDecl *D = *I;
3341 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3342 if (isa<UsingShadowDecl>(D))
3343 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344
Eli Friedman33c2da92009-12-20 22:12:03 +00003345 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3346 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003347 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003348 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003349 else
John McCall32daa422010-03-31 01:36:47 +00003350 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351
Eli Friedman33c2da92009-12-20 22:12:03 +00003352 if (AllowExplicit || !Conv->isExplicit()) {
3353 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003354 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003355 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003356 CandidateSet);
3357 else
John McCall9aa472c2010-03-19 07:35:19 +00003358 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003359 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003360 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003361 }
3362 }
3363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
3365 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003366 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003367 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003368 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003369 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003371 Result);
3372 return;
3373 }
John McCall1d318332010-01-12 00:44:57 +00003374
Douglas Gregor4a520a22009-12-14 17:27:33 +00003375 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003376 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377
Douglas Gregor4a520a22009-12-14 17:27:33 +00003378 if (isa<CXXConstructorDecl>(Function)) {
3379 // Add the user-defined conversion step. Any cv-qualification conversion is
3380 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003381 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003382 return;
3383 }
3384
3385 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003386 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003387 if (ConvType->getAs<RecordType>()) {
3388 // If we're converting to a class type, there may be an copy if
3389 // the resulting temporary object (possible to create an object of
3390 // a base class type). That copy is not a separate conversion, so
3391 // we just make a note of the actual destination type (possibly a
3392 // base class of the type returned by the conversion function) and
3393 // let the user-defined conversion step handle the conversion.
3394 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3395 return;
3396 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003397
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003398 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003400 // If the conversion following the call to the conversion function
3401 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003402 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3403 Best->FinalConversion.Third) {
3404 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003405 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003406 ICS.Standard = Best->FinalConversion;
3407 Sequence.AddConversionSequenceStep(ICS, DestType);
3408 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003409}
3410
John McCallf85e1932011-06-15 23:02:42 +00003411/// The non-zero enum values here are indexes into diagnostic alternatives.
3412enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3413
3414/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003415static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3416 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003417 // Skip parens.
3418 e = e->IgnoreParens();
3419
3420 // Skip address-of nodes.
3421 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3422 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003423 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003424
3425 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003426 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3427 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003428 case CK_Dependent:
3429 case CK_BitCast:
3430 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003431 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003432 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003433
3434 case CK_ArrayToPointerDecay:
3435 return IIK_nonscalar;
3436
3437 case CK_NullToPointer:
3438 return IIK_okay;
3439
3440 default:
3441 break;
3442 }
3443
3444 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003445 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3446 if (!isAddressOf) return IIK_nonlocal;
3447
3448 VarDecl *var;
3449 if (isa<DeclRefExpr>(e)) {
3450 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3451 if (!var) return IIK_nonlocal;
3452 } else {
3453 var = cast<BlockDeclRefExpr>(e)->getDecl();
3454 }
3455
3456 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003457
3458 // If we have a conditional operator, check both sides.
3459 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003460 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003461 return iik;
3462
John McCallc03fa492011-06-27 23:59:58 +00003463 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003464
3465 // These are never scalar.
3466 } else if (isa<ArraySubscriptExpr>(e)) {
3467 return IIK_nonscalar;
3468
3469 // Otherwise, it needs to be a null pointer constant.
3470 } else {
3471 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3472 ? IIK_okay : IIK_nonlocal);
3473 }
3474
3475 return IIK_nonlocal;
3476}
3477
3478/// Check whether the given expression is a valid operand for an
3479/// indirect copy/restore.
3480static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3481 assert(src->isRValue());
3482
John McCallc03fa492011-06-27 23:59:58 +00003483 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003484 if (iik == IIK_okay) return;
3485
3486 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3487 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3488 << src->getSourceRange();
3489}
3490
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003491/// \brief Determine whether we have compatible array types for the
3492/// purposes of GNU by-copy array initialization.
3493static bool hasCompatibleArrayTypes(ASTContext &Context,
3494 const ArrayType *Dest,
3495 const ArrayType *Source) {
3496 // If the source and destination array types are equivalent, we're
3497 // done.
3498 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3499 return true;
3500
3501 // Make sure that the element types are the same.
3502 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3503 return false;
3504
3505 // The only mismatch we allow is when the destination is an
3506 // incomplete array type and the source is a constant array type.
3507 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3508}
3509
John McCallf85e1932011-06-15 23:02:42 +00003510static bool tryObjCWritebackConversion(Sema &S,
3511 InitializationSequence &Sequence,
3512 const InitializedEntity &Entity,
3513 Expr *Initializer) {
3514 bool ArrayDecay = false;
3515 QualType ArgType = Initializer->getType();
3516 QualType ArgPointee;
3517 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3518 ArrayDecay = true;
3519 ArgPointee = ArgArrayType->getElementType();
3520 ArgType = S.Context.getPointerType(ArgPointee);
3521 }
3522
3523 // Handle write-back conversion.
3524 QualType ConvertedArgType;
3525 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3526 ConvertedArgType))
3527 return false;
3528
3529 // We should copy unless we're passing to an argument explicitly
3530 // marked 'out'.
3531 bool ShouldCopy = true;
3532 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3533 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3534
3535 // Do we need an lvalue conversion?
3536 if (ArrayDecay || Initializer->isGLValue()) {
3537 ImplicitConversionSequence ICS;
3538 ICS.setStandard();
3539 ICS.Standard.setAsIdentityConversion();
3540
3541 QualType ResultType;
3542 if (ArrayDecay) {
3543 ICS.Standard.First = ICK_Array_To_Pointer;
3544 ResultType = S.Context.getPointerType(ArgPointee);
3545 } else {
3546 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3547 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3548 }
3549
3550 Sequence.AddConversionSequenceStep(ICS, ResultType);
3551 }
3552
3553 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3554 return true;
3555}
3556
Douglas Gregor20093b42009-12-09 23:02:17 +00003557InitializationSequence::InitializationSequence(Sema &S,
3558 const InitializedEntity &Entity,
3559 const InitializationKind &Kind,
3560 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003561 unsigned NumArgs)
3562 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003563 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566 // The semantics of initializers are as follows. The destination type is
3567 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003568 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003570 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003571 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003572
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003573 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003574 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3575 SequenceKind = DependentSequence;
3576 return;
3577 }
3578
Sebastian Redl7491c492011-06-05 13:59:11 +00003579 // Almost everything is a normal sequence.
3580 setSequenceKind(NormalSequence);
3581
John McCall241d5582010-12-07 22:54:16 +00003582 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003583 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3584 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3585 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003586 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003587 return;
3588 }
3589 Args[I] = Result.take();
3590 }
John McCall241d5582010-12-07 22:54:16 +00003591
Douglas Gregor20093b42009-12-09 23:02:17 +00003592 QualType SourceType;
3593 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003594 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 Initializer = Args[0];
3596 if (!isa<InitListExpr>(Initializer))
3597 SourceType = Initializer->getType();
3598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003599
3600 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003601 // list-initialized (8.5.4).
3602 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003603 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003604 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 // - If the destination type is a reference type, see 8.5.3.
3608 if (DestType->isReferenceType()) {
3609 // C++0x [dcl.init.ref]p1:
3610 // A variable declared to be a T& or T&&, that is, "reference to type T"
3611 // (8.3.2), shall be initialized by an object, or function, of type T or
3612 // by an object that can be converted into a T.
3613 // (Therefore, multiple arguments are not permitted.)
3614 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003615 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003616 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003617 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 return;
3619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620
Douglas Gregor20093b42009-12-09 23:02:17 +00003621 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003622 if (Kind.getKind() == InitializationKind::IK_Value ||
3623 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003624 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 return;
3626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregor99a2e602009-12-16 01:38:02 +00003628 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003629 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003630 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003631 return;
3632 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003633
John McCallce6c9b72011-02-21 07:22:22 +00003634 // - If the destination type is an array of characters, an array of
3635 // char16_t, an array of char32_t, or an array of wchar_t, and the
3636 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003638 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003639 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3640 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003641 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003642 return;
3643 }
3644
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003645 // Note: as an GNU C extension, we allow initialization of an
3646 // array from a compound literal that creates an array of the same
3647 // type, so long as the initializer has no side effects.
3648 if (!S.getLangOptions().CPlusPlus && Initializer &&
3649 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3650 Initializer->getType()->isArrayType()) {
3651 const ArrayType *SourceAT
3652 = Context.getAsArrayType(Initializer->getType());
3653 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003654 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003655 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003656 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003657 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003658 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003659 }
3660 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003661 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003662 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003663 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 return;
3666 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003667
John McCallf85e1932011-06-15 23:02:42 +00003668 // Determine whether we should consider writeback conversions for
3669 // Objective-C ARC.
3670 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3671 Entity.getKind() == InitializedEntity::EK_Parameter;
3672
3673 // We're at the end of the line for C: it's either a write-back conversion
3674 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003675 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003676 // If allowed, check whether this is an Objective-C writeback conversion.
3677 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003678 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003679 return;
3680 }
3681
3682 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003683 AddCAssignmentStep(DestType);
3684 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003685 return;
3686 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
John McCallf85e1932011-06-15 23:02:42 +00003688 assert(S.getLangOptions().CPlusPlus);
3689
Douglas Gregor20093b42009-12-09 23:02:17 +00003690 // - If the destination type is a (possibly cv-qualified) class type:
3691 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692 // - If the initialization is direct-initialization, or if it is
3693 // copy-initialization where the cv-unqualified version of the
3694 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003695 // class of the destination, constructors are considered. [...]
3696 if (Kind.getKind() == InitializationKind::IK_Direct ||
3697 (Kind.getKind() == InitializationKind::IK_Copy &&
3698 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3699 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003701 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003703 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003705 // used) to a derived class thereof are enumerated as described in
3706 // 13.3.1.4, and the best one is chosen through overload resolution
3707 // (13.3).
3708 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003709 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 return;
3711 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003712
Douglas Gregor99a2e602009-12-16 01:38:02 +00003713 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003714 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003715 return;
3716 }
3717 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718
3719 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003720 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003721 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003722 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3723 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003724 return;
3725 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726
Douglas Gregor20093b42009-12-09 23:02:17 +00003727 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003728 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003731 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003732
3733 ImplicitConversionSequence ICS
3734 = S.TryImplicitConversion(Initializer, Entity.getType(),
3735 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003736 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003737 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003738 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3739 allowObjCWritebackConversion);
3740
3741 if (ICS.isStandard() &&
3742 ICS.Standard.Second == ICK_Writeback_Conversion) {
3743 // Objective-C ARC writeback conversion.
3744
3745 // We should copy unless we're passing to an argument explicitly
3746 // marked 'out'.
3747 bool ShouldCopy = true;
3748 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3749 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3750
3751 // If there was an lvalue adjustment, add it as a separate conversion.
3752 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3753 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3754 ImplicitConversionSequence LvalueICS;
3755 LvalueICS.setStandard();
3756 LvalueICS.Standard.setAsIdentityConversion();
3757 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3758 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003759 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003760 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003761
3762 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003763 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003764 DeclAccessPair dap;
3765 if (Initializer->getType() == Context.OverloadTy &&
3766 !S.ResolveAddressOfOverloadedFunction(Initializer
3767 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003768 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003769 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003770 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003771 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003772 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003773
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003774 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003775 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003776}
3777
3778InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003779 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003780 StepEnd = Steps.end();
3781 Step != StepEnd; ++Step)
3782 Step->Destroy();
3783}
3784
3785//===----------------------------------------------------------------------===//
3786// Perform initialization
3787//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003789getAssignmentAction(const InitializedEntity &Entity) {
3790 switch(Entity.getKind()) {
3791 case InitializedEntity::EK_Variable:
3792 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003793 case InitializedEntity::EK_Exception:
3794 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003795 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003796 return Sema::AA_Initializing;
3797
3798 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003800 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3801 return Sema::AA_Sending;
3802
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003803 return Sema::AA_Passing;
3804
3805 case InitializedEntity::EK_Result:
3806 return Sema::AA_Returning;
3807
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003808 case InitializedEntity::EK_Temporary:
3809 // FIXME: Can we tell apart casting vs. converting?
3810 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003812 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003813 case InitializedEntity::EK_ArrayElement:
3814 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003815 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003816 return Sema::AA_Initializing;
3817 }
3818
3819 return Sema::AA_Converting;
3820}
3821
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003822/// \brief Whether we should binding a created object as a temporary when
3823/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003824static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003825 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003826 case InitializedEntity::EK_ArrayElement:
3827 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003828 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003829 case InitializedEntity::EK_New:
3830 case InitializedEntity::EK_Variable:
3831 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003832 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003833 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003834 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003835 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003836 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003838 case InitializedEntity::EK_Parameter:
3839 case InitializedEntity::EK_Temporary:
3840 return true;
3841 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003843 llvm_unreachable("missed an InitializedEntity kind?");
3844}
3845
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003846/// \brief Whether the given entity, when initialized with an object
3847/// created for that initialization, requires destruction.
3848static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3849 switch (Entity.getKind()) {
3850 case InitializedEntity::EK_Member:
3851 case InitializedEntity::EK_Result:
3852 case InitializedEntity::EK_New:
3853 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003854 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003855 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003856 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003857 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003859 case InitializedEntity::EK_Variable:
3860 case InitializedEntity::EK_Parameter:
3861 case InitializedEntity::EK_Temporary:
3862 case InitializedEntity::EK_ArrayElement:
3863 case InitializedEntity::EK_Exception:
3864 return true;
3865 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866
3867 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003868}
3869
Douglas Gregor523d46a2010-04-18 07:40:54 +00003870/// \brief Make a (potentially elidable) temporary copy of the object
3871/// provided by the given initializer by calling the appropriate copy
3872/// constructor.
3873///
3874/// \param S The Sema object used for type-checking.
3875///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003876/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003877/// the type of the initializer expression or a superclass thereof.
3878///
3879/// \param Enter The entity being initialized.
3880///
3881/// \param CurInit The initializer expression.
3882///
3883/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3884/// is permitted in C++03 (but not C++0x) when binding a reference to
3885/// an rvalue.
3886///
3887/// \returns An expression that copies the initializer expression into
3888/// a temporary object, or an error expression if a copy could not be
3889/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003890static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003891 QualType T,
3892 const InitializedEntity &Entity,
3893 ExprResult CurInit,
3894 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003895 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003896 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003898 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003899 Class = cast<CXXRecordDecl>(Record->getDecl());
3900 if (!Class)
3901 return move(CurInit);
3902
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003903 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003904 // When certain criteria are met, an implementation is allowed to
3905 // omit the copy/move construction of a class object, even if the
3906 // copy/move constructor and/or destructor for the object have
3907 // side effects. [...]
3908 // - when a temporary class object that has not been bound to a
3909 // reference (12.2) would be copied/moved to a class object
3910 // with the same cv-unqualified type, the copy/move operation
3911 // can be omitted by constructing the temporary object
3912 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003913 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003914 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003915 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003917 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003918 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003919 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003920 switch (Entity.getKind()) {
3921 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003922 Loc = Entity.getReturnLoc();
3923 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003924
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003925 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003926 Loc = Entity.getThrowLoc();
3927 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003929 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003930 Loc = Entity.getDecl()->getLocation();
3931 break;
3932
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003933 case InitializedEntity::EK_ArrayElement:
3934 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003935 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003936 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003937 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003938 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003939 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003940 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003941 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003942 Loc = CurInitExpr->getLocStart();
3943 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003944 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003945
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003946 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003947 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3948 return move(CurInit);
3949
Douglas Gregorcc15f012011-01-21 19:38:21 +00003950 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003951 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003952 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003953 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003954 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003955 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003956 // C++0x [dcl.init]p16, second bullet to class types, this
3957 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003958 CXXConstructorDecl *Constructor = 0;
3959
3960 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003961 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003962 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003963 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003964 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003965 continue;
3966
3967 DeclAccessPair FoundDecl
3968 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3969 S.AddOverloadCandidate(Constructor, FoundDecl,
3970 &CurInitExpr, 1, CandidateSet);
3971 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003972 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003973
3974 // Handle constructor templates.
3975 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3976 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003977 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003978
Douglas Gregor6493cc52010-11-08 17:16:59 +00003979 Constructor = cast<CXXConstructorDecl>(
3980 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003981 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003982 continue;
3983
3984 // FIXME: Do we need to limit this to copy-constructor-like
3985 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003986 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003987 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3988 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3989 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003992 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003993 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003994 case OR_Success:
3995 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003996
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003997 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003998 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3999 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4000 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004001 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004002 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004003 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004004 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004005 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004006 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004007
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004008 case OR_Ambiguous:
4009 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004010 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004011 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004012 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004013 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004014
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004015 case OR_Deleted:
4016 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004017 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004018 << CurInitExpr->getSourceRange();
4019 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004020 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004021 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004022 }
4023
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004024 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004025 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004026 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004027
Anders Carlsson9a68a672010-04-21 18:47:17 +00004028 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004029 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004030
4031 if (IsExtraneousCopy) {
4032 // If this is a totally extraneous copy for C++03 reference
4033 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004034 // expression. We don't generate an (elided) copy operation here
4035 // because doing so would require us to pass down a flag to avoid
4036 // infinite recursion, where each step adds another extraneous,
4037 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004038
Douglas Gregor2559a702010-04-18 07:57:34 +00004039 // Instantiate the default arguments of any extra parameters in
4040 // the selected copy constructor, as if we were going to create a
4041 // proper call to the copy constructor.
4042 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4043 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4044 if (S.RequireCompleteType(Loc, Parm->getType(),
4045 S.PDiag(diag::err_call_incomplete_argument)))
4046 break;
4047
4048 // Build the default argument expression; we don't actually care
4049 // if this succeeds or not, because this routine will complain
4050 // if there was a problem.
4051 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4052 }
4053
Douglas Gregor523d46a2010-04-18 07:40:54 +00004054 return S.Owned(CurInitExpr);
4055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004056
Chandler Carruth25ca4212011-02-25 19:41:05 +00004057 S.MarkDeclarationReferenced(Loc, Constructor);
4058
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004059 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004060 // constructor call (we might have derived-to-base conversions, or
4061 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004062 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004063 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004064 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004065
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004066 // Actually perform the constructor call.
4067 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004068 move_arg(ConstructorArgs),
4069 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004070 CXXConstructExpr::CK_Complete,
4071 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004073 // If we're supposed to bind temporaries, do so.
4074 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4075 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4076 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004077}
Douglas Gregor20093b42009-12-09 23:02:17 +00004078
Douglas Gregora41a8c52010-04-22 00:20:18 +00004079void InitializationSequence::PrintInitLocationNote(Sema &S,
4080 const InitializedEntity &Entity) {
4081 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4082 if (Entity.getDecl()->getLocation().isInvalid())
4083 return;
4084
4085 if (Entity.getDecl()->getDeclName())
4086 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4087 << Entity.getDecl()->getDeclName();
4088 else
4089 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4090 }
4091}
4092
Sebastian Redl3b802322011-07-14 19:07:55 +00004093static bool isReferenceBinding(const InitializationSequence::Step &s) {
4094 return s.Kind == InitializationSequence::SK_BindReference ||
4095 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4096}
4097
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004098ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004099InitializationSequence::Perform(Sema &S,
4100 const InitializedEntity &Entity,
4101 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004102 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004103 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004104 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004105 unsigned NumArgs = Args.size();
4106 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004107 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004109
Sebastian Redl7491c492011-06-05 13:59:11 +00004110 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004111 // If the declaration is a non-dependent, incomplete array type
4112 // that has an initializer, then its type will be completed once
4113 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004114 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004115 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004116 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004117 if (const IncompleteArrayType *ArrayT
4118 = S.Context.getAsIncompleteArrayType(DeclType)) {
4119 // FIXME: We don't currently have the ability to accurately
4120 // compute the length of an initializer list without
4121 // performing full type-checking of the initializer list
4122 // (since we have to determine where braces are implicitly
4123 // introduced and such). So, we fall back to making the array
4124 // type a dependently-sized array type with no specified
4125 // bound.
4126 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4127 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004128
Douglas Gregord87b61f2009-12-10 17:56:55 +00004129 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004130 if (DeclaratorDecl *DD = Entity.getDecl()) {
4131 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4132 TypeLoc TL = TInfo->getTypeLoc();
4133 if (IncompleteArrayTypeLoc *ArrayLoc
4134 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4135 Brackets = ArrayLoc->getBracketsRange();
4136 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004137 }
4138
4139 *ResultType
4140 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4141 /*NumElts=*/0,
4142 ArrayT->getSizeModifier(),
4143 ArrayT->getIndexTypeCVRQualifiers(),
4144 Brackets);
4145 }
4146
4147 }
4148 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004149 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4150 Kind.isExplicitCast());
4151 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004152 }
4153
Sebastian Redl7491c492011-06-05 13:59:11 +00004154 // No steps means no initialization.
4155 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004156 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004157
Douglas Gregord6542d82009-12-22 15:35:07 +00004158 QualType DestType = Entity.getType().getNonReferenceType();
4159 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004160 // the same as Entity.getDecl()->getType() in cases involving type merging,
4161 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004162 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004163 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004164 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004165
John McCall60d7b3a2010-08-24 06:29:42 +00004166 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004169 // grab the only argument out the Args and place it into the "current"
4170 // initializer.
4171 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004172 case SK_ResolveAddressOfOverloadedFunction:
4173 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004174 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004175 case SK_CastDerivedToBaseLValue:
4176 case SK_BindReference:
4177 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004178 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004179 case SK_UserConversion:
4180 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004181 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004182 case SK_QualificationConversionRValue:
4183 case SK_ConversionSequence:
4184 case SK_ListInitialization:
4185 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004186 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004187 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004188 case SK_ArrayInit:
4189 case SK_PassByIndirectCopyRestore:
4190 case SK_PassByIndirectRestore:
4191 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004192 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004193 CurInit = Args.get()[0];
4194 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004195
4196 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004197 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4198 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4199 if (CurInit.isInvalid())
4200 return ExprError();
4201 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004202 break;
John McCallf6a16482010-12-04 03:47:34 +00004203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004205 case SK_ConstructorInitialization:
4206 case SK_ZeroInitialization:
4207 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209
4210 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004211 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004212 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004213 for (step_iterator Step = step_begin(), StepEnd = step_end();
4214 Step != StepEnd; ++Step) {
4215 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004216 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217
John Wiegley429bb272011-04-08 18:41:53 +00004218 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219
Douglas Gregor20093b42009-12-09 23:02:17 +00004220 switch (Step->Kind) {
4221 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004223 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004224 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004225 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004226 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004227 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004228 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004229 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004230
Douglas Gregor20093b42009-12-09 23:02:17 +00004231 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004232 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004233 case SK_CastDerivedToBaseLValue: {
4234 // We have a derived-to-base cast that produces either an rvalue or an
4235 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236
John McCallf871d0c2010-08-07 06:22:56 +00004237 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004238
Douglas Gregor20093b42009-12-09 23:02:17 +00004239 // Casts to inaccessible base classes are allowed with C-style casts.
4240 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4241 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004242 CurInit.get()->getLocStart(),
4243 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004244 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004245 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004247 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4248 QualType T = SourceType;
4249 if (const PointerType *Pointer = T->getAs<PointerType>())
4250 T = Pointer->getPointeeType();
4251 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004252 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004253 cast<CXXRecordDecl>(RecordTy->getDecl()));
4254 }
4255
John McCall5baba9d2010-08-25 10:28:54 +00004256 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004257 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004258 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004259 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004260 VK_XValue :
4261 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004262 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4263 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004264 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004265 CurInit.get(),
4266 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004267 break;
4268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
Douglas Gregor20093b42009-12-09 23:02:17 +00004270 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004271 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004272 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4273 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004274 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004275 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004276 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004277 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004278 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004279 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004280
John Wiegley429bb272011-04-08 18:41:53 +00004281 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004282 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004283 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4284 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004285 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004286 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004287 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289
Douglas Gregor20093b42009-12-09 23:02:17 +00004290 // Reference binding does not have any corresponding ASTs.
4291
4292 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004293 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004294 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004295
Douglas Gregor20093b42009-12-09 23:02:17 +00004296 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004297
Douglas Gregor20093b42009-12-09 23:02:17 +00004298 case SK_BindReferenceToTemporary:
4299 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004300 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004301 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004302
Douglas Gregor03e80032011-06-21 17:03:29 +00004303 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004304 CurInit = new (S.Context) MaterializeTemporaryExpr(
4305 Entity.getType().getNonReferenceType(),
4306 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004307 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004308
4309 // If we're binding to an Objective-C object that has lifetime, we
4310 // need cleanups.
4311 if (S.getLangOptions().ObjCAutoRefCount &&
4312 CurInit.get()->getType()->isObjCLifetimeType())
4313 S.ExprNeedsCleanups = true;
4314
Douglas Gregor20093b42009-12-09 23:02:17 +00004315 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Douglas Gregor523d46a2010-04-18 07:40:54 +00004317 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004319 /*IsExtraneousCopy=*/true);
4320 break;
4321
Douglas Gregor20093b42009-12-09 23:02:17 +00004322 case SK_UserConversion: {
4323 // We have a user-defined conversion that invokes either a constructor
4324 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004325 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004326 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004327 FunctionDecl *Fn = Step->Function.Function;
4328 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004329 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004330 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004331 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004332 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004333 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004334 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004335 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004336
Douglas Gregor20093b42009-12-09 23:02:17 +00004337 // Determine the arguments required to actually perform the constructor
4338 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004339 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004340 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004341 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004342 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004343 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004344
Douglas Gregor20093b42009-12-09 23:02:17 +00004345 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004347 move_arg(ConstructorArgs),
4348 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004349 CXXConstructExpr::CK_Complete,
4350 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004351 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004352 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004353
Anders Carlsson9a68a672010-04-21 18:47:17 +00004354 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004355 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004356 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357
John McCall2de56d12010-08-25 11:45:40 +00004358 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004359 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4360 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4361 S.IsDerivedFrom(SourceType, Class))
4362 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004364 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004365 } else {
4366 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004367 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004368 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004369 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004370 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004371 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004372
4373 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004374 // derived-to-base conversion? I believe the answer is "no", because
4375 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004376 ExprResult CurInitExprRes =
4377 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4378 FoundFn, Conversion);
4379 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004380 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004381 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004384 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004385 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004386 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004387
John McCall2de56d12010-08-25 11:45:40 +00004388 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004389
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004390 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004392
Sebastian Redl3b802322011-07-14 19:07:55 +00004393 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004394 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004395 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004396 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004397 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004398 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004399 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004400 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004401 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004402 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004403 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4404 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004405 }
4406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407
Sebastian Redl906082e2010-07-20 04:20:21 +00004408 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004409 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004410 CurInit.get()->getType(),
4411 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004412 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004413
Douglas Gregor2f599792010-04-02 18:24:57 +00004414 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004415 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4416 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004417
Douglas Gregor20093b42009-12-09 23:02:17 +00004418 break;
4419 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004420
Douglas Gregor20093b42009-12-09 23:02:17 +00004421 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004422 case SK_QualificationConversionXValue:
4423 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004424 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004425 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004426 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004427 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004428 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004429 VK_XValue :
4430 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004431 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004432 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004433 }
4434
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004435 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004436 Sema::CheckedConversionKind CCK
4437 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4438 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4439 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4440 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004441 ExprResult CurInitExprRes =
4442 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004443 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004444 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004445 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004446 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004447 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449
Douglas Gregord87b61f2009-12-10 17:56:55 +00004450 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004451 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004452 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004453 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004454 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004455
4456 CurInit.release();
4457 CurInit = S.Owned(InitList);
4458 break;
4459 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004460
4461 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004462 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004463 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004464 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004465
Douglas Gregor51c56d62009-12-14 20:49:26 +00004466 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004467 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004468 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4469 ? Kind.getEqualLoc()
4470 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004471
4472 if (Kind.getKind() == InitializationKind::IK_Default) {
4473 // Force even a trivial, implicit default constructor to be
4474 // semantically checked. We do this explicitly because we don't build
4475 // the definition for completely trivial constructors.
4476 CXXRecordDecl *ClassDecl = Constructor->getParent();
4477 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004478 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004479 ClassDecl->hasTrivialDefaultConstructor() &&
4480 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004481 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4482 }
4483
Douglas Gregor51c56d62009-12-14 20:49:26 +00004484 // Determine the arguments required to actually perform the constructor
4485 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004487 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004488 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004489
4490
Douglas Gregor91be6f52010-03-02 17:18:33 +00004491 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004492 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004493 (Kind.getKind() == InitializationKind::IK_Direct ||
4494 Kind.getKind() == InitializationKind::IK_Value)) {
4495 // An explicitly-constructed temporary, e.g., X(1, 2).
4496 unsigned NumExprs = ConstructorArgs.size();
4497 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004498 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004499 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
Douglas Gregorab6677e2010-09-08 00:15:04 +00004501 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4502 if (!TSInfo)
4503 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504
Douglas Gregor91be6f52010-03-02 17:18:33 +00004505 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4506 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004507 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004509 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004510 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004511 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004512 } else {
4513 CXXConstructExpr::ConstructionKind ConstructKind =
4514 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004516 if (Entity.getKind() == InitializedEntity::EK_Base) {
4517 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004518 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004519 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004520 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004521 ConstructKind = CXXConstructExpr::CK_Delegating;
4522 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523
Chandler Carruth428edaf2010-10-25 08:47:36 +00004524 // Only get the parenthesis range if it is a direct construction.
4525 SourceRange parenRange =
4526 Kind.getKind() == InitializationKind::IK_Direct ?
4527 Kind.getParenRange() : SourceRange();
4528
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004529 // If the entity allows NRVO, mark the construction as elidable
4530 // unconditionally.
4531 if (Entity.allowsNRVO())
4532 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4533 Constructor, /*Elidable=*/true,
4534 move_arg(ConstructorArgs),
4535 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004536 ConstructKind,
4537 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004538 else
4539 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004541 move_arg(ConstructorArgs),
4542 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004543 ConstructKind,
4544 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004545 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004546 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004547 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004548
4549 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004550 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004551 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004552 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004553
Douglas Gregor2f599792010-04-02 18:24:57 +00004554 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004555 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004556
Douglas Gregor51c56d62009-12-14 20:49:26 +00004557 break;
4558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004559
Douglas Gregor71d17402009-12-15 00:01:57 +00004560 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004561 step_iterator NextStep = Step;
4562 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004564 NextStep->Kind == SK_ConstructorInitialization) {
4565 // The need for zero-initialization is recorded directly into
4566 // the call to the object's constructor within the next step.
4567 ConstructorInitRequiresZeroInit = true;
4568 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4569 S.getLangOptions().CPlusPlus &&
4570 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004571 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4572 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004574 Kind.getRange().getBegin());
4575
4576 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4577 TSInfo->getType().getNonLValueExprType(S.Context),
4578 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004579 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004580 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004581 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004582 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004583 break;
4584 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004585
4586 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004587 QualType SourceType = CurInit.get()->getType();
4588 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004589 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004590 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4591 if (Result.isInvalid())
4592 return ExprError();
4593 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004594
4595 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004596 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004597 if (ConvTy != Sema::Compatible &&
4598 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004599 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004600 == Sema::Compatible)
4601 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004602 if (CurInitExprRes.isInvalid())
4603 return ExprError();
4604 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004605
Douglas Gregora41a8c52010-04-22 00:20:18 +00004606 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004607 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4608 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004609 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004610 getAssignmentAction(Entity),
4611 &Complained)) {
4612 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004613 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004614 } else if (Complained)
4615 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004616 break;
4617 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004618
4619 case SK_StringInit: {
4620 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004621 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004622 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004623 break;
4624 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004625
4626 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004627 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004628 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004629 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004630 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004631
4632 case SK_ArrayInit:
4633 // Okay: we checked everything before creating this step. Note that
4634 // this is a GNU extension.
4635 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004636 << Step->Type << CurInit.get()->getType()
4637 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004638
4639 // If the destination type is an incomplete array type, update the
4640 // type accordingly.
4641 if (ResultType) {
4642 if (const IncompleteArrayType *IncompleteDest
4643 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4644 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004645 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004646 *ResultType = S.Context.getConstantArrayType(
4647 IncompleteDest->getElementType(),
4648 ConstantSource->getSize(),
4649 ArrayType::Normal, 0);
4650 }
4651 }
4652 }
John McCallf85e1932011-06-15 23:02:42 +00004653 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004654
John McCallf85e1932011-06-15 23:02:42 +00004655 case SK_PassByIndirectCopyRestore:
4656 case SK_PassByIndirectRestore:
4657 checkIndirectCopyRestoreSource(S, CurInit.get());
4658 CurInit = S.Owned(new (S.Context)
4659 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4660 Step->Kind == SK_PassByIndirectCopyRestore));
4661 break;
4662
4663 case SK_ProduceObjCObject:
4664 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004665 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004666 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004667 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004668 }
4669 }
John McCall15d7d122010-11-11 03:21:53 +00004670
4671 // Diagnose non-fatal problems with the completed initialization.
4672 if (Entity.getKind() == InitializedEntity::EK_Member &&
4673 cast<FieldDecl>(Entity.getDecl())->isBitField())
4674 S.CheckBitFieldInitialization(Kind.getLocation(),
4675 cast<FieldDecl>(Entity.getDecl()),
4676 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Douglas Gregor20093b42009-12-09 23:02:17 +00004678 return move(CurInit);
4679}
4680
4681//===----------------------------------------------------------------------===//
4682// Diagnose initialization failures
4683//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004685 const InitializedEntity &Entity,
4686 const InitializationKind &Kind,
4687 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004688 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004689 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690
Douglas Gregord6542d82009-12-22 15:35:07 +00004691 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004692 switch (Failure) {
4693 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004694 // FIXME: Customize for the initialized entity?
4695 if (NumArgs == 0)
4696 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4697 << DestType.getNonReferenceType();
4698 else // FIXME: diagnostic below could be better!
4699 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4700 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004701 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702
Douglas Gregor20093b42009-12-09 23:02:17 +00004703 case FK_ArrayNeedsInitList:
4704 case FK_ArrayNeedsInitListOrStringLiteral:
4705 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4706 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4707 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004709 case FK_ArrayTypeMismatch:
4710 case FK_NonConstantArrayInit:
4711 S.Diag(Kind.getLocation(),
4712 (Failure == FK_ArrayTypeMismatch
4713 ? diag::err_array_init_different_type
4714 : diag::err_array_init_non_constant_array))
4715 << DestType.getNonReferenceType()
4716 << Args[0]->getType()
4717 << Args[0]->getSourceRange();
4718 break;
4719
John McCall6bb80172010-03-30 21:47:33 +00004720 case FK_AddressOfOverloadFailed: {
4721 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004723 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004724 true,
4725 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004726 break;
John McCall6bb80172010-03-30 21:47:33 +00004727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728
Douglas Gregor20093b42009-12-09 23:02:17 +00004729 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004730 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004731 switch (FailedOverloadResult) {
4732 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004733 if (Failure == FK_UserConversionOverloadFailed)
4734 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4735 << Args[0]->getType() << DestType
4736 << Args[0]->getSourceRange();
4737 else
4738 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4739 << DestType << Args[0]->getType()
4740 << Args[0]->getSourceRange();
4741
John McCall120d63c2010-08-24 20:38:10 +00004742 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004743 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744
Douglas Gregor20093b42009-12-09 23:02:17 +00004745 case OR_No_Viable_Function:
4746 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4747 << Args[0]->getType() << DestType.getNonReferenceType()
4748 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004749 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004750 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751
Douglas Gregor20093b42009-12-09 23:02:17 +00004752 case OR_Deleted: {
4753 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4754 << Args[0]->getType() << DestType.getNonReferenceType()
4755 << Args[0]->getSourceRange();
4756 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004757 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004758 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4759 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004760 if (Ovl == OR_Deleted) {
4761 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004762 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004763 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004764 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004765 }
4766 break;
4767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768
Douglas Gregor20093b42009-12-09 23:02:17 +00004769 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004770 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004771 break;
4772 }
4773 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004774
Douglas Gregor20093b42009-12-09 23:02:17 +00004775 case FK_NonConstLValueReferenceBindingToTemporary:
4776 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004777 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004778 Failure == FK_NonConstLValueReferenceBindingToTemporary
4779 ? diag::err_lvalue_reference_bind_to_temporary
4780 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004781 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004782 << DestType.getNonReferenceType()
4783 << Args[0]->getType()
4784 << Args[0]->getSourceRange();
4785 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004786
Douglas Gregor20093b42009-12-09 23:02:17 +00004787 case FK_RValueReferenceBindingToLValue:
4788 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004789 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004790 << Args[0]->getSourceRange();
4791 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004792
Douglas Gregor20093b42009-12-09 23:02:17 +00004793 case FK_ReferenceInitDropsQualifiers:
4794 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4795 << DestType.getNonReferenceType()
4796 << Args[0]->getType()
4797 << Args[0]->getSourceRange();
4798 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004799
Douglas Gregor20093b42009-12-09 23:02:17 +00004800 case FK_ReferenceInitFailed:
4801 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4802 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004803 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004804 << Args[0]->getType()
4805 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004806 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4807 Args[0]->getType()->isObjCObjectPointerType())
4808 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004809 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004810
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004811 case FK_ConversionFailed: {
4812 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004813 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4814 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004815 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004816 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004817 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004818 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004819 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4820 Args[0]->getType()->isObjCObjectPointerType())
4821 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004822 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004823 }
John Wiegley429bb272011-04-08 18:41:53 +00004824
4825 case FK_ConversionFromPropertyFailed:
4826 // No-op. This error has already been reported.
4827 break;
4828
Douglas Gregord87b61f2009-12-10 17:56:55 +00004829 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004830 SourceRange R;
4831
4832 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004833 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004834 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004835 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004836 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004837
Douglas Gregor19311e72010-09-08 21:40:08 +00004838 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4839 if (Kind.isCStyleOrFunctionalCast())
4840 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4841 << R;
4842 else
4843 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4844 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004845 break;
4846 }
4847
4848 case FK_ReferenceBindingToInitList:
4849 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4850 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4851 break;
4852
4853 case FK_InitListBadDestinationType:
4854 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4855 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4856 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
Douglas Gregor51c56d62009-12-14 20:49:26 +00004858 case FK_ConstructorOverloadFailed: {
4859 SourceRange ArgsRange;
4860 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004861 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004862 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004863
Douglas Gregor51c56d62009-12-14 20:49:26 +00004864 // FIXME: Using "DestType" for the entity we're printing is probably
4865 // bad.
4866 switch (FailedOverloadResult) {
4867 case OR_Ambiguous:
4868 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4869 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004870 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4871 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004872 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004873
Douglas Gregor51c56d62009-12-14 20:49:26 +00004874 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004875 if (Kind.getKind() == InitializationKind::IK_Default &&
4876 (Entity.getKind() == InitializedEntity::EK_Base ||
4877 Entity.getKind() == InitializedEntity::EK_Member) &&
4878 isa<CXXConstructorDecl>(S.CurContext)) {
4879 // This is implicit default initialization of a member or
4880 // base within a constructor. If no viable function was
4881 // found, notify the user that she needs to explicitly
4882 // initialize this base/member.
4883 CXXConstructorDecl *Constructor
4884 = cast<CXXConstructorDecl>(S.CurContext);
4885 if (Entity.getKind() == InitializedEntity::EK_Base) {
4886 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4887 << Constructor->isImplicit()
4888 << S.Context.getTypeDeclType(Constructor->getParent())
4889 << /*base=*/0
4890 << Entity.getType();
4891
4892 RecordDecl *BaseDecl
4893 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4894 ->getDecl();
4895 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4896 << S.Context.getTagDeclType(BaseDecl);
4897 } else {
4898 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4899 << Constructor->isImplicit()
4900 << S.Context.getTypeDeclType(Constructor->getParent())
4901 << /*member=*/1
4902 << Entity.getName();
4903 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4904
4905 if (const RecordType *Record
4906 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004907 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004908 diag::note_previous_decl)
4909 << S.Context.getTagDeclType(Record->getDecl());
4910 }
4911 break;
4912 }
4913
Douglas Gregor51c56d62009-12-14 20:49:26 +00004914 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4915 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004916 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004917 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004918
Douglas Gregor51c56d62009-12-14 20:49:26 +00004919 case OR_Deleted: {
4920 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4921 << true << DestType << ArgsRange;
4922 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004923 OverloadingResult Ovl
4924 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004925 if (Ovl == OR_Deleted) {
4926 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004927 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004928 } else {
4929 llvm_unreachable("Inconsistent overload resolution?");
4930 }
4931 break;
4932 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004933
Douglas Gregor51c56d62009-12-14 20:49:26 +00004934 case OR_Success:
4935 llvm_unreachable("Conversion did not fail!");
4936 break;
4937 }
4938 break;
4939 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004940
Douglas Gregor99a2e602009-12-16 01:38:02 +00004941 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004942 if (Entity.getKind() == InitializedEntity::EK_Member &&
4943 isa<CXXConstructorDecl>(S.CurContext)) {
4944 // This is implicit default-initialization of a const member in
4945 // a constructor. Complain that it needs to be explicitly
4946 // initialized.
4947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4948 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4949 << Constructor->isImplicit()
4950 << S.Context.getTypeDeclType(Constructor->getParent())
4951 << /*const=*/1
4952 << Entity.getName();
4953 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4954 << Entity.getName();
4955 } else {
4956 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4957 << DestType << (bool)DestType->getAs<RecordType>();
4958 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004959 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004960
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004961 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004963 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004965 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004966
Douglas Gregora41a8c52010-04-22 00:20:18 +00004967 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004968 return true;
4969}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004970
Chris Lattner5f9e2722011-07-23 10:55:15 +00004971void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004972 switch (SequenceKind) {
4973 case FailedSequence: {
4974 OS << "Failed sequence: ";
4975 switch (Failure) {
4976 case FK_TooManyInitsForReference:
4977 OS << "too many initializers for reference";
4978 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004979
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004980 case FK_ArrayNeedsInitList:
4981 OS << "array requires initializer list";
4982 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004983
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004984 case FK_ArrayNeedsInitListOrStringLiteral:
4985 OS << "array requires initializer list or string literal";
4986 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004987
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004988 case FK_ArrayTypeMismatch:
4989 OS << "array type mismatch";
4990 break;
4991
4992 case FK_NonConstantArrayInit:
4993 OS << "non-constant array initializer";
4994 break;
4995
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004996 case FK_AddressOfOverloadFailed:
4997 OS << "address of overloaded function failed";
4998 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004999
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005000 case FK_ReferenceInitOverloadFailed:
5001 OS << "overload resolution for reference initialization failed";
5002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005004 case FK_NonConstLValueReferenceBindingToTemporary:
5005 OS << "non-const lvalue reference bound to temporary";
5006 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005007
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005008 case FK_NonConstLValueReferenceBindingToUnrelated:
5009 OS << "non-const lvalue reference bound to unrelated type";
5010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005012 case FK_RValueReferenceBindingToLValue:
5013 OS << "rvalue reference bound to an lvalue";
5014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005016 case FK_ReferenceInitDropsQualifiers:
5017 OS << "reference initialization drops qualifiers";
5018 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005020 case FK_ReferenceInitFailed:
5021 OS << "reference initialization failed";
5022 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005023
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005024 case FK_ConversionFailed:
5025 OS << "conversion failed";
5026 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027
John Wiegley429bb272011-04-08 18:41:53 +00005028 case FK_ConversionFromPropertyFailed:
5029 OS << "conversion from property failed";
5030 break;
5031
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005032 case FK_TooManyInitsForScalar:
5033 OS << "too many initializers for scalar";
5034 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005035
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005036 case FK_ReferenceBindingToInitList:
5037 OS << "referencing binding to initializer list";
5038 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005040 case FK_InitListBadDestinationType:
5041 OS << "initializer list for non-aggregate, non-scalar type";
5042 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005043
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005044 case FK_UserConversionOverloadFailed:
5045 OS << "overloading failed for user-defined conversion";
5046 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005047
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005048 case FK_ConstructorOverloadFailed:
5049 OS << "constructor overloading failed";
5050 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005051
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005052 case FK_DefaultInitOfConst:
5053 OS << "default initialization of a const variable";
5054 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005056 case FK_Incomplete:
5057 OS << "initialization of incomplete type";
5058 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005060 OS << '\n';
5061 return;
5062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005064 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005065 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005066 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
Sebastian Redl7491c492011-06-05 13:59:11 +00005068 case NormalSequence:
5069 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005070 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005071 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005072
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005073 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5074 if (S != step_begin()) {
5075 OS << " -> ";
5076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005077
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005078 switch (S->Kind) {
5079 case SK_ResolveAddressOfOverloadedFunction:
5080 OS << "resolve address of overloaded function";
5081 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005083 case SK_CastDerivedToBaseRValue:
5084 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5085 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005086
Sebastian Redl906082e2010-07-20 04:20:21 +00005087 case SK_CastDerivedToBaseXValue:
5088 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5089 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005090
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005091 case SK_CastDerivedToBaseLValue:
5092 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5093 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005095 case SK_BindReference:
5096 OS << "bind reference to lvalue";
5097 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005099 case SK_BindReferenceToTemporary:
5100 OS << "bind reference to a temporary";
5101 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005102
Douglas Gregor523d46a2010-04-18 07:40:54 +00005103 case SK_ExtraneousCopyToTemporary:
5104 OS << "extraneous C++03 copy to temporary";
5105 break;
5106
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005107 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005108 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005109 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005110
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005111 case SK_QualificationConversionRValue:
5112 OS << "qualification conversion (rvalue)";
5113
Sebastian Redl906082e2010-07-20 04:20:21 +00005114 case SK_QualificationConversionXValue:
5115 OS << "qualification conversion (xvalue)";
5116
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005117 case SK_QualificationConversionLValue:
5118 OS << "qualification conversion (lvalue)";
5119 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005120
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005121 case SK_ConversionSequence:
5122 OS << "implicit conversion sequence (";
5123 S->ICS->DebugPrint(); // FIXME: use OS
5124 OS << ")";
5125 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005127 case SK_ListInitialization:
5128 OS << "list initialization";
5129 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005130
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005131 case SK_ConstructorInitialization:
5132 OS << "constructor initialization";
5133 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005135 case SK_ZeroInitialization:
5136 OS << "zero initialization";
5137 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005139 case SK_CAssignment:
5140 OS << "C assignment";
5141 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005143 case SK_StringInit:
5144 OS << "string initialization";
5145 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005146
5147 case SK_ObjCObjectConversion:
5148 OS << "Objective-C object conversion";
5149 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005150
5151 case SK_ArrayInit:
5152 OS << "array initialization";
5153 break;
John McCallf85e1932011-06-15 23:02:42 +00005154
5155 case SK_PassByIndirectCopyRestore:
5156 OS << "pass by indirect copy and restore";
5157 break;
5158
5159 case SK_PassByIndirectRestore:
5160 OS << "pass by indirect restore";
5161 break;
5162
5163 case SK_ProduceObjCObject:
5164 OS << "Objective-C object retension";
5165 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005166 }
5167 }
5168}
5169
5170void InitializationSequence::dump() const {
5171 dump(llvm::errs());
5172}
5173
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005174static void DiagnoseNarrowingInInitList(
5175 Sema& S, QualType EntityType, const Expr *InitE,
5176 bool Constant, const APValue &ConstantValue) {
5177 if (Constant) {
5178 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005179 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005180 ? diag::err_init_list_constant_narrowing
5181 : diag::warn_init_list_constant_narrowing)
5182 << InitE->getSourceRange()
5183 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005184 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005185 } else
5186 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005187 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005188 ? diag::err_init_list_variable_narrowing
5189 : diag::warn_init_list_variable_narrowing)
5190 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005191 << InitE->getType().getLocalUnqualifiedType()
5192 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005193
5194 llvm::SmallString<128> StaticCast;
5195 llvm::raw_svector_ostream OS(StaticCast);
5196 OS << "static_cast<";
5197 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5198 // It's important to use the typedef's name if there is one so that the
5199 // fixit doesn't break code using types like int64_t.
5200 //
5201 // FIXME: This will break if the typedef requires qualification. But
5202 // getQualifiedNameAsString() includes non-machine-parsable components.
5203 OS << TT->getDecl();
5204 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5205 OS << BT->getName(S.getLangOptions());
5206 else {
5207 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5208 // with a broken cast.
5209 return;
5210 }
5211 OS << ">(";
5212 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5213 << InitE->getSourceRange()
5214 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5215 << FixItHint::CreateInsertion(
5216 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5217}
5218
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005219//===----------------------------------------------------------------------===//
5220// Initialization helper functions
5221//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005222bool
5223Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5224 ExprResult Init) {
5225 if (Init.isInvalid())
5226 return false;
5227
5228 Expr *InitE = Init.get();
5229 assert(InitE && "No initialization expression");
5230
5231 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5232 SourceLocation());
5233 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005234 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005235}
5236
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005237ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005238Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5239 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005240 ExprResult Init,
5241 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005242 if (Init.isInvalid())
5243 return ExprError();
5244
John McCall15d7d122010-11-11 03:21:53 +00005245 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005246 assert(InitE && "No initialization expression?");
5247
5248 if (EqualLoc.isInvalid())
5249 EqualLoc = InitE->getLocStart();
5250
5251 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5252 EqualLoc);
5253 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5254 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005255
5256 bool Constant = false;
5257 APValue Result;
5258 if (TopLevelOfInitList &&
5259 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5260 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5261 Constant, Result);
5262 }
John McCallf312b1e2010-08-26 23:41:50 +00005263 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005264}