Debian Codegraph @

gcc/d/dmd/nogc.d

raw
1 /**
2 * Checks that a function marked `@nogc` does not invoke the Garbage Collector.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/function.html#nogc-functions, No-GC Functions)
5 *
6 * Copyright: Copyright (C) 1999-2025 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/compiler/src/dmd/nogc.d, _nogc.d)
10 * Documentation: https://dlang.org/phobos/dmd_nogc.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/nogc.d
12 */
13
14 module dmd.nogc;
15
16 import core.stdc.stdio;
17
18 import dmd.aggregate;
19 import dmd.astenums;
20 import dmd.declaration;
21 import dmd.common.outbuffer;
22 import dmd.dmodule;
23 import dmd.dscope;
24 import dmd.dtemplate : isDsymbol;
25 import dmd.dsymbol : PASS;
26 import dmd.errors;
27 import dmd.expression;
28 import dmd.func;
29 import dmd.globals;
30 import dmd.init;
31 import dmd.location;
32 import dmd.mtype;
33 import dmd.rootobject : RootObject, DYNCAST;
34 import dmd.semantic2;
35 import dmd.semantic3;
36 import dmd.tokens;
37 import dmd.visitor;
38 import dmd.visitor.postorder;
39
40 /**************************************
41 * Look for GC-allocations
42 */
43 extern (C++) final class NOGCVisitor : StoppableVisitor
44 {
45 alias visit = typeof(super).visit;
46 public:
47 FuncDeclaration f;
48 bool checkOnly; // don't print errors
49 bool err;
50 bool nogcExceptions; // -preview=dip1008 enabled
51
52 extern (D) this(FuncDeclaration f) scope @safe
53 {
54 this.f = f;
55 }
56
57 void doCond(Expression exp)
58 {
59 if (exp)
60 walkPostorder(exp, this);
61 }
62
63 override void visit(Expression e)
64 {
65 }
66
67 override void visit(DeclarationExp e)
68 {
69 // Note that, walkPostorder does not support DeclarationExp today.
70 VarDeclaration v = e.declaration.isVarDeclaration();
71 if (v && !(v.storage_class & STC.manifest) && !v.isDataseg() && v._init)
72 {
73 if (ExpInitializer ei = v._init.isExpInitializer())
74 {
75 doCond(ei.exp);
76 }
77 }
78 }
79
80 /**
81 * Register that expression `e` requires the GC
82 * Params:
83 * e = expression that uses GC
84 * msg = error message when `e` is used in a `@nogc` function.
85 * Returns: `true` if `err` was set, `false` if it's not in a `@nogc` and not checkonly (-betterC)
86 */
87 private bool setGC(Expression e, const(char)* msg)
88 {
89 if (checkOnly)
90 {
91 err = true;
92 return true;
93 }
94 if (f.setGC(e.loc, msg))
95 {
96 error(e.loc, "%s causes a GC allocation in `@nogc` %s `%s`", msg, f.kind(), f.toChars());
97 err = true;
98 return true;
99 }
100 return false;
101 }
102
103 override void visit(CallExp e)
104 {
105 import dmd.id : Id;
106 import core.stdc.stdio : printf;
107 if (!e.f)
108 return;
109
110 // Treat lowered hook calls as their original expressions.
111 auto fd = stripHookTraceImpl(e.f);
112 if (fd.ident == Id._d_arraysetlengthT)
113 {
114 if (setGC(e, "setting this array's `length`"))
115 return;
116 f.printGCUsage(e.loc, "setting `length` may cause a GC allocation");
117 }
118 }
119
120 override void visit(ArrayLiteralExp e)
121 {
122 if (e.type.ty != Tarray || !e.elements || !e.elements.length || e.onstack)
123 return;
124 if (setGC(e, "this array literal"))
125 return;
126 f.printGCUsage(e.loc, "array literal may cause a GC allocation");
127 }
128
129 override void visit(AssocArrayLiteralExp e)
130 {
131 if (!e.keys.length)
132 return;
133 if (setGC(e, "this associative array literal"))
134 return;
135 f.printGCUsage(e.loc, "associative array literal may cause a GC allocation");
136 }
137
138 override void visit(NewExp e)
139 {
140 if (e.placement)
141 return; // placement new doesn't use the GC
142 if (e.member && !e.member.isNogc() && f.setGC(e.loc, null))
143 {
144 // @nogc-ness is already checked in NewExp::semantic
145 return;
146 }
147 if (e.onstack)
148 return;
149 if (nogcExceptions && e.thrownew)
150 return; // separate allocator is called for this, not the GC
151
152 if (setGC(e, "allocating with `new`"))
153 return;
154 f.printGCUsage(e.loc, "`new` causes a GC allocation");
155 }
156
157 override void visit(DeleteExp e)
158 {
159 if (VarExp ve = e.e1.isVarExp())
160 {
161 VarDeclaration v = ve.var.isVarDeclaration();
162 if (v && v.onstack)
163 return; // delete for scope allocated class object
164 }
165
166 // Semantic should have already handled this case.
167 assert(0);
168 }
169
170 override void visit(IndexExp e)
171 {
172 Type t1b = e.e1.type.toBasetype();
173 if (e.modifiable && t1b.ty == Taarray)
174 {
175 if (setGC(e, "assigning this associative array element"))
176 return;
177 f.printGCUsage(e.loc, "assigning an associative array element may cause a GC allocation");
178 }
179 }
180
181 override void visit(AssignExp e)
182 {
183 if (e.e1.op == EXP.arrayLength)
184 {
185 if (setGC(e, "setting this array's `length`"))
186 return;
187 f.printGCUsage(e.loc, "setting `length` may cause a GC allocation");
188 }
189 }
190
191 override void visit(CatAssignExp e)
192 {
193 if (checkOnly)
194 {
195 err = true;
196 return;
197 }
198 if (setGC(e, "appending to this array with operator `~=`"))
199 return;
200 f.printGCUsage(e.loc, "operator `~=` may cause a GC allocation");
201 }
202
203 override void visit(CatExp e)
204 {
205 if (setGC(e, "concatenating with operator `~`"))
206 return;
207 f.printGCUsage(e.loc, "operator `~` may cause a GC allocation");
208 }
209 }
210
211 Expression checkGC(Scope* sc, Expression e)
212 {
213 if (sc.ctfeBlock) // ignore GC in ctfe blocks
214 return e;
215
216 /* If betterC, allow GC to happen in non-CTFE code.
217 * Just don't generate code for it.
218 * Detect non-CTFE use of the GC in betterC code.
219 */
220 const betterC = !global.params.useGC;
221 FuncDeclaration f = sc.func;
222 if (e && e.op != EXP.error && f && sc.intypeof != 1 &&
223 (!sc.ctfe || betterC) &&
224 (f.type.ty == Tfunction &&
225 (cast(TypeFunction)f.type).isNogc || f.nogcInprocess || global.params.v.gc) &&
226 !sc.debug_)
227 {
228 scope NOGCVisitor gcv = new NOGCVisitor(f);
229 gcv.checkOnly = betterC;
230 gcv.nogcExceptions = sc.previews.dip1008;
231 walkPostorder(e, gcv);
232 if (gcv.err)
233 {
234 if (betterC)
235 {
236 /* Allow ctfe to use the gc code, but don't let it into the runtime
237 */
238 f.skipCodegen = true;
239 }
240 else
241 return ErrorExp.get();
242 }
243 }
244 return e;
245 }
246
247 extern (D) void printGCUsage(FuncDeclaration fd, Loc loc, const(char)* warn)
248 {
249 if (!global.params.v.gc)
250 return;
251
252 Module m = fd.getModule();
253 if (m && m.isRoot() && !fd.inUnittest())
254 {
255 message(loc, "vgc: %s", warn);
256 }
257 }
258
259 /**
260 * Removes `_d_HookTraceImpl` if found from `fd`.
261 * This is needed to be able to find hooks that are called though the hook's `*Trace` wrapper.
262 * Parameters:
263 * fd = The function declaration to remove `_d_HookTraceImpl` from
264 */
265 private FuncDeclaration stripHookTraceImpl(FuncDeclaration fd)
266 {
267 import dmd.id : Id;
268 import dmd.dsymbol : Dsymbol;
269
270 if (fd.ident != Id._d_HookTraceImpl)
271 return fd;
272
273 // Get the Hook from the second template parameter
274 auto templateInstance = fd.parent.isTemplateInstance;
275 RootObject hook = (*templateInstance.tiargs)[1];
276 Dsymbol s = hook.isDsymbol();
277 assert(s, "Expected _d_HookTraceImpl's second template parameter to be an alias to the hook!");
278 return s.isFuncDeclaration;
279 }
280
281 /**************************************
282 * The function is doing something that may allocate with the GC,
283 * so mark it as not nogc (not no-how).
284 *
285 * Params:
286 * fd = function
287 * loc = location of GC action
288 * fmt = format string for error message. Must include "%s `%s`" for the function kind and name.
289 * args = arguments to format string
290 *
291 * Returns:
292 * true if function is marked as @nogc, meaning a user error occurred
293 */
294 extern (D) bool setGC(FuncDeclaration fd, Loc loc, const(char)* fmt, RootObject[] args...)
295 {
296 //printf("setGC() %s\n", toChars());
297 if (fd.nogcInprocess && fd.semanticRun < PASS.semantic3 && fd._scope)
298 {
299 fd.semantic2(fd._scope);
300 fd.semantic3(fd._scope);
301 }
302
303 if (fd.nogcInprocess)
304 {
305 fd.nogcInprocess = false;
306 if (fmt)
307 fd.nogcViolation = new AttributeViolation(loc, fmt, args); // action that requires GC
308 else if (args.length > 0)
309 {
310 if (auto sa = args[0].isDsymbol())
311 {
312 if (FuncDeclaration fd2 = sa.isFuncDeclaration())
313 {
314 fd.nogcViolation = new AttributeViolation(loc, fd2); // call to non-@nogc function
315 }
316 }
317 }
318
319 fd.type.toTypeFunction().isNogc = false;
320 if (fd.fes)
321 fd.fes.func.setGC(Loc.init, null, null);
322 }
323 else if (fd.isNogc())
324 return true;
325 return false;
326 }
327
328 /**************************************
329 * The function calls non-`@nogc` function f, mark it as not nogc.
330 * Params:
331 * fd = function doin the call
332 * f = function being called
333 * Returns:
334 * true if function is marked as @nogc, meaning a user error occurred
335 */
336 extern (D) bool setGCCall(FuncDeclaration fd, FuncDeclaration f)
337 {
338 return fd.setGC(fd.loc, null, f);
339 }
340
341 bool isNogc(FuncDeclaration fd)
342 {
343 //printf("isNogc() %s, inprocess: %d\n", toChars(), !!(flags & FUNCFLAG.nogcInprocess));
344 if (fd.nogcInprocess)
345 fd.setGC(fd.loc, null);
346 return fd.type.toTypeFunction().isNogc;
347 }
348
349 extern (D) bool isNogcBypassingInference(FuncDeclaration fd)
350 {
351 return !fd.nogcInprocess && fd.isNogc();
352 }