[PATCH] D38473: Include getting generated struct offsets in CodegenABITypes

Michael Ferguson via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 2 12:19:19 PDT 2017


This change adds a new function, CodeGen::getFieldNumber, that
enables a user of clang's code generation to get the field number
in a generated LLVM IR struct that corresponds to a particular field
in a C struct.

It is important to expose this information in Clang's code generation
interface because there is no reasonable way for users of Clang's code
generation to get this information. In particular:

1. LLVM struct types do not include field names.
2. Clang adds a non-trivial amount of logic to the code generation of
LLVM IR types for structs, in particular to handle padding and bit
fields.

This in some ways is a philosophical continuation of
https://reviews.llvm.org/D35180 .

I'm working on a programming language that uses Clang to create
seamless C interoperability. One of the language features is to create
"extern records", which are just structs that have a definition in C
code. The language needs to be able to code generate element access to
particular structure fields by name, and without this patch, I need to
use clang-internal headers to do so.



diff --git a/include/clang/CodeGen/CodeGenABITypes.h
b/include/clang/CodeGen/CodeGenABITypes.h
index 615e55c8b6..f4fa28da1b 100644
--- a/include/clang/CodeGen/CodeGenABITypes.h
+++ b/include/clang/CodeGen/CodeGenABITypes.h
@@ -78,6 +78,10 @@ llvm::FunctionType
*convertFreeFunctionType(CodeGenModule &CGM,

 llvm::Type *convertTypeForMemory(CodeGenModule &CGM, QualType T);

+// Returns a field number for a struct suitable for GEP'ing
+unsigned getFieldNumber(CodeGenModule &CGM,
+                        const RecordDecl *RD, const FieldDecl *FD);
+
 }  // end namespace CodeGen
 }  // end namespace clang

diff --git a/lib/CodeGen/CodeGenABITypes.cpp b/lib/CodeGen/CodeGenABITypes.cpp
index 0735a9c3df..759ad75897 100644
--- a/lib/CodeGen/CodeGenABITypes.cpp
+++ b/lib/CodeGen/CodeGenABITypes.cpp
@@ -17,6 +17,7 @@
 //===----------------------------------------------------------------------===//

 #include "clang/CodeGen/CodeGenABITypes.h"
+#include "CGRecordLayout.h"
 #include "CodeGenModule.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/CodeGenOptions.h"
@@ -80,3 +81,8 @@ llvm::Type *
 CodeGen::convertTypeForMemory(CodeGenModule &CGM, QualType T) {
   return CGM.getTypes().ConvertTypeForMem(T);
 }
+
+unsigned CodeGen::getFieldNumber(CodeGenModule &CGM,
+                                 const RecordDecl *RD, const FieldDecl *FD) {
+  return CGM.getTypes().getCGRecordLayout(RD).getLLVMFieldNo(FD);
+}


More information about the cfe-commits mailing list