Skip to content

Commit db22909

Browse files
authored
[CIR] Upstream support for cir.get_global (#135095)
This adds basic support for referencing global variables from within functions via the cir.get_global operation.
1 parent 36acaa0 commit db22909

File tree

9 files changed

+288
-2
lines changed

9 files changed

+288
-2
lines changed

clang/include/clang/CIR/Dialect/IR/CIROps.td

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1279,6 +1279,37 @@ def GlobalOp : CIR_Op<"global"> {
12791279
let hasVerifier = 1;
12801280
}
12811281

1282+
//===----------------------------------------------------------------------===//
1283+
// GetGlobalOp
1284+
//===----------------------------------------------------------------------===//
1285+
1286+
def GetGlobalOp : CIR_Op<"get_global",
1287+
[Pure, DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
1288+
let summary = "Get the address of a global variable";
1289+
let description = [{
1290+
The `cir.get_global` operation retrieves the address pointing to a
1291+
named global variable. If the global variable is marked constant, writing
1292+
to the resulting address (such as through a `cir.store` operation) is
1293+
undefined. The resulting type must always be a `!cir.ptr<...>` type with the
1294+
same address space as the global variable.
1295+
1296+
Example:
1297+
```mlir
1298+
%x = cir.get_global @gv : !cir.ptr<i32>
1299+
```
1300+
}];
1301+
1302+
let arguments = (ins FlatSymbolRefAttr:$name);
1303+
let results = (outs Res<CIR_PointerType, "", []>:$addr);
1304+
1305+
let assemblyFormat = [{
1306+
$name `:` qualified(type($addr)) attr-dict
1307+
}];
1308+
1309+
// `GetGlobalOp` is fully verified by its traits.
1310+
let hasVerifier = 0;
1311+
}
1312+
12821313
//===----------------------------------------------------------------------===//
12831314
// FuncOp
12841315
//===----------------------------------------------------------------------===//

clang/include/clang/CIR/MissingFeatures.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ struct MissingFeatures {
3535
static bool opGlobalThreadLocal() { return false; }
3636
static bool opGlobalConstant() { return false; }
3737
static bool opGlobalAlignment() { return false; }
38+
static bool opGlobalWeakRef() { return false; }
3839

3940
static bool supportIFuncAttr() { return false; }
4041
static bool supportVisibility() { return false; }
@@ -136,6 +137,10 @@ struct MissingFeatures {
136137
static bool objCGC() { return false; }
137138
static bool weakRefReference() { return false; }
138139
static bool hip() { return false; }
140+
static bool setObjCGCLValueClass() { return false; }
141+
static bool mangledNames() { return false; }
142+
static bool setDLLStorageClass() { return false; }
143+
static bool openMP() { return false; }
139144

140145
// Missing types
141146
static bool dataMemberType() { return false; }

clang/lib/CIR/CodeGen/CIRGenExpr.cpp

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,43 @@ void CIRGenFunction::emitStoreThroughLValue(RValue src, LValue dst,
183183
emitStoreOfScalar(src.getScalarVal(), dst, isInit);
184184
}
185185

186+
static LValue emitGlobalVarDeclLValue(CIRGenFunction &cgf, const Expr *e,
187+
const VarDecl *vd) {
188+
QualType T = e->getType();
189+
190+
// If it's thread_local, emit a call to its wrapper function instead.
191+
assert(!cir::MissingFeatures::opGlobalThreadLocal());
192+
if (vd->getTLSKind() == VarDecl::TLS_Dynamic)
193+
cgf.cgm.errorNYI(e->getSourceRange(),
194+
"emitGlobalVarDeclLValue: thread_local variable");
195+
196+
// Check if the variable is marked as declare target with link clause in
197+
// device codegen.
198+
if (cgf.getLangOpts().OpenMP)
199+
cgf.cgm.errorNYI(e->getSourceRange(), "emitGlobalVarDeclLValue: OpenMP");
200+
201+
// Traditional LLVM codegen handles thread local separately, CIR handles
202+
// as part of getAddrOfGlobalVar.
203+
mlir::Value v = cgf.cgm.getAddrOfGlobalVar(vd);
204+
205+
assert(!cir::MissingFeatures::addressSpace());
206+
mlir::Type realVarTy = cgf.convertTypeForMem(vd->getType());
207+
cir::PointerType realPtrTy = cgf.getBuilder().getPointerTo(realVarTy);
208+
if (realPtrTy != v.getType())
209+
v = cgf.getBuilder().createBitcast(v.getLoc(), v, realPtrTy);
210+
211+
CharUnits alignment = cgf.getContext().getDeclAlign(vd);
212+
Address addr(v, realVarTy, alignment);
213+
LValue lv;
214+
if (vd->getType()->isReferenceType())
215+
cgf.cgm.errorNYI(e->getSourceRange(),
216+
"emitGlobalVarDeclLValue: reference type");
217+
else
218+
lv = cgf.makeAddrLValue(addr, T, AlignmentSource::Decl);
219+
assert(!cir::MissingFeatures::setObjCGCLValueClass());
220+
return lv;
221+
}
222+
186223
void CIRGenFunction::emitStoreOfScalar(mlir::Value value, Address addr,
187224
bool isVolatile, QualType ty,
188225
bool isInit, bool isNontemporal) {
@@ -288,7 +325,7 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr *e) {
288325

289326
// Check if this is a global variable
290327
if (vd->hasLinkage() || vd->isStaticDataMember())
291-
cgm.errorNYI(vd->getSourceRange(), "emitDeclRefLValue: global variable");
328+
return emitGlobalVarDeclLValue(*this, e, vd);
292329

293330
Address addr = Address::invalid();
294331

@@ -299,7 +336,7 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr *e) {
299336
} else {
300337
// Otherwise, it might be static local we haven't emitted yet for some
301338
// reason; most likely, because it's in an outer function.
302-
cgm.errorNYI(vd->getSourceRange(), "emitDeclRefLValue: static local");
339+
cgm.errorNYI(e->getSourceRange(), "emitDeclRefLValue: static local");
303340
}
304341

305342
return makeAddrLValue(addr, ty, AlignmentSource::Type);

clang/lib/CIR/CodeGen/CIRGenModule.cpp

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,102 @@ void CIRGenModule::emitGlobalFunctionDefinition(clang::GlobalDecl gd,
202202
curCGF = nullptr;
203203
}
204204

205+
mlir::Operation *CIRGenModule::getGlobalValue(StringRef name) {
206+
return mlir::SymbolTable::lookupSymbolIn(theModule, name);
207+
}
208+
209+
/// If the specified mangled name is not in the module,
210+
/// create and return an mlir GlobalOp with the specified type (TODO(cir):
211+
/// address space).
212+
///
213+
/// TODO(cir):
214+
/// 1. If there is something in the module with the specified name, return
215+
/// it potentially bitcasted to the right type.
216+
///
217+
/// 2. If \p d is non-null, it specifies a decl that correspond to this. This
218+
/// is used to set the attributes on the global when it is first created.
219+
///
220+
/// 3. If \p isForDefinition is true, it is guaranteed that an actual global
221+
/// with type \p ty will be returned, not conversion of a variable with the same
222+
/// mangled name but some other type.
223+
cir::GlobalOp
224+
CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
225+
LangAS langAS, const VarDecl *d,
226+
ForDefinition_t isForDefinition) {
227+
// Lookup the entry, lazily creating it if necessary.
228+
cir::GlobalOp entry;
229+
if (mlir::Operation *v = getGlobalValue(mangledName)) {
230+
if (!isa<cir::GlobalOp>(v))
231+
errorNYI(d->getSourceRange(), "global with non-GlobalOp type");
232+
entry = cast<cir::GlobalOp>(v);
233+
}
234+
235+
if (entry) {
236+
assert(!cir::MissingFeatures::addressSpace());
237+
assert(!cir::MissingFeatures::opGlobalWeakRef());
238+
239+
assert(!cir::MissingFeatures::setDLLStorageClass());
240+
assert(!cir::MissingFeatures::openMP());
241+
242+
if (entry.getSymType() == ty)
243+
return entry;
244+
245+
// If there are two attempts to define the same mangled name, issue an
246+
// error.
247+
//
248+
// TODO(cir): look at mlir::GlobalValue::isDeclaration for all aspects of
249+
// recognizing the global as a declaration, for now only check if
250+
// initializer is present.
251+
if (isForDefinition && !entry.isDeclaration()) {
252+
errorNYI(d->getSourceRange(), "global with conflicting type");
253+
}
254+
255+
// Address space check removed because it is unnecessary because CIR records
256+
// address space info in types.
257+
258+
// (If global is requested for a definition, we always need to create a new
259+
// global, not just return a bitcast.)
260+
if (!isForDefinition)
261+
return entry;
262+
}
263+
264+
errorNYI(d->getSourceRange(), "reference of undeclared global");
265+
}
266+
267+
cir::GlobalOp
268+
CIRGenModule::getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
269+
ForDefinition_t isForDefinition) {
270+
assert(d->hasGlobalStorage() && "Not a global variable");
271+
QualType astTy = d->getType();
272+
if (!ty)
273+
ty = getTypes().convertTypeForMem(astTy);
274+
275+
assert(!cir::MissingFeatures::mangledNames());
276+
return getOrCreateCIRGlobal(d->getIdentifier()->getName(), ty,
277+
astTy.getAddressSpace(), d, isForDefinition);
278+
}
279+
280+
/// Return the mlir::Value for the address of the given global variable. If
281+
/// \p ty is non-null and if the global doesn't exist, then it will be created
282+
/// with the specified type instead of whatever the normal requested type would
283+
/// be. If \p isForDefinition is true, it is guaranteed that an actual global
284+
/// with type \p ty will be returned, not conversion of a variable with the same
285+
/// mangled name but some other type.
286+
mlir::Value CIRGenModule::getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty,
287+
ForDefinition_t isForDefinition) {
288+
assert(d->hasGlobalStorage() && "Not a global variable");
289+
QualType astTy = d->getType();
290+
if (!ty)
291+
ty = getTypes().convertTypeForMem(astTy);
292+
293+
assert(!cir::MissingFeatures::opGlobalThreadLocal());
294+
295+
cir::GlobalOp g = getOrCreateCIRGlobal(d, ty, isForDefinition);
296+
mlir::Type ptrTy = builder.getPointerTo(g.getSymType());
297+
return builder.create<cir::GetGlobalOp>(getLoc(d->getSourceRange()), ptrTy,
298+
g.getSymName());
299+
}
300+
205301
void CIRGenModule::emitGlobalVarDefinition(const clang::VarDecl *vd,
206302
bool isTentative) {
207303
const QualType astTy = vd->getType();
@@ -507,6 +603,7 @@ cir::FuncOp CIRGenModule::getAddrOfFunction(clang::GlobalDecl gd,
507603
funcType = convertType(fd->getType());
508604
}
509605

606+
assert(!cir::MissingFeatures::mangledNames());
510607
cir::FuncOp func = getOrCreateCIRFunction(
511608
cast<NamedDecl>(gd.getDecl())->getIdentifier()->getName(), funcType, gd,
512609
forVTable, dontDefer, /*isThunk=*/false, isForDefinition);

clang/lib/CIR/CodeGen/CIRGenModule.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,31 @@ class CIRGenModule : public CIRGenTypeCache {
9191
const clang::LangOptions &getLangOpts() const { return langOpts; }
9292
mlir::MLIRContext &getMLIRContext() { return *builder.getContext(); }
9393

94+
/// -------
95+
/// Handling globals
96+
/// -------
97+
98+
mlir::Operation *getGlobalValue(llvm::StringRef ref);
99+
100+
/// If the specified mangled name is not in the module, create and return an
101+
/// mlir::GlobalOp value
102+
cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty,
103+
LangAS langAS, const VarDecl *d,
104+
ForDefinition_t isForDefinition);
105+
106+
cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
107+
ForDefinition_t isForDefinition);
108+
109+
/// Return the mlir::Value for the address of the given global variable.
110+
/// If Ty is non-null and if the global doesn't exist, then it will be created
111+
/// with the specified type instead of whatever the normal requested type
112+
/// would be. If IsForDefinition is true, it is guaranteed that an actual
113+
/// global with type Ty will be returned, not conversion of a variable with
114+
/// the same mangled name but some other type.
115+
mlir::Value
116+
getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty = {},
117+
ForDefinition_t isForDefinition = NotForDefinition);
118+
94119
/// Helpers to convert the presumed location of Clang's SourceLocation to an
95120
/// MLIR Location.
96121
mlir::Location getLoc(clang::SourceLocation cLoc);

