syang-ng opened a new pull request #9114: URL: https://github.com/apache/tvm/pull/9114
As we discussed in [this post](https://discuss.tvm.apache.org/t/undefined-behavior-happens-when-casting-string-to-bool/11090/10), a casting from handle to int or other types is actually undefined. For example, when we try to cast a handle to bool, it will invoke `llvm::Constant* zero = llvm::ConstantInt::get(DTypeToLLVMType(from), 0);`, which means that we regard the from type is `int`, but actually it is `handle`. [src/target/llvm/codegen_llvm.cc - CodeGenLLVM::CreateCast](https://github.com/apache/tvm/blob/main/src/target/llvm/codegen_llvm.cc#L687): ```c++ llvm::Value* CodeGenLLVM::CreateCast(DataType from, DataType to, llvm::Value* value) { llvm::Type* target = DTypeToLLVMType(to); if (value->getType() == target) return value; if (to.is_handle()) { return builder_->CreateBitCast(value, target); } else if (to.is_uint() && to.bits() == 1) { if (from.is_float()) { llvm::Constant* zero = llvm::ConstantFP::get(DTypeToLLVMType(from), 0.); return builder_->CreateFCmpONE(value, zero); } else { llvm::Constant* zero = llvm::ConstantInt::get(DTypeToLLVMType(from), 0); return builder_->CreateICmpNE(value, zero); } } else if (!from.is_float() && !to.is_float()) { return builder_->CreateIntCast(value, target, from.is_int()); } else if (from.is_float() && to.is_int()) { return builder_->CreateFPToSI(value, target); } else if (from.is_float() && to.is_uint()) { if (to.bits() < 8) { value = builder_->CreateFPToUI(value, DTypeToLLVMType(to.with_bits(8))); return builder_->CreateIntCast(value, target, false); } else { return builder_->CreateFPToUI(value, target); } } else if (from.is_int() && to.is_float()) { return builder_->CreateSIToFP(value, target); } else if (from.is_uint() && to.is_float()) { return builder_->CreateUIToFP(value, target); } else { ICHECK(from.is_float() && to.is_float()); return builder_->CreateFPCast(value, target); } } ``` And this undefined behavior may cause some other problems, like program crashes:  -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
