如何在 LLVM 中按名称查找模块中使用的类型?

How to lookup a type used in a module by name in LLVM?

在 LLVM 中,可以使用 Function* Module::getFunction(StringRef Name) const 在模块中按名称查找函数。

同样,可以使用 GlobalVariable* Module::getGlobalVariable(StringRef Name) const.

在模块中按名称查找全局变量

如何对模块中定义的类型执行相同的操作?

类型不同于函数和全局变量,因为这两者存在于模块中,并且最终会在可执行文件或生成的任何内容中包含一些字节。类型不是那样的。

类型不占 space,存在于 Context and aren't necessarily findable. They generally can be found, though: If you want to find the singleton 42-bit integer type, you ask IntegerType::get(), and if you want to find a struct, you ask StructType, either by structure or by name

(请记住,并非所有结构类型都可以通过询问 LLVM 找到。在我的例子中,我曾经遇到过调用者需要指向结构的指针的问题,但结构类型仍然只是一个代码中那个位置的占位符,既没有名称也没有定义。我最终通过询问我自己的代码找到了正确的 LLVM 类型,而不是询问 LLVM,我认为很多人做类似的事情。)

StructType *StructType::getTypeByName(Context, Name)。如果您没有上下文,请使用 MyModule.getContext()doxygen

顺便说一句,我不认为其他类型可以有名字。

我觉得这个说法

... a type defined within a module

只能应用于已识别的结构,因为在特定的 LLVMContext 中只能有一个具有给定名称的已识别结构。文字结构类型在结构上是唯一的,并且像 'exist' 已经寻找的 i8 这样的原语,所以您所做的就是获取它们并使用它们来注释值。也许这就是为什么它们是用 get 方法创建的。

您可以使用 Module::getIdentifiedStructTypes 方法在 llvm::Module 中获取已识别的结构。

如果您对浏览一个模块并识别该模块中使用的所有类型感兴趣,一定要看看 TypeFinder.cpp