[clang] [CIR] Refactor global variable emission and initialization (PR #138222)

Andy Kaylor via cfe-commits cfe-commits at lists.llvm.org
Fri May 2 10:14:07 PDT 2025


================
@@ -269,6 +269,40 @@ mlir::Operation *CIRGenModule::getGlobalValue(StringRef name) {
   return mlir::SymbolTable::lookupSymbolIn(theModule, name);
 }
 
+cir::GlobalOp CIRGenModule::createGlobalOp(CIRGenModule &cgm,
+                                           mlir::Location loc, StringRef name,
+                                           mlir::Type t,
+                                           mlir::Operation *insertPoint) {
+  cir::GlobalOp g;
+  CIRGenBuilderTy &builder = cgm.getBuilder();
+
+  {
+    mlir::OpBuilder::InsertionGuard guard(builder);
+
+    // Some global emissions are triggered while emitting a function, e.g.
+    // void s() { const char *s = "yolo"; ... }
+    //
+    // Be sure to insert global before the current function
+    CIRGenFunction *curCGF = cgm.curCGF;
+    if (curCGF)
+      builder.setInsertionPoint(curCGF->curFn);
+
+    g = builder.create<cir::GlobalOp>(loc, name, t);
+    if (!curCGF) {
+      if (insertPoint)
+        cgm.getModule().insert(insertPoint, g);
----------------
andykaylor wrote:

I don't see any place else in the incubator where this happens. It seems this is the wrapper where it happens. Beyond this we're into general MLIR code, but a quick search didn't turn up any place there where this pattern occurred.

Generally, I don't think it matters where the entries get pushed in the list. The one place we are providing an insert point is when we're replacing a previously declared global. I'm not sure it matters there either honestly. but I guess it makes the output easier to read.

https://github.com/llvm/llvm-project/pull/138222


More information about the cfe-commits mailing list