d: Merge upstream dmd ff57fec515, druntime ff57fec515, phobos 17bafda79.
[official-gcc.git] / gcc / d / dmd / dstruct.d
blob36e847c3f883ae18f5503d2de40653026e753721
1 /**
2 * Struct and union declarations.
4 * Specification: $(LINK2 https://dlang.org/spec/struct.html, Structs, Unions)
6 * Copyright: Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dstruct.d, _dstruct.d)
10 * Documentation: https://dlang.org/phobos/dmd_dstruct.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dstruct.d
14 module dmd.dstruct;
16 import core.stdc.stdio;
18 import dmd.aggregate;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.attrib;
22 import dmd.declaration;
23 import dmd.dmodule;
24 import dmd.dscope;
25 import dmd.dsymbol;
26 import dmd.dsymbolsem;
27 import dmd.dtemplate;
28 import dmd.errors;
29 import dmd.expression;
30 import dmd.func;
31 import dmd.globals;
32 import dmd.id;
33 import dmd.identifier;
34 import dmd.location;
35 import dmd.mtype;
36 import dmd.opover;
37 import dmd.target;
38 import dmd.tokens;
39 import dmd.typesem;
40 import dmd.typinf;
41 import dmd.visitor;
43 /***************************************
44 * Search sd for a member function of the form:
45 * `extern (D) string toString();`
46 * Params:
47 * sd = struct declaration to search
48 * Returns:
49 * FuncDeclaration of `toString()` if found, `null` if not
51 extern (C++) FuncDeclaration search_toString(StructDeclaration sd)
53 Dsymbol s = search_function(sd, Id.tostring);
54 FuncDeclaration fd = s ? s.isFuncDeclaration() : null;
55 if (fd)
57 __gshared TypeFunction tftostring;
58 if (!tftostring)
60 tftostring = new TypeFunction(ParameterList(), Type.tstring, LINK.d);
61 tftostring = tftostring.merge().toTypeFunction();
63 fd = fd.overloadExactMatch(tftostring);
65 return fd;
68 /***************************************
69 * Request additional semantic analysis for TypeInfo generation.
70 * Params:
71 * sc = context
72 * t = type that TypeInfo is being generated for
74 extern (D) void semanticTypeInfo(Scope* sc, Type t)
76 if (sc)
78 if (sc.intypeof)
79 return;
80 if (!sc.needsCodegen())
81 return;
84 if (!t)
85 return;
87 void visitVector(TypeVector t)
89 semanticTypeInfo(sc, t.basetype);
92 void visitAArray(TypeAArray t)
94 semanticTypeInfo(sc, t.index);
95 semanticTypeInfo(sc, t.next);
98 void visitStruct(TypeStruct t)
100 //printf("semanticTypeInfo.visit(TypeStruct = %s)\n", t.toChars());
101 StructDeclaration sd = t.sym;
103 /* Step 1: create TypeInfoDeclaration
105 if (!sc) // inline may request TypeInfo.
107 Scope scx;
108 scx.eSink = global.errorSink;
109 scx._module = sd.getModule();
110 getTypeInfoType(sd.loc, t, &scx);
111 sd.requestTypeInfo = true;
113 else if (!sc.minst)
115 // don't yet have to generate TypeInfo instance if
116 // the typeid(T) expression exists in speculative scope.
118 else
120 getTypeInfoType(sd.loc, t, sc);
121 sd.requestTypeInfo = true;
123 // https://issues.dlang.org/show_bug.cgi?id=15149
124 // if the typeid operand type comes from a
125 // result of auto function, it may be yet speculative.
126 // unSpeculative(sc, sd);
129 /* Step 2: If the TypeInfo generation requires sd.semantic3, run it later.
130 * This should be done even if typeid(T) exists in speculative scope.
131 * Because it may appear later in non-speculative scope.
133 if (!sd.members)
134 return; // opaque struct
135 if (!sd.xeq && !sd.xcmp && !sd.postblit && !sd.tidtor && !sd.xhash && !search_toString(sd))
136 return; // none of TypeInfo-specific members
138 // If the struct is in a non-root module, run semantic3 to get
139 // correct symbols for the member function.
140 if (sd.semanticRun >= PASS.semantic3)
142 // semantic3 is already done
144 else if (TemplateInstance ti = sd.isInstantiated())
146 if (ti.minst && !ti.minst.isRoot())
147 Module.addDeferredSemantic3(sd);
149 else
151 if (sd.inNonRoot())
153 //printf("deferred sem3 for TypeInfo - sd = %s, inNonRoot = %d\n", sd.toChars(), sd.inNonRoot());
154 Module.addDeferredSemantic3(sd);
159 void visitTuple(TypeTuple t)
161 if (t.arguments)
163 foreach (arg; *t.arguments)
165 semanticTypeInfo(sc, arg.type);
170 /* Note structural similarity of this Type walker to that in isSpeculativeType()
173 Type tb = t.toBasetype();
174 switch (tb.ty)
176 case Tvector: visitVector(tb.isTypeVector()); break;
177 case Taarray: visitAArray(tb.isTypeAArray()); break;
178 case Tstruct: visitStruct(tb.isTypeStruct()); break;
179 case Ttuple: visitTuple (tb.isTypeTuple()); break;
181 case Tclass:
182 case Tenum: break;
184 default: semanticTypeInfo(sc, tb.nextOf()); break;
188 enum StructFlags : int
190 none = 0x0,
191 hasPointers = 0x1, // NB: should use noPointers as in ClassFlags
194 /***********************************************************
195 * All `struct` declarations are an instance of this.
197 extern (C++) class StructDeclaration : AggregateDeclaration
199 FuncDeclarations postblits; // Array of postblit functions
200 FuncDeclaration postblit; // aggregate postblit
202 FuncDeclaration xeq; // TypeInfo_Struct.xopEquals
203 FuncDeclaration xcmp; // TypeInfo_Struct.xopCmp
204 FuncDeclaration xhash; // TypeInfo_Struct.xtoHash
205 extern (C++) __gshared FuncDeclaration xerreq; // object.xopEquals
206 extern (C++) __gshared FuncDeclaration xerrcmp; // object.xopCmp
208 // ABI-specific type(s) if the struct can be passed in registers
209 TypeTuple argTypes;
211 structalign_t alignment; // alignment applied outside of the struct
212 ThreeState ispod; // if struct is POD
214 // `bool` fields that are compacted into bit fields in a string mixin
215 private extern (D) static struct BitFields
217 bool zeroInit; // !=0 if initialize with 0 fill
218 bool hasIdentityAssign; // true if has identity opAssign
219 bool hasBlitAssign; // true if opAssign is a blit
220 bool hasIdentityEquals; // true if has identity opEquals
221 bool hasNoFields; // has no fields
222 bool hasCopyCtor; // copy constructor
223 bool hasPointerField; // members with indirections
224 bool hasVoidInitPointers; // void-initialized unsafe fields
225 bool hasSystemFields; // @system members
226 bool hasFieldWithInvariant; // invariants
227 bool computedTypeProperties;// the above 3 fields are computed
228 // Even if struct is defined as non-root symbol, some built-in operations
229 // (e.g. TypeidExp, NewExp, ArrayLiteralExp, etc) request its TypeInfo.
230 // For those, today TypeInfo_Struct is generated in COMDAT.
231 bool requestTypeInfo;
234 import dmd.common.bitfields : generateBitFields;
235 mixin(generateBitFields!(BitFields, ushort));
237 extern (D) this(const ref Loc loc, Identifier id, bool inObject)
239 super(loc, id);
240 zeroInit = false; // assume false until we do semantic processing
241 ispod = ThreeState.none;
242 // For forward references
243 type = new TypeStruct(this);
245 if (inObject)
247 if (id == Id.ModuleInfo && !Module.moduleinfo)
248 Module.moduleinfo = this;
252 static StructDeclaration create(const ref Loc loc, Identifier id, bool inObject)
254 return new StructDeclaration(loc, id, inObject);
257 override StructDeclaration syntaxCopy(Dsymbol s)
259 StructDeclaration sd =
260 s ? cast(StructDeclaration)s
261 : new StructDeclaration(loc, ident, false);
262 ScopeDsymbol.syntaxCopy(sd);
263 return sd;
266 override const(char)* kind() const
268 return "struct";
271 override final void finalizeSize()
273 //printf("StructDeclaration::finalizeSize() %s, sizeok = %d\n", toChars(), sizeok);
274 assert(sizeok != Sizeok.done);
276 if (sizeok == Sizeok.inProcess)
278 return;
280 sizeok = Sizeok.inProcess;
282 //printf("+StructDeclaration::finalizeSize() %s, fields.length = %d, sizeok = %d\n", toChars(), fields.length, sizeok);
284 fields.setDim(0); // workaround
286 // Set the offsets of the fields and determine the size of the struct
287 FieldState fieldState;
288 bool isunion = isUnionDeclaration() !is null;
289 for (size_t i = 0; i < members.length; i++)
291 Dsymbol s = (*members)[i];
292 s.setFieldOffset(this, fieldState, isunion);
294 if (type.ty == Terror)
296 errors = true;
297 return;
300 if (structsize == 0)
302 hasNoFields = true;
303 alignsize = 1;
305 // A fine mess of what size a zero sized struct should be
306 final switch (classKind)
308 case ClassKind.d:
309 case ClassKind.cpp:
310 structsize = 1;
311 break;
313 case ClassKind.c:
314 case ClassKind.objc:
315 if (target.c.bitFieldStyle == TargetC.BitFieldStyle.MS)
317 /* Undocumented MS behavior for:
318 * struct S { int :0; };
320 structsize = 4;
322 else if (target.c.bitFieldStyle == TargetC.BitFieldStyle.DM)
324 structsize = 0;
325 alignsize = 0;
327 else
328 structsize = 0;
329 break;
333 // Round struct size up to next alignsize boundary.
334 // This will ensure that arrays of structs will get their internals
335 // aligned properly.
336 if (alignment.isDefault() || alignment.isPack())
337 structsize = (structsize + alignsize - 1) & ~(alignsize - 1);
338 else
339 structsize = (structsize + alignment.get() - 1) & ~(alignment.get() - 1);
341 sizeok = Sizeok.done;
343 //printf("-StructDeclaration::finalizeSize() %s, fields.length = %d, structsize = %d\n", toChars(), cast(int)fields.length, cast(int)structsize);
345 if (errors)
346 return;
348 // Calculate fields[i].overlapped
349 if (checkOverlappedFields())
351 errors = true;
352 return;
355 // Determine if struct is all zeros or not
356 zeroInit = true;
357 foreach (vd; fields)
359 if (vd._init)
361 if (vd._init.isVoidInitializer())
362 /* Treat as 0 for the purposes of putting the initializer
363 * in the BSS segment, or doing a mass set to 0
365 continue;
367 // Zero size fields are zero initialized
368 if (vd.type.size(vd.loc) == 0)
369 continue;
371 // Examine init to see if it is all 0s.
372 auto exp = vd.getConstInitializer();
373 if (!exp || !_isZeroInit(exp))
375 zeroInit = false;
376 break;
379 else if (!vd.type.isZeroInit(loc))
381 zeroInit = false;
382 break;
387 argTypes = target.toArgTypes(type);
390 /// Compute cached type properties for `TypeStruct`
391 extern(D) final void determineTypeProperties()
393 if (computedTypeProperties)
394 return;
395 foreach (vd; fields)
397 if (vd.storage_class & STC.ref_ || vd.hasPointers())
398 hasPointerField = true;
400 if (vd._init && vd._init.isVoidInitializer() && vd.type.hasPointers())
401 hasVoidInitPointers = true;
403 if (vd.storage_class & STC.system || vd.type.hasSystemFields())
404 hasSystemFields = true;
406 if (!vd._init && vd.type.hasVoidInitPointers())
407 hasVoidInitPointers = true;
409 if (vd.type.hasInvariant())
410 hasFieldWithInvariant = true;
412 computedTypeProperties = true;
415 /***************************************
416 * Determine if struct is POD (Plain Old Data).
418 * POD is defined as:
419 * $(OL
420 * $(LI not nested)
421 * $(LI no postblits, destructors, or assignment operators)
422 * $(LI no `ref` fields or fields that are themselves non-POD)
424 * The idea being these are compatible with C structs.
426 * Returns:
427 * true if struct is POD
429 final bool isPOD()
431 // If we've already determined whether this struct is POD.
432 if (ispod != ThreeState.none)
433 return (ispod == ThreeState.yes);
435 ispod = ThreeState.yes;
437 if (enclosing || postblit || dtor || hasCopyCtor)
439 ispod = ThreeState.no;
440 return false;
443 // Recursively check all fields are POD.
444 for (size_t i = 0; i < fields.length; i++)
446 VarDeclaration v = fields[i];
447 if (v.storage_class & STC.ref_)
449 ispod = ThreeState.no;
450 return false;
453 Type tv = v.type.baseElemOf();
454 if (tv.ty == Tstruct)
456 TypeStruct ts = cast(TypeStruct)tv;
457 StructDeclaration sd = ts.sym;
458 if (!sd.isPOD())
460 ispod = ThreeState.no;
461 return false;
466 return (ispod == ThreeState.yes);
469 /***************************************
470 * Determine if struct has copy construction (copy constructor or postblit)
471 * Returns:
472 * true if struct has copy construction
474 final bool hasCopyConstruction()
476 return postblit || hasCopyCtor;
479 override final inout(StructDeclaration) isStructDeclaration() inout @nogc nothrow pure @safe
481 return this;
484 override void accept(Visitor v)
486 v.visit(this);
489 final uint numArgTypes() const
491 return argTypes && argTypes.arguments ? cast(uint) argTypes.arguments.length : 0;
494 final Type argType(uint index)
496 return index < numArgTypes() ? (*argTypes.arguments)[index].type : null;
500 /***************************************
501 * Verifies whether the struct declaration has a
502 * constructor that is not a copy constructor.
503 * Optionally, it can check whether the struct
504 * declaration has a regular constructor, that
505 * is not disabled.
507 * Params:
508 * checkDisabled = if the struct has a regular
509 non-disabled constructor
510 * Returns:
511 * true, if the struct has a regular (optionally,
512 * not disabled) constructor, false otherwise.
514 final bool hasRegularCtor(bool checkDisabled = false)
516 if (!ctor)
517 return false;
519 bool result;
520 overloadApply(ctor, (Dsymbol s)
522 if (auto td = s.isTemplateDeclaration())
524 if (checkDisabled && td.onemember)
526 if (auto ctorDecl = td.onemember.isCtorDeclaration())
528 if (ctorDecl.storage_class & STC.disable)
529 return 0;
532 result = true;
533 return 1;
535 if (auto ctorDecl = s.isCtorDeclaration())
537 if (!ctorDecl.isCpCtor && (!checkDisabled || !(ctorDecl.storage_class & STC.disable)))
539 result = true;
540 return 1;
543 return 0;
545 return result;
549 /**********************************
550 * Determine if exp is all binary zeros.
551 * Params:
552 * exp = expression to check
553 * Returns:
554 * true if it's all binary 0
556 bool _isZeroInit(Expression exp)
558 switch (exp.op)
560 case EXP.int64:
561 return exp.toInteger() == 0;
563 case EXP.null_:
564 return true;
566 case EXP.structLiteral:
568 auto sle = exp.isStructLiteralExp();
569 if (sle.sd.isNested())
570 return false;
571 const isCstruct = sle.sd.isCsymbol(); // C structs are default initialized to all zeros
572 foreach (i; 0 .. sle.sd.fields.length)
574 auto field = sle.sd.fields[i];
575 if (field.type.size(field.loc))
577 auto e = sle.elements && i < sle.elements.length ? (*sle.elements)[i] : null;
578 if (e ? !_isZeroInit(e)
579 : !isCstruct && !field.type.isZeroInit(field.loc))
580 return false;
583 return true;
586 case EXP.arrayLiteral:
588 auto ale = cast(ArrayLiteralExp)exp;
590 const dim = ale.elements ? ale.elements.length : 0;
592 if (ale.type.toBasetype().ty == Tarray) // if initializing a dynamic array
593 return dim == 0;
595 foreach (i; 0 .. dim)
597 if (!_isZeroInit(ale[i]))
598 return false;
601 /* Note that true is returned for all T[0]
603 return true;
606 case EXP.string_:
608 StringExp se = cast(StringExp)exp;
610 if (se.type.toBasetype().ty == Tarray) // if initializing a dynamic array
611 return se.len == 0;
613 foreach (i; 0 .. se.len)
615 if (se.getCodeUnit(i))
616 return false;
618 return true;
621 case EXP.vector:
623 auto ve = cast(VectorExp) exp;
624 return _isZeroInit(ve.e1);
627 case EXP.float64:
628 case EXP.complex80:
630 import dmd.root.ctfloat : CTFloat;
631 return (exp.toReal() is CTFloat.zero) &&
632 (exp.toImaginary() is CTFloat.zero);
635 default:
636 return false;
640 /***********************************************************
641 * Unions are a variation on structs.
643 extern (C++) final class UnionDeclaration : StructDeclaration
645 extern (D) this(const ref Loc loc, Identifier id)
647 super(loc, id, false);
650 override UnionDeclaration syntaxCopy(Dsymbol s)
652 assert(!s);
653 auto ud = new UnionDeclaration(loc, ident);
654 StructDeclaration.syntaxCopy(ud);
655 return ud;
658 override const(char)* kind() const
660 return "union";
663 override inout(UnionDeclaration) isUnionDeclaration() inout
665 return this;
668 override void accept(Visitor v)
670 v.visit(this);