如何将可变数量的参数传递给 LLVM opt pass?

How do I pass a variable number of arguments to a LLVM opt pass?

我想将可变数量的参数传递给我的 LLVM opt pass。

为此,我做了类似的事情:

static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
static cl::list<std::string> Libraries("l", cl::ZeroOrMore);

但是,如果我现在像这样调用 opt:

foo@foo-Ubuntu:~/llvm-ir-obfuscation$ opt -load cmake-build-debug/water/libMapInstWMPass.so -mapiWM programs/ll/sum100.ll -S 2 3 4  -o foo.ll
opt: Too many positional arguments specified!
Can specify at most 2 positional arguments: See: opt -help

,然后我收到 opt 最多接受 2 个位置参数的错误。

我做错了什么?

我认为问题是 opt 已经在解析它自己的参数,并且已经有位码文件作为位置参数来处理,所以有多个位置参数会产生歧义。

文档解释了 API 就像它在独立应用程序中使用一样。因此,例如,如果您执行以下操作:

int main(int argc, char *argv[]) {
  cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
  cl::list<std::string> Files2(cl::Positional, cl::OneOrMore);
  cl::list<std::string> Libraries("l", cl::ZeroOrMore);
  cl::ParseCommandLineOptions(argc, argv);

  for(auto &e : Libraries) outs() << e << "\n";
  outs() << "....\n";
  for(auto &e : Files) outs() << e << "\n";
  outs() << "....\n";
  for(auto &e : Files2) outs() << e << "\n";
  outs() << "....\n";
}

你得到这样的东西:

$ foo -l one two three four five six

one
....
two
three
four
five
....
six
....

现在,如果您交换两个位置参数定义,甚至将 Files2 选项的 cl::OneOrMore 更改为 cl::ZeroOrMore,您将得到一个错误

$ option: error - option can never match, because another positional argument will match an unbounded number of values, and this option does not require a value!

就我个人而言,当我使用 opt 时,我放弃了位置参数选项并执行如下操作:

cl::list<std::string> Lists("lists", cl::desc("Specify names"), cl::OneOrMore);

这让我可以这样做:

opt -load ./fooPass.so -foo -o out.bc -lists one ./in.bc -lists two

并以我得到的相同方式遍历 std::string 列表:

one
two

正如@compor 所建议的,这可能与 opt 和您自己的传球交织在一起的参数有关。 CommandLine 库主要是为 LLVM 框架内的独立应用程序编写的。

但是,您可以执行以下操作:

static cl::list<std::string> Args1("args1", cl::Positional, cl::CommaSeparated);
static cl::list<std::string> Args2("args2", cl::ZeroOrMore);

这样做的好处是您可以在命令行中使用逗号输入多个参数,例如 arg1,arg2,... 或使用标识符 -args1 arg1 arg2 ...;这些被插入到 Args1 列表中。如果您只在命令行上提供一个位置参数 arg,那么 Args1 将只包含这个参数。

此外,您可以在任何地方的命令行上指定 -args2 arg(命名为非位置选项)。这些将进入 Args2 列表。