1 //===- TranslateToCpp.cpp - Translating to C++ calls ----------------------===// 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 "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 10 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" 11 #include "mlir/Dialect/EmitC/IR/EmitC.h" 12 #include "mlir/Dialect/Func/IR/FuncOps.h" 13 #include "mlir/Dialect/SCF/SCF.h" 14 #include "mlir/IR/BuiltinOps.h" 15 #include "mlir/IR/BuiltinTypes.h" 16 #include "mlir/IR/Dialect.h" 17 #include "mlir/IR/Operation.h" 18 #include "mlir/Support/IndentedOstream.h" 19 #include "mlir/Target/Cpp/CppEmitter.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringMap.h" 23 #include "llvm/ADT/TypeSwitch.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/FormatVariadic.h" 26 #include <utility> 27 28 #define DEBUG_TYPE "translate-to-cpp" 29 30 using namespace mlir; 31 using namespace mlir::emitc; 32 using llvm::formatv; 33 34 /// Convenience functions to produce interleaved output with functions returning 35 /// a LogicalResult. This is different than those in STLExtras as functions used 36 /// on each element doesn't return a string. 37 template <typename ForwardIterator, typename UnaryFunctor, 38 typename NullaryFunctor> 39 inline LogicalResult 40 interleaveWithError(ForwardIterator begin, ForwardIterator end, 41 UnaryFunctor eachFn, NullaryFunctor betweenFn) { 42 if (begin == end) 43 return success(); 44 if (failed(eachFn(*begin))) 45 return failure(); 46 ++begin; 47 for (; begin != end; ++begin) { 48 betweenFn(); 49 if (failed(eachFn(*begin))) 50 return failure(); 51 } 52 return success(); 53 } 54 55 template <typename Container, typename UnaryFunctor, typename NullaryFunctor> 56 inline LogicalResult interleaveWithError(const Container &c, 57 UnaryFunctor eachFn, 58 NullaryFunctor betweenFn) { 59 return interleaveWithError(c.begin(), c.end(), eachFn, betweenFn); 60 } 61 62 template <typename Container, typename UnaryFunctor> 63 inline LogicalResult interleaveCommaWithError(const Container &c, 64 raw_ostream &os, 65 UnaryFunctor eachFn) { 66 return interleaveWithError(c.begin(), c.end(), eachFn, [&]() { os << ", "; }); 67 } 68 69 namespace { 70 /// Emitter that uses dialect specific emitters to emit C++ code. 71 struct CppEmitter { 72 explicit CppEmitter(raw_ostream &os, bool declareVariablesAtTop); 73 74 /// Emits attribute or returns failure. 75 LogicalResult emitAttribute(Location loc, Attribute attr); 76 77 /// Emits operation 'op' with/without training semicolon or returns failure. 78 LogicalResult emitOperation(Operation &op, bool trailingSemicolon); 79 80 /// Emits type 'type' or returns failure. 81 LogicalResult emitType(Location loc, Type type); 82 83 /// Emits array of types as a std::tuple of the emitted types. 84 /// - emits void for an empty array; 85 /// - emits the type of the only element for arrays of size one; 86 /// - emits a std::tuple otherwise; 87 LogicalResult emitTypes(Location loc, ArrayRef<Type> types); 88 89 /// Emits array of types as a std::tuple of the emitted types independently of 90 /// the array size. 91 LogicalResult emitTupleType(Location loc, ArrayRef<Type> types); 92 93 /// Emits an assignment for a variable which has been declared previously. 94 LogicalResult emitVariableAssignment(OpResult result); 95 96 /// Emits a variable declaration for a result of an operation. 97 LogicalResult emitVariableDeclaration(OpResult result, 98 bool trailingSemicolon); 99 100 /// Emits the variable declaration and assignment prefix for 'op'. 101 /// - emits separate variable followed by std::tie for multi-valued operation; 102 /// - emits single type followed by variable for single result; 103 /// - emits nothing if no value produced by op; 104 /// Emits final '=' operator where a type is produced. Returns failure if 105 /// any result type could not be converted. 106 LogicalResult emitAssignPrefix(Operation &op); 107 108 /// Emits a label for the block. 109 LogicalResult emitLabel(Block &block); 110 111 /// Emits the operands and atttributes of the operation. All operands are 112 /// emitted first and then all attributes in alphabetical order. 113 LogicalResult emitOperandsAndAttributes(Operation &op, 114 ArrayRef<StringRef> exclude = {}); 115 116 /// Emits the operands of the operation. All operands are emitted in order. 117 LogicalResult emitOperands(Operation &op); 118 119 /// Return the existing or a new name for a Value. 120 StringRef getOrCreateName(Value val); 121 122 /// Return the existing or a new label of a Block. 123 StringRef getOrCreateName(Block &block); 124 125 /// Whether to map an mlir integer to a unsigned integer in C++. 126 bool shouldMapToUnsigned(IntegerType::SignednessSemantics val); 127 128 /// RAII helper function to manage entering/exiting C++ scopes. 129 struct Scope { 130 Scope(CppEmitter &emitter) 131 : valueMapperScope(emitter.valueMapper), 132 blockMapperScope(emitter.blockMapper), emitter(emitter) { 133 emitter.valueInScopeCount.push(emitter.valueInScopeCount.top()); 134 emitter.labelInScopeCount.push(emitter.labelInScopeCount.top()); 135 } 136 ~Scope() { 137 emitter.valueInScopeCount.pop(); 138 emitter.labelInScopeCount.pop(); 139 } 140 141 private: 142 llvm::ScopedHashTableScope<Value, std::string> valueMapperScope; 143 llvm::ScopedHashTableScope<Block *, std::string> blockMapperScope; 144 CppEmitter &emitter; 145 }; 146 147 /// Returns wether the Value is assigned to a C++ variable in the scope. 148 bool hasValueInScope(Value val); 149 150 // Returns whether a label is assigned to the block. 151 bool hasBlockLabel(Block &block); 152 153 /// Returns the output stream. 154 raw_indented_ostream &ostream() { return os; }; 155 156 /// Returns if all variables for op results and basic block arguments need to 157 /// be declared at the beginning of a function. 158 bool shouldDeclareVariablesAtTop() { return declareVariablesAtTop; }; 159 160 private: 161 using ValueMapper = llvm::ScopedHashTable<Value, std::string>; 162 using BlockMapper = llvm::ScopedHashTable<Block *, std::string>; 163 164 /// Output stream to emit to. 165 raw_indented_ostream os; 166 167 /// Boolean to enforce that all variables for op results and block 168 /// arguments are declared at the beginning of the function. This also 169 /// includes results from ops located in nested regions. 170 bool declareVariablesAtTop; 171 172 /// Map from value to name of C++ variable that contain the name. 173 ValueMapper valueMapper; 174 175 /// Map from block to name of C++ label. 176 BlockMapper blockMapper; 177 178 /// The number of values in the current scope. This is used to declare the 179 /// names of values in a scope. 180 std::stack<int64_t> valueInScopeCount; 181 std::stack<int64_t> labelInScopeCount; 182 }; 183 } // namespace 184 185 static LogicalResult printConstantOp(CppEmitter &emitter, Operation *operation, 186 Attribute value) { 187 OpResult result = operation->getResult(0); 188 189 // Only emit an assignment as the variable was already declared when printing 190 // the FuncOp. 191 if (emitter.shouldDeclareVariablesAtTop()) { 192 // Skip the assignment if the emitc.constant has no value. 193 if (auto oAttr = value.dyn_cast<emitc::OpaqueAttr>()) { 194 if (oAttr.getValue().empty()) 195 return success(); 196 } 197 198 if (failed(emitter.emitVariableAssignment(result))) 199 return failure(); 200 return emitter.emitAttribute(operation->getLoc(), value); 201 } 202 203 // Emit a variable declaration for an emitc.constant op without value. 204 if (auto oAttr = value.dyn_cast<emitc::OpaqueAttr>()) { 205 if (oAttr.getValue().empty()) 206 // The semicolon gets printed by the emitOperation function. 207 return emitter.emitVariableDeclaration(result, 208 /*trailingSemicolon=*/false); 209 } 210 211 // Emit a variable declaration. 212 if (failed(emitter.emitAssignPrefix(*operation))) 213 return failure(); 214 return emitter.emitAttribute(operation->getLoc(), value); 215 } 216 217 static LogicalResult printOperation(CppEmitter &emitter, 218 emitc::ConstantOp constantOp) { 219 Operation *operation = constantOp.getOperation(); 220 Attribute value = constantOp.value(); 221 222 return printConstantOp(emitter, operation, value); 223 } 224 225 static LogicalResult printOperation(CppEmitter &emitter, 226 emitc::VariableOp variableOp) { 227 Operation *operation = variableOp.getOperation(); 228 Attribute value = variableOp.value(); 229 230 return printConstantOp(emitter, operation, value); 231 } 232 233 static LogicalResult printOperation(CppEmitter &emitter, 234 arith::ConstantOp constantOp) { 235 Operation *operation = constantOp.getOperation(); 236 Attribute value = constantOp.getValue(); 237 238 return printConstantOp(emitter, operation, value); 239 } 240 241 static LogicalResult printOperation(CppEmitter &emitter, 242 func::ConstantOp constantOp) { 243 Operation *operation = constantOp.getOperation(); 244 Attribute value = constantOp.getValueAttr(); 245 246 return printConstantOp(emitter, operation, value); 247 } 248 249 static LogicalResult printOperation(CppEmitter &emitter, 250 cf::BranchOp branchOp) { 251 raw_ostream &os = emitter.ostream(); 252 Block &successor = *branchOp.getSuccessor(); 253 254 for (auto pair : 255 llvm::zip(branchOp.getOperands(), successor.getArguments())) { 256 Value &operand = std::get<0>(pair); 257 BlockArgument &argument = std::get<1>(pair); 258 os << emitter.getOrCreateName(argument) << " = " 259 << emitter.getOrCreateName(operand) << ";\n"; 260 } 261 262 os << "goto "; 263 if (!(emitter.hasBlockLabel(successor))) 264 return branchOp.emitOpError("unable to find label for successor block"); 265 os << emitter.getOrCreateName(successor); 266 return success(); 267 } 268 269 static LogicalResult printOperation(CppEmitter &emitter, 270 cf::CondBranchOp condBranchOp) { 271 raw_indented_ostream &os = emitter.ostream(); 272 Block &trueSuccessor = *condBranchOp.getTrueDest(); 273 Block &falseSuccessor = *condBranchOp.getFalseDest(); 274 275 os << "if (" << emitter.getOrCreateName(condBranchOp.getCondition()) 276 << ") {\n"; 277 278 os.indent(); 279 280 // If condition is true. 281 for (auto pair : llvm::zip(condBranchOp.getTrueOperands(), 282 trueSuccessor.getArguments())) { 283 Value &operand = std::get<0>(pair); 284 BlockArgument &argument = std::get<1>(pair); 285 os << emitter.getOrCreateName(argument) << " = " 286 << emitter.getOrCreateName(operand) << ";\n"; 287 } 288 289 os << "goto "; 290 if (!(emitter.hasBlockLabel(trueSuccessor))) { 291 return condBranchOp.emitOpError("unable to find label for successor block"); 292 } 293 os << emitter.getOrCreateName(trueSuccessor) << ";\n"; 294 os.unindent() << "} else {\n"; 295 os.indent(); 296 // If condition is false. 297 for (auto pair : llvm::zip(condBranchOp.getFalseOperands(), 298 falseSuccessor.getArguments())) { 299 Value &operand = std::get<0>(pair); 300 BlockArgument &argument = std::get<1>(pair); 301 os << emitter.getOrCreateName(argument) << " = " 302 << emitter.getOrCreateName(operand) << ";\n"; 303 } 304 305 os << "goto "; 306 if (!(emitter.hasBlockLabel(falseSuccessor))) { 307 return condBranchOp.emitOpError() 308 << "unable to find label for successor block"; 309 } 310 os << emitter.getOrCreateName(falseSuccessor) << ";\n"; 311 os.unindent() << "}"; 312 return success(); 313 } 314 315 static LogicalResult printOperation(CppEmitter &emitter, func::CallOp callOp) { 316 if (failed(emitter.emitAssignPrefix(*callOp.getOperation()))) 317 return failure(); 318 319 raw_ostream &os = emitter.ostream(); 320 os << callOp.getCallee() << "("; 321 if (failed(emitter.emitOperands(*callOp.getOperation()))) 322 return failure(); 323 os << ")"; 324 return success(); 325 } 326 327 static LogicalResult printOperation(CppEmitter &emitter, emitc::CallOp callOp) { 328 raw_ostream &os = emitter.ostream(); 329 Operation &op = *callOp.getOperation(); 330 331 if (failed(emitter.emitAssignPrefix(op))) 332 return failure(); 333 os << callOp.callee(); 334 335 auto emitArgs = [&](Attribute attr) -> LogicalResult { 336 if (auto t = attr.dyn_cast<IntegerAttr>()) { 337 // Index attributes are treated specially as operand index. 338 if (t.getType().isIndex()) { 339 int64_t idx = t.getInt(); 340 if ((idx < 0) || (idx >= op.getNumOperands())) 341 return op.emitOpError("invalid operand index"); 342 if (!emitter.hasValueInScope(op.getOperand(idx))) 343 return op.emitOpError("operand ") 344 << idx << "'s value not defined in scope"; 345 os << emitter.getOrCreateName(op.getOperand(idx)); 346 return success(); 347 } 348 } 349 if (failed(emitter.emitAttribute(op.getLoc(), attr))) 350 return failure(); 351 352 return success(); 353 }; 354 355 if (callOp.template_args()) { 356 os << "<"; 357 if (failed(interleaveCommaWithError(*callOp.template_args(), os, emitArgs))) 358 return failure(); 359 os << ">"; 360 } 361 362 os << "("; 363 364 LogicalResult emittedArgs = 365 callOp.args() ? interleaveCommaWithError(*callOp.args(), os, emitArgs) 366 : emitter.emitOperands(op); 367 if (failed(emittedArgs)) 368 return failure(); 369 os << ")"; 370 return success(); 371 } 372 373 static LogicalResult printOperation(CppEmitter &emitter, 374 emitc::ApplyOp applyOp) { 375 raw_ostream &os = emitter.ostream(); 376 Operation &op = *applyOp.getOperation(); 377 378 if (failed(emitter.emitAssignPrefix(op))) 379 return failure(); 380 os << applyOp.applicableOperator(); 381 os << emitter.getOrCreateName(applyOp.getOperand()); 382 383 return success(); 384 } 385 386 static LogicalResult printOperation(CppEmitter &emitter, 387 emitc::IncludeOp includeOp) { 388 raw_ostream &os = emitter.ostream(); 389 390 os << "#include "; 391 if (includeOp.is_standard_include()) 392 os << "<" << includeOp.include() << ">"; 393 else 394 os << "\"" << includeOp.include() << "\""; 395 396 return success(); 397 } 398 399 static LogicalResult printOperation(CppEmitter &emitter, scf::ForOp forOp) { 400 401 raw_indented_ostream &os = emitter.ostream(); 402 403 OperandRange operands = forOp.getIterOperands(); 404 Block::BlockArgListType iterArgs = forOp.getRegionIterArgs(); 405 Operation::result_range results = forOp.getResults(); 406 407 if (!emitter.shouldDeclareVariablesAtTop()) { 408 for (OpResult result : results) { 409 if (failed(emitter.emitVariableDeclaration(result, 410 /*trailingSemicolon=*/true))) 411 return failure(); 412 } 413 } 414 415 for (auto pair : llvm::zip(iterArgs, operands)) { 416 if (failed(emitter.emitType(forOp.getLoc(), std::get<0>(pair).getType()))) 417 return failure(); 418 os << " " << emitter.getOrCreateName(std::get<0>(pair)) << " = "; 419 os << emitter.getOrCreateName(std::get<1>(pair)) << ";"; 420 os << "\n"; 421 } 422 423 os << "for ("; 424 if (failed( 425 emitter.emitType(forOp.getLoc(), forOp.getInductionVar().getType()))) 426 return failure(); 427 os << " "; 428 os << emitter.getOrCreateName(forOp.getInductionVar()); 429 os << " = "; 430 os << emitter.getOrCreateName(forOp.getLowerBound()); 431 os << "; "; 432 os << emitter.getOrCreateName(forOp.getInductionVar()); 433 os << " < "; 434 os << emitter.getOrCreateName(forOp.getUpperBound()); 435 os << "; "; 436 os << emitter.getOrCreateName(forOp.getInductionVar()); 437 os << " += "; 438 os << emitter.getOrCreateName(forOp.getStep()); 439 os << ") {\n"; 440 os.indent(); 441 442 Region &forRegion = forOp.getRegion(); 443 auto regionOps = forRegion.getOps(); 444 445 // We skip the trailing yield op because this updates the result variables 446 // of the for op in the generated code. Instead we update the iterArgs at 447 // the end of a loop iteration and set the result variables after the for 448 // loop. 449 for (auto it = regionOps.begin(); std::next(it) != regionOps.end(); ++it) { 450 if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true))) 451 return failure(); 452 } 453 454 Operation *yieldOp = forRegion.getBlocks().front().getTerminator(); 455 // Copy yield operands into iterArgs at the end of a loop iteration. 456 for (auto pair : llvm::zip(iterArgs, yieldOp->getOperands())) { 457 BlockArgument iterArg = std::get<0>(pair); 458 Value operand = std::get<1>(pair); 459 os << emitter.getOrCreateName(iterArg) << " = " 460 << emitter.getOrCreateName(operand) << ";\n"; 461 } 462 463 os.unindent() << "}"; 464 465 // Copy iterArgs into results after the for loop. 466 for (auto pair : llvm::zip(results, iterArgs)) { 467 OpResult result = std::get<0>(pair); 468 BlockArgument iterArg = std::get<1>(pair); 469 os << "\n" 470 << emitter.getOrCreateName(result) << " = " 471 << emitter.getOrCreateName(iterArg) << ";"; 472 } 473 474 return success(); 475 } 476 477 static LogicalResult printOperation(CppEmitter &emitter, scf::IfOp ifOp) { 478 raw_indented_ostream &os = emitter.ostream(); 479 480 if (!emitter.shouldDeclareVariablesAtTop()) { 481 for (OpResult result : ifOp.getResults()) { 482 if (failed(emitter.emitVariableDeclaration(result, 483 /*trailingSemicolon=*/true))) 484 return failure(); 485 } 486 } 487 488 os << "if ("; 489 if (failed(emitter.emitOperands(*ifOp.getOperation()))) 490 return failure(); 491 os << ") {\n"; 492 os.indent(); 493 494 Region &thenRegion = ifOp.getThenRegion(); 495 for (Operation &op : thenRegion.getOps()) { 496 // Note: This prints a superfluous semicolon if the terminating yield op has 497 // zero results. 498 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/true))) 499 return failure(); 500 } 501 502 os.unindent() << "}"; 503 504 Region &elseRegion = ifOp.getElseRegion(); 505 if (!elseRegion.empty()) { 506 os << " else {\n"; 507 os.indent(); 508 509 for (Operation &op : elseRegion.getOps()) { 510 // Note: This prints a superfluous semicolon if the terminating yield op 511 // has zero results. 512 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/true))) 513 return failure(); 514 } 515 516 os.unindent() << "}"; 517 } 518 519 return success(); 520 } 521 522 static LogicalResult printOperation(CppEmitter &emitter, scf::YieldOp yieldOp) { 523 raw_ostream &os = emitter.ostream(); 524 Operation &parentOp = *yieldOp.getOperation()->getParentOp(); 525 526 if (yieldOp.getNumOperands() != parentOp.getNumResults()) { 527 return yieldOp.emitError("number of operands does not to match the number " 528 "of the parent op's results"); 529 } 530 531 if (failed(interleaveWithError( 532 llvm::zip(parentOp.getResults(), yieldOp.getOperands()), 533 [&](auto pair) -> LogicalResult { 534 auto result = std::get<0>(pair); 535 auto operand = std::get<1>(pair); 536 os << emitter.getOrCreateName(result) << " = "; 537 538 if (!emitter.hasValueInScope(operand)) 539 return yieldOp.emitError("operand value not in scope"); 540 os << emitter.getOrCreateName(operand); 541 return success(); 542 }, 543 [&]() { os << ";\n"; }))) 544 return failure(); 545 546 return success(); 547 } 548 549 static LogicalResult printOperation(CppEmitter &emitter, 550 func::ReturnOp returnOp) { 551 raw_ostream &os = emitter.ostream(); 552 os << "return"; 553 switch (returnOp.getNumOperands()) { 554 case 0: 555 return success(); 556 case 1: 557 os << " " << emitter.getOrCreateName(returnOp.getOperand(0)); 558 return success(emitter.hasValueInScope(returnOp.getOperand(0))); 559 default: 560 os << " std::make_tuple("; 561 if (failed(emitter.emitOperandsAndAttributes(*returnOp.getOperation()))) 562 return failure(); 563 os << ")"; 564 return success(); 565 } 566 } 567 568 static LogicalResult printOperation(CppEmitter &emitter, ModuleOp moduleOp) { 569 CppEmitter::Scope scope(emitter); 570 571 for (Operation &op : moduleOp) { 572 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false))) 573 return failure(); 574 } 575 return success(); 576 } 577 578 static LogicalResult printOperation(CppEmitter &emitter, 579 func::FuncOp functionOp) { 580 // We need to declare variables at top if the function has multiple blocks. 581 if (!emitter.shouldDeclareVariablesAtTop() && 582 functionOp.getBlocks().size() > 1) { 583 return functionOp.emitOpError( 584 "with multiple blocks needs variables declared at top"); 585 } 586 587 CppEmitter::Scope scope(emitter); 588 raw_indented_ostream &os = emitter.ostream(); 589 if (failed(emitter.emitTypes(functionOp.getLoc(), 590 functionOp.getFunctionType().getResults()))) 591 return failure(); 592 os << " " << functionOp.getName(); 593 594 os << "("; 595 if (failed(interleaveCommaWithError( 596 functionOp.getArguments(), os, 597 [&](BlockArgument arg) -> LogicalResult { 598 if (failed(emitter.emitType(functionOp.getLoc(), arg.getType()))) 599 return failure(); 600 os << " " << emitter.getOrCreateName(arg); 601 return success(); 602 }))) 603 return failure(); 604 os << ") {\n"; 605 os.indent(); 606 if (emitter.shouldDeclareVariablesAtTop()) { 607 // Declare all variables that hold op results including those from nested 608 // regions. 609 WalkResult result = 610 functionOp.walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult { 611 for (OpResult result : op->getResults()) { 612 if (failed(emitter.emitVariableDeclaration( 613 result, /*trailingSemicolon=*/true))) { 614 return WalkResult( 615 op->emitError("unable to declare result variable for op")); 616 } 617 } 618 return WalkResult::advance(); 619 }); 620 if (result.wasInterrupted()) 621 return failure(); 622 } 623 624 Region::BlockListType &blocks = functionOp.getBlocks(); 625 // Create label names for basic blocks. 626 for (Block &block : blocks) { 627 emitter.getOrCreateName(block); 628 } 629 630 // Declare variables for basic block arguments. 631 for (auto it = std::next(blocks.begin()); it != blocks.end(); ++it) { 632 Block &block = *it; 633 for (BlockArgument &arg : block.getArguments()) { 634 if (emitter.hasValueInScope(arg)) 635 return functionOp.emitOpError(" block argument #") 636 << arg.getArgNumber() << " is out of scope"; 637 if (failed( 638 emitter.emitType(block.getParentOp()->getLoc(), arg.getType()))) { 639 return failure(); 640 } 641 os << " " << emitter.getOrCreateName(arg) << ";\n"; 642 } 643 } 644 645 for (Block &block : blocks) { 646 // Only print a label if the block has predecessors. 647 if (!block.hasNoPredecessors()) { 648 if (failed(emitter.emitLabel(block))) 649 return failure(); 650 } 651 for (Operation &op : block.getOperations()) { 652 // When generating code for an scf.if or cf.cond_br op no semicolon needs 653 // to be printed after the closing brace. 654 // When generating code for an scf.for op, printing a trailing semicolon 655 // is handled within the printOperation function. 656 bool trailingSemicolon = 657 !isa<scf::IfOp, scf::ForOp, cf::CondBranchOp>(op); 658 659 if (failed(emitter.emitOperation( 660 op, /*trailingSemicolon=*/trailingSemicolon))) 661 return failure(); 662 } 663 } 664 os.unindent() << "}\n"; 665 return success(); 666 } 667 668 CppEmitter::CppEmitter(raw_ostream &os, bool declareVariablesAtTop) 669 : os(os), declareVariablesAtTop(declareVariablesAtTop) { 670 valueInScopeCount.push(0); 671 labelInScopeCount.push(0); 672 } 673 674 /// Return the existing or a new name for a Value. 675 StringRef CppEmitter::getOrCreateName(Value val) { 676 if (!valueMapper.count(val)) 677 valueMapper.insert(val, formatv("v{0}", ++valueInScopeCount.top())); 678 return *valueMapper.begin(val); 679 } 680 681 /// Return the existing or a new label for a Block. 682 StringRef CppEmitter::getOrCreateName(Block &block) { 683 if (!blockMapper.count(&block)) 684 blockMapper.insert(&block, formatv("label{0}", ++labelInScopeCount.top())); 685 return *blockMapper.begin(&block); 686 } 687 688 bool CppEmitter::shouldMapToUnsigned(IntegerType::SignednessSemantics val) { 689 switch (val) { 690 case IntegerType::Signless: 691 return false; 692 case IntegerType::Signed: 693 return false; 694 case IntegerType::Unsigned: 695 return true; 696 } 697 llvm_unreachable("Unexpected IntegerType::SignednessSemantics"); 698 } 699 700 bool CppEmitter::hasValueInScope(Value val) { return valueMapper.count(val); } 701 702 bool CppEmitter::hasBlockLabel(Block &block) { 703 return blockMapper.count(&block); 704 } 705 706 LogicalResult CppEmitter::emitAttribute(Location loc, Attribute attr) { 707 auto printInt = [&](const APInt &val, bool isUnsigned) { 708 if (val.getBitWidth() == 1) { 709 if (val.getBoolValue()) 710 os << "true"; 711 else 712 os << "false"; 713 } else { 714 SmallString<128> strValue; 715 val.toString(strValue, 10, !isUnsigned, false); 716 os << strValue; 717 } 718 }; 719 720 auto printFloat = [&](const APFloat &val) { 721 if (val.isFinite()) { 722 SmallString<128> strValue; 723 // Use default values of toString except don't truncate zeros. 724 val.toString(strValue, 0, 0, false); 725 switch (llvm::APFloatBase::SemanticsToEnum(val.getSemantics())) { 726 case llvm::APFloatBase::S_IEEEsingle: 727 os << "(float)"; 728 break; 729 case llvm::APFloatBase::S_IEEEdouble: 730 os << "(double)"; 731 break; 732 default: 733 break; 734 }; 735 os << strValue; 736 } else if (val.isNaN()) { 737 os << "NAN"; 738 } else if (val.isInfinity()) { 739 if (val.isNegative()) 740 os << "-"; 741 os << "INFINITY"; 742 } 743 }; 744 745 // Print floating point attributes. 746 if (auto fAttr = attr.dyn_cast<FloatAttr>()) { 747 printFloat(fAttr.getValue()); 748 return success(); 749 } 750 if (auto dense = attr.dyn_cast<DenseFPElementsAttr>()) { 751 os << '{'; 752 interleaveComma(dense, os, [&](const APFloat &val) { printFloat(val); }); 753 os << '}'; 754 return success(); 755 } 756 757 // Print integer attributes. 758 if (auto iAttr = attr.dyn_cast<IntegerAttr>()) { 759 if (auto iType = iAttr.getType().dyn_cast<IntegerType>()) { 760 printInt(iAttr.getValue(), shouldMapToUnsigned(iType.getSignedness())); 761 return success(); 762 } 763 if (auto iType = iAttr.getType().dyn_cast<IndexType>()) { 764 printInt(iAttr.getValue(), false); 765 return success(); 766 } 767 } 768 if (auto dense = attr.dyn_cast<DenseIntElementsAttr>()) { 769 if (auto iType = dense.getType() 770 .cast<TensorType>() 771 .getElementType() 772 .dyn_cast<IntegerType>()) { 773 os << '{'; 774 interleaveComma(dense, os, [&](const APInt &val) { 775 printInt(val, shouldMapToUnsigned(iType.getSignedness())); 776 }); 777 os << '}'; 778 return success(); 779 } 780 if (auto iType = dense.getType() 781 .cast<TensorType>() 782 .getElementType() 783 .dyn_cast<IndexType>()) { 784 os << '{'; 785 interleaveComma(dense, os, 786 [&](const APInt &val) { printInt(val, false); }); 787 os << '}'; 788 return success(); 789 } 790 } 791 792 // Print opaque attributes. 793 if (auto oAttr = attr.dyn_cast<emitc::OpaqueAttr>()) { 794 os << oAttr.getValue(); 795 return success(); 796 } 797 798 // Print symbolic reference attributes. 799 if (auto sAttr = attr.dyn_cast<SymbolRefAttr>()) { 800 if (sAttr.getNestedReferences().size() > 1) 801 return emitError(loc, "attribute has more than 1 nested reference"); 802 os << sAttr.getRootReference().getValue(); 803 return success(); 804 } 805 806 // Print type attributes. 807 if (auto type = attr.dyn_cast<TypeAttr>()) 808 return emitType(loc, type.getValue()); 809 810 return emitError(loc, "cannot emit attribute of type ") << attr.getType(); 811 } 812 813 LogicalResult CppEmitter::emitOperands(Operation &op) { 814 auto emitOperandName = [&](Value result) -> LogicalResult { 815 if (!hasValueInScope(result)) 816 return op.emitOpError() << "operand value not in scope"; 817 os << getOrCreateName(result); 818 return success(); 819 }; 820 return interleaveCommaWithError(op.getOperands(), os, emitOperandName); 821 } 822 823 LogicalResult 824 CppEmitter::emitOperandsAndAttributes(Operation &op, 825 ArrayRef<StringRef> exclude) { 826 if (failed(emitOperands(op))) 827 return failure(); 828 // Insert comma in between operands and non-filtered attributes if needed. 829 if (op.getNumOperands() > 0) { 830 for (NamedAttribute attr : op.getAttrs()) { 831 if (!llvm::is_contained(exclude, attr.getName().strref())) { 832 os << ", "; 833 break; 834 } 835 } 836 } 837 // Emit attributes. 838 auto emitNamedAttribute = [&](NamedAttribute attr) -> LogicalResult { 839 if (llvm::is_contained(exclude, attr.getName().strref())) 840 return success(); 841 os << "/* " << attr.getName().getValue() << " */"; 842 if (failed(emitAttribute(op.getLoc(), attr.getValue()))) 843 return failure(); 844 return success(); 845 }; 846 return interleaveCommaWithError(op.getAttrs(), os, emitNamedAttribute); 847 } 848 849 LogicalResult CppEmitter::emitVariableAssignment(OpResult result) { 850 if (!hasValueInScope(result)) { 851 return result.getDefiningOp()->emitOpError( 852 "result variable for the operation has not been declared"); 853 } 854 os << getOrCreateName(result) << " = "; 855 return success(); 856 } 857 858 LogicalResult CppEmitter::emitVariableDeclaration(OpResult result, 859 bool trailingSemicolon) { 860 if (hasValueInScope(result)) { 861 return result.getDefiningOp()->emitError( 862 "result variable for the operation already declared"); 863 } 864 if (failed(emitType(result.getOwner()->getLoc(), result.getType()))) 865 return failure(); 866 os << " " << getOrCreateName(result); 867 if (trailingSemicolon) 868 os << ";\n"; 869 return success(); 870 } 871 872 LogicalResult CppEmitter::emitAssignPrefix(Operation &op) { 873 switch (op.getNumResults()) { 874 case 0: 875 break; 876 case 1: { 877 OpResult result = op.getResult(0); 878 if (shouldDeclareVariablesAtTop()) { 879 if (failed(emitVariableAssignment(result))) 880 return failure(); 881 } else { 882 if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/false))) 883 return failure(); 884 os << " = "; 885 } 886 break; 887 } 888 default: 889 if (!shouldDeclareVariablesAtTop()) { 890 for (OpResult result : op.getResults()) { 891 if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/true))) 892 return failure(); 893 } 894 } 895 os << "std::tie("; 896 interleaveComma(op.getResults(), os, 897 [&](Value result) { os << getOrCreateName(result); }); 898 os << ") = "; 899 } 900 return success(); 901 } 902 903 LogicalResult CppEmitter::emitLabel(Block &block) { 904 if (!hasBlockLabel(block)) 905 return block.getParentOp()->emitError("label for block not found"); 906 // FIXME: Add feature in `raw_indented_ostream` to ignore indent for block 907 // label instead of using `getOStream`. 908 os.getOStream() << getOrCreateName(block) << ":\n"; 909 return success(); 910 } 911 912 LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) { 913 LogicalResult status = 914 llvm::TypeSwitch<Operation *, LogicalResult>(&op) 915 // Builtin ops. 916 .Case<ModuleOp>([&](auto op) { return printOperation(*this, op); }) 917 // CF ops. 918 .Case<cf::BranchOp, cf::CondBranchOp>( 919 [&](auto op) { return printOperation(*this, op); }) 920 // EmitC ops. 921 .Case<emitc::ApplyOp, emitc::CallOp, emitc::ConstantOp, 922 emitc::IncludeOp, emitc::VariableOp>( 923 [&](auto op) { return printOperation(*this, op); }) 924 // Func ops. 925 .Case<func::CallOp, func::ConstantOp, func::FuncOp, func::ReturnOp>( 926 [&](auto op) { return printOperation(*this, op); }) 927 // SCF ops. 928 .Case<scf::ForOp, scf::IfOp, scf::YieldOp>( 929 [&](auto op) { return printOperation(*this, op); }) 930 // Arithmetic ops. 931 .Case<arith::ConstantOp>( 932 [&](auto op) { return printOperation(*this, op); }) 933 .Default([&](Operation *) { 934 return op.emitOpError("unable to find printer for op"); 935 }); 936 937 if (failed(status)) 938 return failure(); 939 os << (trailingSemicolon ? ";\n" : "\n"); 940 return success(); 941 } 942 943 LogicalResult CppEmitter::emitType(Location loc, Type type) { 944 if (auto iType = type.dyn_cast<IntegerType>()) { 945 switch (iType.getWidth()) { 946 case 1: 947 return (os << "bool"), success(); 948 case 8: 949 case 16: 950 case 32: 951 case 64: 952 if (shouldMapToUnsigned(iType.getSignedness())) 953 return (os << "uint" << iType.getWidth() << "_t"), success(); 954 else 955 return (os << "int" << iType.getWidth() << "_t"), success(); 956 default: 957 return emitError(loc, "cannot emit integer type ") << type; 958 } 959 } 960 if (auto fType = type.dyn_cast<FloatType>()) { 961 switch (fType.getWidth()) { 962 case 32: 963 return (os << "float"), success(); 964 case 64: 965 return (os << "double"), success(); 966 default: 967 return emitError(loc, "cannot emit float type ") << type; 968 } 969 } 970 if (auto iType = type.dyn_cast<IndexType>()) 971 return (os << "size_t"), success(); 972 if (auto tType = type.dyn_cast<TensorType>()) { 973 if (!tType.hasRank()) 974 return emitError(loc, "cannot emit unranked tensor type"); 975 if (!tType.hasStaticShape()) 976 return emitError(loc, "cannot emit tensor type with non static shape"); 977 os << "Tensor<"; 978 if (failed(emitType(loc, tType.getElementType()))) 979 return failure(); 980 auto shape = tType.getShape(); 981 for (auto dimSize : shape) { 982 os << ", "; 983 os << dimSize; 984 } 985 os << ">"; 986 return success(); 987 } 988 if (auto tType = type.dyn_cast<TupleType>()) 989 return emitTupleType(loc, tType.getTypes()); 990 if (auto oType = type.dyn_cast<emitc::OpaqueType>()) { 991 os << oType.getValue(); 992 return success(); 993 } 994 if (auto pType = type.dyn_cast<emitc::PointerType>()) { 995 if (failed(emitType(loc, pType.getPointee()))) 996 return failure(); 997 os << "*"; 998 return success(); 999 } 1000 return emitError(loc, "cannot emit type ") << type; 1001 } 1002 1003 LogicalResult CppEmitter::emitTypes(Location loc, ArrayRef<Type> types) { 1004 switch (types.size()) { 1005 case 0: 1006 os << "void"; 1007 return success(); 1008 case 1: 1009 return emitType(loc, types.front()); 1010 default: 1011 return emitTupleType(loc, types); 1012 } 1013 } 1014 1015 LogicalResult CppEmitter::emitTupleType(Location loc, ArrayRef<Type> types) { 1016 os << "std::tuple<"; 1017 if (failed(interleaveCommaWithError( 1018 types, os, [&](Type type) { return emitType(loc, type); }))) 1019 return failure(); 1020 os << ">"; 1021 return success(); 1022 } 1023 1024 LogicalResult emitc::translateToCpp(Operation *op, raw_ostream &os, 1025 bool declareVariablesAtTop) { 1026 CppEmitter emitter(os, declareVariablesAtTop); 1027 return emitter.emitOperation(*op, /*trailingSemicolon=*/false); 1028 } 1029