1//===- PredicateExpanderDag.cpp - Composable predicate dag lowering -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "PredicateExpanderDag.h"
10#include "llvm/Support/raw_ostream.h"
11#include "llvm/TableGen/Error.h"
12#include "llvm/TableGen/Record.h"
13
14using namespace llvm;
15
16bool llvm::emitPredicateDag(
17 const Record *Owner, const Init &Val, bool ParenIfBinOp, raw_ostream &OS,
18 function_ref<bool(const Init &, raw_ostream &)> EmitLeaf) {
19 if (const auto *D = dyn_cast<DagInit>(Val: &Val)) {
20 const auto *Op = dyn_cast<DefInit>(Val: D->getOperator());
21 if (!Op)
22 PrintFatalError(Rec: Owner, Msg: "invalid predicate dag operator");
23 StringRef OpName = Op->getDef()->getName();
24 if (OpName == "not") {
25 if (D->getNumArgs() != 1)
26 PrintFatalError(Rec: Owner, Msg: "'not' takes exactly one operand");
27 OS << "!(";
28 bool Err = emitPredicateDag(Owner, Val: *D->getArg(Num: 0), /*ParenIfBinOp=*/false,
29 OS, EmitLeaf);
30 OS << ')';
31 return Err;
32 }
33
34 if (OpName == "none_of") {
35 if (D->getNumArgs() == 0)
36 PrintFatalError(Rec: Owner, Msg: "'none_of' requires at least one operand");
37 OS << "!(";
38 ListSeparator LS(" || ");
39 for (const Init *Arg : D->getArgs()) {
40 OS << LS;
41 if (emitPredicateDag(Owner, Val: *Arg, /*ParenIfBinOp=*/D->getNumArgs() > 1,
42 OS, EmitLeaf))
43 return true;
44 }
45
46 OS << ')';
47 return false;
48 }
49
50 if (OpName == "any_of" || OpName == "all_of") {
51 if (D->getNumArgs() == 0)
52 PrintFatalError(Rec: Owner,
53 Msg: "'" + OpName + "' requires at least one operand");
54 bool Paren = D->getNumArgs() > 1 && std::exchange(obj&: ParenIfBinOp, new_val: true);
55 if (Paren)
56 OS << '(';
57 ListSeparator LS(OpName == "any_of" ? " || " : " && ");
58 for (const Init *Arg : D->getArgs()) {
59 OS << LS;
60 if (emitPredicateDag(Owner, Val: *Arg, ParenIfBinOp, OS, EmitLeaf))
61 return true;
62 }
63 if (Paren)
64 OS << ')';
65 return false;
66 }
67 PrintFatalError(Rec: Owner, Msg: "unknown predicate dag operator '" + OpName +
68 "'; expected all_of/any_of/none_of/not");
69 }
70
71 // Any non-dag operand (or the base leaf) is emitted by the caller, which
72 // diagnoses leaf-level errors specific to its consumer.
73 return EmitLeaf(Val, OS);
74}
75