[AsmWriter] Don't crash when printing addrspace and the operand is null
authorVasileios Porpodas <vporpodas@google.com>
Mon, 9 Jan 2023 23:18:55 +0000 (15:18 -0800)
committerVasileios Porpodas <vporpodas@google.com>
Tue, 10 Jan 2023 23:14:25 +0000 (15:14 -0800)
This helps print instructions with detached operands in the debugger.

Differential Revision: https://reviews.llvm.org/D141343

llvm/lib/IR/AsmWriter.cpp
llvm/unittests/IR/AsmWriterTest.cpp

index b1ec484..234f4d8 100644 (file)
@@ -4008,6 +4008,10 @@ void AssemblyWriter::printInfoComment(const Value &V) {
 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
                                     raw_ostream &Out) {
   // We print the address space of the call if it is non-zero.
+  if (Operand == nullptr) {
+    Out << " <cannot get addrspace!>";
+    return;
+  }
   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
   bool PrintAddrSpace = CallAddrSpace != 0;
   if (!PrintAddrSpace) {
index c8b5379..9fc7ce4 100644 (file)
@@ -62,4 +62,23 @@ TEST(AsmWriterTest, DumpDIExpression) {
             OS.str());
 }
 
+TEST(AsmWriterTest, PrintAddrspaceWithNullOperand) {
+  LLVMContext Ctx;
+  std::unique_ptr<Module> M;
+  SmallVector<Type *, 3> FArgTypes;
+  FArgTypes.push_back(Type::getInt64Ty(Ctx));
+  FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false);
+  Function *F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
+  Argument *Arg0 = F->getArg(0);
+  Value *Args[] = {Arg0};
+  std::unique_ptr<CallInst> Call(CallInst::Create(F, Args));
+  // This will make Call's operand null.
+  Call->dropAllReferences();
+
+  std::string S;
+  raw_string_ostream OS(S);
+  Call->print(OS);
+  std::size_t r = OS.str().find("<cannot get addrspace!>");
+  EXPECT_TRUE(r != std::string::npos);
+}
 }