LLVM强制转换指令 [英] LLVM Cast Instructions

查看:61
本文介绍了LLVM强制转换指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要使用fadd添加的ConstantIntConstantFP值。但是,将ConstantInt转换为fadd可以接受的浮点数时遇到问题。

以下是代码的摘录:

Value* left = ConstantInt::get(Type::getInt64Ty(getGlobalContext()), 12, true);
Value* right = ConstantFP::get(Type::getFloatTy(getGlobalContext()), 11.6);

Instruction* cast = CastInst::Create(Instruction::SIToFP, left, left->getType(), "", currentBlock());
left = cast->getOperand(0);

BinaryOperator::Create(Instruction::FAdd, left, right, "", currentBlock());

WHEREcurrentBlock()返回BasicBlock。在尝试为此生成操作码之后,LLVM抱怨它无法将这两个值相加,因为它们不相同。

我对LLVM比较陌生,因此如果此代码没有任何意义,我将听取任何建议。

Clang

我处理这些事情的通常方法是查看推荐答案生成什么-LLVMIR和C++API调用(C++后端)。为简单起见,您可以使用online instance。因此,编译这段C代码:

float foo(int a, float b) {
  return a + b;
}

提供此LLVM IR:

define float @foo(i32 %a, float %b) #0 {
entry:
  %conv = sitofp i32 %a to float
  %add = fadd float %conv, %b
  ret float %add
}

这是重新创建它所需的C++API调用:

 // Function: foo (func_foo)
 {
  Function::arg_iterator args = func_foo->arg_begin();
  Value* int32_a = args++;
  int32_a->setName("a");
  Value* float_b = args++;
  float_b->setName("b");

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

  // Block entry (label_entry)
  CastInst* float_conv = new SIToFPInst(int32_a, Type::getFloatTy(mod->getContext()), "conv", label_entry);
  BinaryOperator* float_add = BinaryOperator::Create(Instruction::FAdd, float_conv, float_b, "add", label_entry);
  ReturnInst::Create(mod->getContext(), float_add, label_entry);   
 }

您可以随意调整输入的C代码(例如,用常量替换var等)并查看Clang/LLVM发出的内容。当您不太熟悉IR和API时,这是最好/最快的方法。

这篇关于LLVM强制转换指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