clang/lib/CIR/Dialect/IR/CIRDialect.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -848,6 +848,41 @@ parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr,
848848
return success();
849849
}
850850

851+
//===----------------------------------------------------------------------===//
852+
// GetGlobalOp
853+
//===----------------------------------------------------------------------===//
854+
855+
LogicalResult
856+
cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
857+
// Verify that the result type underlying pointer type matches the type of
858+
// the referenced cir.global or cir.func op.
859+
mlir::Operation *op =
860+
symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
861+
if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
862+
return emitOpError("'")
863+
<< getName()
864+
<< "' does not reference a valid cir.global or cir.func";
865+
866+
mlir::Type symTy;
867+
if (auto g = dyn_cast<GlobalOp>(op)) {
868+
symTy = g.getSymType();
869+
assert(!cir::MissingFeatures::addressSpace());
870+
assert(!cir::MissingFeatures::opGlobalThreadLocal());
871+
} else if (auto f = dyn_cast<FuncOp>(op)) {
872+
symTy = f.getFunctionType();
873+
} else {
874+
llvm_unreachable("Unexpected operation for GetGlobalOp");
875+
}
876+
877+
auto resultType = dyn_cast<PointerType>(getAddr().getType());
878+
if (!resultType || symTy != resultType.getPointee())
879+
return emitOpError("result type pointee type '")
880+
<< resultType.getPointee() << "' does not match type " << symTy
881+
<< " of the global @" << getName();
882+
883+
return success();
884+
}
885+
851886
//===----------------------------------------------------------------------===//
852887
// FuncOp
853888
//===----------------------------------------------------------------------===//

clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,26 @@ mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewrite(
828828
return mlir::LogicalResult::success();
829829
}
830830

831+
mlir::LogicalResult CIRToLLVMGetGlobalOpLowering::matchAndRewrite(
832+
cir::GetGlobalOp op, OpAdaptor adaptor,
833+
mlir::ConversionPatternRewriter &rewriter) const {
834+
// FIXME(cir): Premature DCE to avoid lowering stuff we're not using.
835+
// CIRGen should mitigate this and not emit the get_global.
836+
if (op->getUses().empty()) {
837+
rewriter.eraseOp(op);
838+
return mlir::success();
839+
}
840+
841+
mlir::Type type = getTypeConverter()->convertType(op.getType());
842+
mlir::Operation *newop =
843+
rewriter.create<mlir::LLVM::AddressOfOp>(op.getLoc(), type, op.getName());
844+
845+
assert(!cir::MissingFeatures::opGlobalThreadLocal());
846+
847+
rewriter.replaceOp(op, newop);
848+
return mlir::success();
849+
}
850+
831851
/// Replace CIR global with a region initialized LLVM global and update
832852
/// insertion point to the end of the initializer block.
833853
void CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
@@ -1418,6 +1438,7 @@ void ConvertCIRToLLVMPass::runOnOperation() {
14181438
CIRToLLVMCmpOpLowering,
14191439
CIRToLLVMConstantOpLowering,
14201440
CIRToLLVMFuncOpLowering,
1441+
CIRToLLVMGetGlobalOpLowering,
14211442
CIRToLLVMTrapOpLowering,
14221443
CIRToLLVMUnaryOpLowering
14231444
// clang-format on

clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,16 @@ class CIRToLLVMFuncOpLowering : public mlir::OpConversionPattern<cir::FuncOp> {
140140
mlir::ConversionPatternRewriter &) const override;
141141
};
142142

