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