0

I'm trying to get the pointer to each instruction, which supposedly can be achieved by doing:

Value* ptr = dyn_cast<Value>(&inst);

However, I keep getting a segmentation fault when running the compiled C++ program with cmake. In debug mode, I get the following error message:

opt-11: /usr/lib/llvm-11/include/llvm/IR/User.h:170: llvm::Value* llvm::User::getOperand(unsigned int) 
const: Assertion `i < NumUserOperands && "getOperand() out of range!"' failed.

In LLVM doc, here is the block of code that points to the source of the assertion:

   Value *getOperand(unsigned i) const {
     assert(i < NumUserOperands && "getOperand() out of range!");
     return getOperandList()[i];
   }

I added empty check to every variable acquired from getOperand() in the program but the error remains. Does anyone know why it's happening and how to fix it?

4
  • 1. Run Valgrind. 2. If you want to do a lot with LLVM, build a tree with debug symbols. Commented Mar 14, 2021 at 8:41
  • And FWIW, using dyn_cast<> to cast to Value doesn't make sense. Value is the root class. If you have an Instruction* you already have Value*, there's nothing left for dyn_cast<> to do. Commented Mar 14, 2021 at 10:18
  • Thanks for the comments! I'm new to debugging in C++, can you elaborate on building a tree with the debug symbol? Commented Mar 14, 2021 at 10:49
  • You are right, previously I thought the source of my problem was at the instruction pointer but it is not. Commented Mar 14, 2021 at 10:57

1 Answer 1

0

Actually, some instructions in the LLVM IR had only one operand and it would not make sense to get the second one with inst.getOperand(1). Therefore it is necessary to check the number of operands before proceeding:

         for (auto& inst : bb) {
            Value* v1;
            Value* v2;
            if (inst.getNumOperands() >= 1) 
                v1 = inst.getOperand(0);
            if (inst.getNumOperands() == 2)
                v2 = inst.getOperand(1);
         }

or simply

         for (auto& inst : bb) {
            Value* v1 = inst.getOperand(0);
            Value* v2;
            if (inst.getNumOperands() == 2)
                v2 = inst.getOperand(1);
         }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.