LLVM C API下Type与Type*类型比较及取值方法问询
Great question! Let's break this down clearly, since there's a common point of confusion between LLVM's C and C++ APIs when it comes to type handling.
First, a critical clarification for the LLVM C API:
There is no "llvm Type" value type in the C API. All type-related objects are referenced via pointers—specifically
LLVMTypeRef, which is just a typedef forType*under the hood. So when you're talking about "llvm Type" vs "Type*" in this context, you're actually referring to the same thing: a pointer to an LLVM type object.
Comparing Types
You have two reliable ways to check if two types are equivalent in the C API:
- Pointer equality check: LLVM typically reuses singleton instances for common types (like
i32,void, etc.), so if twoLLVMTypeRefpointers point to the same memory address, they represent the exact same type. This is the simplest check for most cases:LLVMValueRef val1 = /* your value */; LLVMValueRef val2 = /* another value */; LLVMTypeRef type1 = LLVMTypeOf(val1); LLVMTypeRef type2 = LLVMTypeOf(val2); if (type1 == type2) { // The types are the same (same singleton instance) } - Semantic equality with
LLVMEqualTypes: If you need to verify that two types are semantically equivalent (even if they were created as separate instances, which is rare but possible in edge cases), use the official API function:if (LLVMEqualTypes(type1, type2)) { // The types are functionally identical, even if their pointers differ }
Getting a Value's Type
You're already on the right track with LLVMTypeOf—this is the only official way to retrieve the type of an LLVMValueRef in the C API. It directly returns an LLVMTypeRef (your Type*), which is the standard handle for working with types in the C API. There's no way to get a "value type" version of the type here, since the C API is designed entirely around pointer-based handles.
A quick note to avoid pitfalls: Always make sure your LLVMValueRef isn't a null pointer before calling LLVMTypeOf—dereferencing a null value here will cause undefined behavior.
内容的提问来源于stack exchange,提问作者Destructor