143+
class CIRToLLVMGetGlobalOpLowering
144+
: public mlir::OpConversionPattern<cir::GetGlobalOp> {
145+
public:
146+
using mlir::OpConversionPattern<cir::GetGlobalOp>::OpConversionPattern;
147+
148+
mlir::LogicalResult
149+
matchAndRewrite(cir::GetGlobalOp op, OpAdaptor,
150+
mlir::ConversionPatternRewriter &) const override;
151+
};
152+
143153
class CIRToLLVMGlobalOpLowering
144154
: public mlir::OpConversionPattern<cir::GlobalOp> {
145155
const mlir::DataLayout &dataLayout;

clang/test/CIR/CodeGen/basic.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,28 @@ void f5(void) {
144144
// OGCG: br label %[[LOOP:.*]]
145145
// OGCG: [[LOOP]]:
146146
// OGCG: br label %[[LOOP]]
147+
148+
int gv;
149+
int f6(void) {
150+
return gv;
151+
}
152+
153+
// CIR: cir.func @f6() -> !s32i
154+
// CIR-NEXT: %[[RV:.*]] = cir.alloca !s32i, !cir.ptr<!s32i>, ["__retval"] {alignment = 4 : i64}
155+
// CIR-NEXT: %[[GV_PTR:.*]] = cir.get_global @gv : !cir.ptr<!s32i>
156+
// CIR-NEXT: %[[GV:.*]] = cir.load %[[GV_PTR]] : !cir.ptr<!s32i>, !s32i
157+
// CIR-NEXT: cir.store %[[GV]], %[[RV]] : !s32i, !cir.ptr<!s32i>
158+
// CIR-NEXT: %[[R:.*]] = cir.load %[[RV]] : !cir.ptr<!s32i>, !s32i
159+
// CIR-NEXT: cir.return %[[R]] : !s32i
160+
161+
// LLVM: define i32 @f6()
162+
// LLVM-NEXT: %[[RV_PTR:.*]] = alloca i32, i64 1, align 4
163+
// LLVM-NEXT: %[[GV:.*]] = load i32, ptr @gv, align 4
164+
// LLVM-NEXT: store i32 %[[GV]], ptr %[[RV_PTR]], align 4
165+
// LLVM-NEXT: %[[RV:.*]] = load i32, ptr %[[RV_PTR]], align 4
166+
// LLVM-NEXT: ret i32 %[[RV]]
167+
168+
// OGCG: define{{.*}} i32 @f6()
169+
// OGCG-NEXT: entry:
170+
// OGCG-NEXT: %[[GV:.*]] = load i32, ptr @gv, align 4
171+
// OGCG-NEXT: ret i32 %[[GV]]

0 commit comments

Comments
 (0)