4

我正在研究 LLVM IR 中的一个程序,我正在尝试初始化一个字符串,上面写着“Hello World!” 但我不知道怎么做。代码的目标是计算字符串中的字符数。在需要初始化字符串之前,在标题之后,我有以下内容:

int main (int argc, const char *argv[]) {
    //Setting up 
    //Build a pointer to the string - LLVMValueRef *strptr=LLVMBuildGlobalStringPtr(builder, const char *string, const char *name);
    LLVMValueRef *strptr;
    LLVMContextRef context = LLVMContextCreate();
    LLVMBuilderRef builder = LLVMCreateBuilderInContext (context);
    LLVMModuleRef module1 = LLVMModuleCreateWithNameInContext("mod", context);
}
4

1 回答 1

8

使用 C++ 后端查看这些事情的最简单方法 - 它生成为您构建模块的 C++ API 调用。你可以在网上看到这个。

“编译”这段代码:

const char* foo() {
  const char* s = "hello world";
  return s;
}

以下是相关的 C++ API 调用:

GlobalVariable* gvar_array__str = new GlobalVariable(/*Module=*/*mod, 
 /*Type=*/ArrayTy_0,
 /*isConstant=*/true,
 /*Linkage=*/GlobalValue::PrivateLinkage,
 /*Initializer=*/0, // has initializer, specified below
 /*Name=*/".str");
 gvar_array__str->setAlignment(1);

 // Constant Definitions
 Constant *const_array_4 = ConstantDataArray::getString(mod->getContext(), "hello world", true);
 std::vector<Constant*> const_ptr_5_indices;
 ConstantInt* const_int64_6 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("0"), 10));
 const_ptr_5_indices.push_back(const_int64_6);
 const_ptr_5_indices.push_back(const_int64_6);
 Constant* const_ptr_5 = ConstantExpr::getGetElementPtr(gvar_array__str, const_ptr_5_indices);

 // Global Variable Definitions
 gvar_array__str->setInitializer(const_array_4);

 // Function Definitions

 // Function: foo (func_foo)
 {

  BasicBlock* label_entry = BasicBlock::Create(mod->getContext(), "entry",func_foo,0);

  // Block entry (label_entry)
  ReturnInst::Create(mod->getContext(), const_ptr_5, label_entry);

 }
于 2013-05-21T00:41:02.240 回答