我在C++中有一些示例代码:
struct RecordTest
{
int value1;
int value2;
};
void test()
{
RecordTest rt;
rt.value1 = 15;
rt.value2 = 75;
}
Run Code Online (Sandbox Code Playgroud)
和LLVM 3.4 IR:
%struct.RecordTest = type { i32, i32 }
; Function Attrs: nounwind
define void @_Z4testv() #0 {
entry:
%rt = alloca %struct.RecordTest, align 4
%value1 = getelementptr inbounds %struct.RecordTest* %rt, i32 0, i32 0
store i32 15, i32* %value1, align 4
%value2 = getelementptr inbounds %struct.RecordTest* %rt, i32 0, i32 1
store i32 75, i32* %value2, align 4
ret void
}
Run Code Online (Sandbox Code Playgroud)
还有一个非常简单的问题:如何RecordTest在没有索引的情况下访问字段(当我解析.cpp时)只有名称(value1和value2)?
我只知道一种方式(来自llc -march=cpp) - 带索引:
AllocaInst* ptr_rt = new AllocaInst(StructTy_struct_RecordTest, "rt", label_entry);
ptr_rt->setAlignment(4);
std::vector<Value*> ptr_value1_indices;
ptr_value1_indices.push_back(const_int32_6);
ptr_value1_indices.push_back(const_int32_6);
Instruction* ptr_value1 = GetElementPtrInst::Create(ptr_rt, ptr_value1_indices, "value1", label_entry);
StoreInst* void_9 = new StoreInst(const_int32_7, ptr_value1, false, label_entry);
void_9->setAlignment(4);
std::vector<Value*> ptr_value2_indices;
ptr_value2_indices.push_back(const_int32_6);
ptr_value2_indices.push_back(const_int32_5);
Instruction* ptr_value2 = GetElementPtrInst::Create(ptr_rt, ptr_value2_indices, "value2", label_entry);
StoreInst* void_10 = new StoreInst(const_int32_8, ptr_value2, false, label_entry);
void_10->setAlignment(4);
Run Code Online (Sandbox Code Playgroud)
那么,如果我不知道字段的索引(const_int32_5以及const_int32_6上面的代码中),我可以从C++转换为LLVM IR 吗?
UPD ================================
因此,我们无法访问字段名称.如果我们需要它(我们这样做,如果我们解析.cpp),我们可以这样写:
// It can be some kind of singletone
static std::map<std::string, std::vector<std::string>> mymap;
// Some function, where we first time meet RecordTest
std::vector<std::string> fieldNames;
fieldNames.push_back("value1");
fieldNames.push_back("value2");
mymap["RecordTest"] = fieldNames;
// Some function, where we need to access to RecordTest field
std::vector<std::string> fieldNamesAgain = mymap.find("RecordTest")->second;
std::string fieldName = "value1";
int idxValue1 = -1;
for (int i = 0, e = fieldNamesAgain.size(); i < e; i++) // little ugly search
{
if (fieldName == fieldNamesAgain[i])
{
// we get field index, and now we can build code
// as in example above (llc -march=cpp)
idxValue1 = i;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的吗 ?
您不能通过名称访问结构体的字段,只能通过索引访问。当您使用 Clang 编译时,此信息通常不存在。
有一个例外,那就是如果您使用调试信息进行编译。在这种情况下,您将拥有有关该类型的充足数据;具体来说,您将获得字段的顺序,以及每个字段的元数据条目,其中包含其名称(以及其他有用的内容,例如相对于类型开头的偏移量)。
在源代码级调试指南中阅读有关此内容的更多信息- 特别是,请参阅有关结构编码的部分及其非常好的示例。
查看DebugInfo.h中的类来帮助查询调试信息,尽管我认为无论如何您都必须进行一些手动挖掘。
| 归档时间: |
|
| 查看次数: |
3799 次 |
| 最近记录: |