slang_backend.cpp revision 283a6cf32b808c703b219862ac491df3c9fc8b4b
1/* 2 * Copyright 2010-2012, The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "slang_backend.h" 18 19#include <string> 20#include <vector> 21 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/Attr.h" 24#include "clang/AST/Decl.h" 25#include "clang/AST/DeclGroup.h" 26 27#include "clang/Basic/Diagnostic.h" 28#include "clang/Basic/TargetInfo.h" 29#include "clang/Basic/TargetOptions.h" 30 31#include "clang/CodeGen/ModuleBuilder.h" 32 33#include "clang/Frontend/CodeGenOptions.h" 34#include "clang/Frontend/FrontendDiagnostic.h" 35 36#include "llvm/ADT/Twine.h" 37#include "llvm/ADT/StringExtras.h" 38 39#include "llvm/Bitcode/ReaderWriter.h" 40 41#include "llvm/CodeGen/RegAllocRegistry.h" 42#include "llvm/CodeGen/SchedulerRegistry.h" 43 44#include "llvm/IR/Constant.h" 45#include "llvm/IR/Constants.h" 46#include "llvm/IR/DataLayout.h" 47#include "llvm/IR/DebugLoc.h" 48#include "llvm/IR/DerivedTypes.h" 49#include "llvm/IR/Function.h" 50#include "llvm/IR/IRBuilder.h" 51#include "llvm/IR/IRPrintingPasses.h" 52#include "llvm/IR/LLVMContext.h" 53#include "llvm/IR/Metadata.h" 54#include "llvm/IR/Module.h" 55 56#include "llvm/Transforms/IPO/PassManagerBuilder.h" 57 58#include "llvm/Target/TargetMachine.h" 59#include "llvm/Target/TargetOptions.h" 60#include "llvm/Support/TargetRegistry.h" 61 62#include "llvm/MC/SubtargetFeature.h" 63 64#include "slang_assert.h" 65#include "slang.h" 66#include "slang_bitcode_gen.h" 67#include "slang_rs_context.h" 68#include "slang_rs_export_foreach.h" 69#include "slang_rs_export_func.h" 70#include "slang_rs_export_reduce.h" 71#include "slang_rs_export_type.h" 72#include "slang_rs_export_var.h" 73#include "slang_rs_metadata.h" 74 75#include "rs_cc_options.h" 76 77#include "strip_unknown_attributes.h" 78 79namespace slang { 80 81void Backend::CreateFunctionPasses() { 82 if (!mPerFunctionPasses) { 83 mPerFunctionPasses = new llvm::legacy::FunctionPassManager(mpModule); 84 85 llvm::PassManagerBuilder PMBuilder; 86 PMBuilder.OptLevel = mCodeGenOpts.OptimizationLevel; 87 PMBuilder.populateFunctionPassManager(*mPerFunctionPasses); 88 } 89} 90 91void Backend::CreateModulePasses() { 92 if (!mPerModulePasses) { 93 mPerModulePasses = new llvm::legacy::PassManager(); 94 95 llvm::PassManagerBuilder PMBuilder; 96 PMBuilder.OptLevel = mCodeGenOpts.OptimizationLevel; 97 PMBuilder.SizeLevel = mCodeGenOpts.OptimizeSize; 98 if (mCodeGenOpts.UnitAtATime) { 99 PMBuilder.DisableUnitAtATime = 0; 100 } else { 101 PMBuilder.DisableUnitAtATime = 1; 102 } 103 104 if (mCodeGenOpts.UnrollLoops) { 105 PMBuilder.DisableUnrollLoops = 0; 106 } else { 107 PMBuilder.DisableUnrollLoops = 1; 108 } 109 110 PMBuilder.populateModulePassManager(*mPerModulePasses); 111 // Add a pass to strip off unknown/unsupported attributes. 112 mPerModulePasses->add(createStripUnknownAttributesPass()); 113 } 114} 115 116bool Backend::CreateCodeGenPasses() { 117 if ((mOT != Slang::OT_Assembly) && (mOT != Slang::OT_Object)) 118 return true; 119 120 // Now we add passes for code emitting 121 if (mCodeGenPasses) { 122 return true; 123 } else { 124 mCodeGenPasses = new llvm::legacy::FunctionPassManager(mpModule); 125 } 126 127 // Create the TargetMachine for generating code. 128 std::string Triple = mpModule->getTargetTriple(); 129 130 std::string Error; 131 const llvm::Target* TargetInfo = 132 llvm::TargetRegistry::lookupTarget(Triple, Error); 133 if (TargetInfo == nullptr) { 134 mDiagEngine.Report(clang::diag::err_fe_unable_to_create_target) << Error; 135 return false; 136 } 137 138 // Target Machine Options 139 llvm::TargetOptions Options; 140 141 // Use soft-float ABI for ARM (which is the target used by Slang during code 142 // generation). Codegen still uses hardware FPU by default. To use software 143 // floating point, add 'soft-float' feature to FeaturesStr below. 144 Options.FloatABIType = llvm::FloatABI::Soft; 145 146 // BCC needs all unknown symbols resolved at compilation time. So we don't 147 // need any relocation model. 148 llvm::Reloc::Model RM = llvm::Reloc::Static; 149 150 // This is set for the linker (specify how large of the virtual addresses we 151 // can access for all unknown symbols.) 152 llvm::CodeModel::Model CM; 153 if (mpModule->getDataLayout().getPointerSize() == 4) { 154 CM = llvm::CodeModel::Small; 155 } else { 156 // The target may have pointer size greater than 32 (e.g. x86_64 157 // architecture) may need large data address model 158 CM = llvm::CodeModel::Medium; 159 } 160 161 // Setup feature string 162 std::string FeaturesStr; 163 if (mTargetOpts.CPU.size() || mTargetOpts.Features.size()) { 164 llvm::SubtargetFeatures Features; 165 166 for (std::vector<std::string>::const_iterator 167 I = mTargetOpts.Features.begin(), E = mTargetOpts.Features.end(); 168 I != E; 169 I++) 170 Features.AddFeature(*I); 171 172 FeaturesStr = Features.getString(); 173 } 174 175 llvm::TargetMachine *TM = 176 TargetInfo->createTargetMachine(Triple, mTargetOpts.CPU, FeaturesStr, 177 Options, RM, CM); 178 179 // Register scheduler 180 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler); 181 182 // Register allocation policy: 183 // createFastRegisterAllocator: fast but bad quality 184 // createGreedyRegisterAllocator: not so fast but good quality 185 llvm::RegisterRegAlloc::setDefault((mCodeGenOpts.OptimizationLevel == 0) ? 186 llvm::createFastRegisterAllocator : 187 llvm::createGreedyRegisterAllocator); 188 189 llvm::CodeGenOpt::Level OptLevel = llvm::CodeGenOpt::Default; 190 if (mCodeGenOpts.OptimizationLevel == 0) { 191 OptLevel = llvm::CodeGenOpt::None; 192 } else if (mCodeGenOpts.OptimizationLevel == 3) { 193 OptLevel = llvm::CodeGenOpt::Aggressive; 194 } 195 196 llvm::TargetMachine::CodeGenFileType CGFT = 197 llvm::TargetMachine::CGFT_AssemblyFile; 198 if (mOT == Slang::OT_Object) { 199 CGFT = llvm::TargetMachine::CGFT_ObjectFile; 200 } 201 if (TM->addPassesToEmitFile(*mCodeGenPasses, mBufferOutStream, 202 CGFT, OptLevel)) { 203 mDiagEngine.Report(clang::diag::err_fe_unable_to_interface_with_target); 204 return false; 205 } 206 207 return true; 208} 209 210Backend::Backend(RSContext *Context, clang::DiagnosticsEngine *DiagEngine, 211 const RSCCOptions &Opts, const clang::CodeGenOptions &CodeGenOpts, 212 const clang::TargetOptions &TargetOpts, PragmaList *Pragmas, 213 llvm::raw_ostream *OS, Slang::OutputType OT, 214 clang::SourceManager &SourceMgr, bool AllowRSPrefix, 215 bool IsFilterscript) 216 : ASTConsumer(), mTargetOpts(TargetOpts), mpModule(nullptr), mpOS(OS), 217 mOT(OT), mGen(nullptr), mPerFunctionPasses(nullptr), 218 mPerModulePasses(nullptr), mCodeGenPasses(nullptr), 219 mBufferOutStream(*mpOS), mContext(Context), 220 mSourceMgr(SourceMgr), mASTPrint(Opts.mASTPrint), mAllowRSPrefix(AllowRSPrefix), 221 mIsFilterscript(IsFilterscript), mExportVarMetadata(nullptr), 222 mExportFuncMetadata(nullptr), mExportForEachNameMetadata(nullptr), 223 mExportForEachSignatureMetadata(nullptr), 224 mExportReduceNewMetadata(nullptr), 225 mExportTypeMetadata(nullptr), mRSObjectSlotsMetadata(nullptr), 226 mRefCount(mContext->getASTContext()), 227 mASTChecker(Context, Context->getTargetAPI(), IsFilterscript), 228 mForEachHandler(Context), 229 mLLVMContext(llvm::getGlobalContext()), mDiagEngine(*DiagEngine), 230 mCodeGenOpts(CodeGenOpts), mPragmas(Pragmas) { 231 mGen = CreateLLVMCodeGen(mDiagEngine, "", mCodeGenOpts, mLLVMContext); 232} 233 234void Backend::Initialize(clang::ASTContext &Ctx) { 235 mGen->Initialize(Ctx); 236 237 mpModule = mGen->GetModule(); 238} 239 240void Backend::HandleTranslationUnit(clang::ASTContext &Ctx) { 241 HandleTranslationUnitPre(Ctx); 242 243 if (mASTPrint) 244 Ctx.getTranslationUnitDecl()->dump(); 245 246 mGen->HandleTranslationUnit(Ctx); 247 248 // Here, we complete a translation unit (whole translation unit is now in LLVM 249 // IR). Now, interact with LLVM backend to generate actual machine code (asm 250 // or machine code, whatever.) 251 252 // Silently ignore if we weren't initialized for some reason. 253 if (!mpModule) 254 return; 255 256 llvm::Module *M = mGen->ReleaseModule(); 257 if (!M) { 258 // The module has been released by IR gen on failures, do not double free. 259 mpModule = nullptr; 260 return; 261 } 262 263 slangAssert(mpModule == M && 264 "Unexpected module change during LLVM IR generation"); 265 266 // Insert #pragma information into metadata section of module 267 if (!mPragmas->empty()) { 268 llvm::NamedMDNode *PragmaMetadata = 269 mpModule->getOrInsertNamedMetadata(Slang::PragmaMetadataName); 270 for (PragmaList::const_iterator I = mPragmas->begin(), E = mPragmas->end(); 271 I != E; 272 I++) { 273 llvm::SmallVector<llvm::Metadata*, 2> Pragma; 274 // Name goes first 275 Pragma.push_back(llvm::MDString::get(mLLVMContext, I->first)); 276 // And then value 277 Pragma.push_back(llvm::MDString::get(mLLVMContext, I->second)); 278 279 // Create MDNode and insert into PragmaMetadata 280 PragmaMetadata->addOperand( 281 llvm::MDNode::get(mLLVMContext, Pragma)); 282 } 283 } 284 285 HandleTranslationUnitPost(mpModule); 286 287 // Create passes for optimization and code emission 288 289 // Create and run per-function passes 290 CreateFunctionPasses(); 291 if (mPerFunctionPasses) { 292 mPerFunctionPasses->doInitialization(); 293 294 for (llvm::Module::iterator I = mpModule->begin(), E = mpModule->end(); 295 I != E; 296 I++) 297 if (!I->isDeclaration()) 298 mPerFunctionPasses->run(*I); 299 300 mPerFunctionPasses->doFinalization(); 301 } 302 303 // Create and run module passes 304 CreateModulePasses(); 305 if (mPerModulePasses) 306 mPerModulePasses->run(*mpModule); 307 308 switch (mOT) { 309 case Slang::OT_Assembly: 310 case Slang::OT_Object: { 311 if (!CreateCodeGenPasses()) 312 return; 313 314 mCodeGenPasses->doInitialization(); 315 316 for (llvm::Module::iterator I = mpModule->begin(), E = mpModule->end(); 317 I != E; 318 I++) 319 if (!I->isDeclaration()) 320 mCodeGenPasses->run(*I); 321 322 mCodeGenPasses->doFinalization(); 323 break; 324 } 325 case Slang::OT_LLVMAssembly: { 326 llvm::legacy::PassManager *LLEmitPM = new llvm::legacy::PassManager(); 327 LLEmitPM->add(llvm::createPrintModulePass(mBufferOutStream)); 328 LLEmitPM->run(*mpModule); 329 break; 330 } 331 case Slang::OT_Bitcode: { 332 writeBitcode(mBufferOutStream, *mpModule, getTargetAPI(), 333 mCodeGenOpts.OptimizationLevel, mCodeGenOpts.getDebugInfo()); 334 break; 335 } 336 case Slang::OT_Nothing: { 337 return; 338 } 339 default: { 340 slangAssert(false && "Unknown output type"); 341 } 342 } 343 344 mBufferOutStream.flush(); 345} 346 347void Backend::HandleTagDeclDefinition(clang::TagDecl *D) { 348 mGen->HandleTagDeclDefinition(D); 349} 350 351void Backend::CompleteTentativeDefinition(clang::VarDecl *D) { 352 mGen->CompleteTentativeDefinition(D); 353} 354 355Backend::~Backend() { 356 delete mpModule; 357 delete mGen; 358 delete mPerFunctionPasses; 359 delete mPerModulePasses; 360 delete mCodeGenPasses; 361} 362 363// 1) Add zero initialization of local RS object types 364void Backend::AnnotateFunction(clang::FunctionDecl *FD) { 365 if (FD && 366 FD->hasBody() && 367 !Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) { 368 mRefCount.Init(); 369 mRefCount.SetDeclContext(FD); 370 mRefCount.Visit(FD->getBody()); 371 } 372} 373 374void Backend::LowerRSForEachCall(clang::FunctionDecl *FD) { 375 // Skip this AST walking for lower API levels. 376 if (getTargetAPI() < SLANG_N_TARGET_API) { 377 return; 378 } 379 380 if (!FD || !FD->hasBody() || 381 Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) { 382 return; 383 } 384 385 mForEachHandler.VisitStmt(FD->getBody()); 386} 387 388bool Backend::HandleTopLevelDecl(clang::DeclGroupRef D) { 389 // Find and remember the types for rs_allocation and rs_script_call_t so 390 // they can be used later for translating rsForEach() calls. 391 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); 392 (mContext->getAllocationType().isNull() || 393 mContext->getScriptCallType().isNull()) && 394 I != E; I++) { 395 if (clang::TypeDecl* TD = llvm::dyn_cast<clang::TypeDecl>(*I)) { 396 clang::StringRef TypeName = TD->getName(); 397 if (TypeName.equals("rs_allocation")) { 398 mContext->setAllocationType(TD); 399 } else if (TypeName.equals("rs_script_call_t")) { 400 mContext->setScriptCallType(TD); 401 } 402 } 403 } 404 405 // Disallow user-defined functions with prefix "rs" 406 if (!mAllowRSPrefix) { 407 // Iterate all function declarations in the program. 408 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); 409 I != E; I++) { 410 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 411 if (FD == nullptr) 412 continue; 413 if (!FD->getName().startswith("rs")) // Check prefix 414 continue; 415 if (!Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) 416 mContext->ReportError(FD->getLocation(), 417 "invalid function name prefix, " 418 "\"rs\" is reserved: '%0'") 419 << FD->getName(); 420 } 421 } 422 423 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; I++) { 424 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 425 if (FD) { 426 // Handle forward reference from pragma (see 427 // RSReducePragmaHandler::HandlePragma for backward reference). 428 mContext->markUsedByReducePragma(FD, RSContext::CheckNameYes); 429 if (FD->isGlobal()) { 430 // Check that we don't have any array parameters being misinterpreted as 431 // kernel pointers due to the C type system's array to pointer decay. 432 size_t numParams = FD->getNumParams(); 433 for (size_t i = 0; i < numParams; i++) { 434 const clang::ParmVarDecl *PVD = FD->getParamDecl(i); 435 clang::QualType QT = PVD->getOriginalType(); 436 if (QT->isArrayType()) { 437 mContext->ReportError( 438 PVD->getTypeSpecStartLoc(), 439 "exported function parameters may not have array type: %0") 440 << QT; 441 } 442 } 443 AnnotateFunction(FD); 444 } 445 } 446 447 if (getTargetAPI() >= SLANG_N_TARGET_API) { 448 if (FD && FD->hasBody() && 449 RSExportForEach::isRSForEachFunc(getTargetAPI(), FD)) { 450 // Log kernels by their names, and assign them slot numbers. 451 if (!Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) { 452 mContext->addForEach(FD); 453 } 454 } else { 455 // Look for any kernel launch calls and translate them into using the 456 // internal API. 457 // TODO: Simply ignores kernel launch inside a kernel for now. 458 // Needs more rigorous and comprehensive checks. 459 LowerRSForEachCall(FD); 460 } 461 } 462 } 463 464 return mGen->HandleTopLevelDecl(D); 465} 466 467void Backend::HandleTranslationUnitPre(clang::ASTContext &C) { 468 clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 469 470 if (!mContext->processReducePragmas(this)) 471 return; 472 473 // If we have an invalid RS/FS AST, don't check further. 474 if (!mASTChecker.Validate()) { 475 return; 476 } 477 478 if (mIsFilterscript) { 479 mContext->addPragma("rs_fp_relaxed", ""); 480 } 481 482 int version = mContext->getVersion(); 483 if (version == 0) { 484 // Not setting a version is an error 485 mDiagEngine.Report( 486 mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()), 487 mDiagEngine.getCustomDiagID( 488 clang::DiagnosticsEngine::Error, 489 "missing pragma for version in source file")); 490 } else { 491 slangAssert(version == 1); 492 } 493 494 if (mContext->getReflectJavaPackageName().empty()) { 495 mDiagEngine.Report( 496 mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()), 497 mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error, 498 "missing \"#pragma rs " 499 "java_package_name(com.foo.bar)\" " 500 "in source file")); 501 return; 502 } 503 504 // Create a static global destructor if necessary (to handle RS object 505 // runtime cleanup). 506 clang::FunctionDecl *FD = mRefCount.CreateStaticGlobalDtor(); 507 if (FD) { 508 HandleTopLevelDecl(clang::DeclGroupRef(FD)); 509 } 510 511 // Process any static function declarations 512 for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(), 513 E = TUDecl->decls_end(); I != E; I++) { 514 if ((I->getKind() >= clang::Decl::firstFunction) && 515 (I->getKind() <= clang::Decl::lastFunction)) { 516 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 517 if (FD && !FD->isGlobal()) { 518 AnnotateFunction(FD); 519 } 520 } 521 } 522} 523 524/////////////////////////////////////////////////////////////////////////////// 525void Backend::dumpExportVarInfo(llvm::Module *M) { 526 int slotCount = 0; 527 if (mExportVarMetadata == nullptr) 528 mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN); 529 530 llvm::SmallVector<llvm::Metadata *, 2> ExportVarInfo; 531 532 // We emit slot information (#rs_object_slots) for any reference counted 533 // RS type or pointer (which can also be bound). 534 535 for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(), 536 E = mContext->export_vars_end(); 537 I != E; 538 I++) { 539 const RSExportVar *EV = *I; 540 const RSExportType *ET = EV->getType(); 541 bool countsAsRSObject = false; 542 543 // Variable name 544 ExportVarInfo.push_back( 545 llvm::MDString::get(mLLVMContext, EV->getName().c_str())); 546 547 // Type name 548 switch (ET->getClass()) { 549 case RSExportType::ExportClassPrimitive: { 550 const RSExportPrimitiveType *PT = 551 static_cast<const RSExportPrimitiveType*>(ET); 552 ExportVarInfo.push_back( 553 llvm::MDString::get( 554 mLLVMContext, llvm::utostr_32(PT->getType()))); 555 if (PT->isRSObjectType()) { 556 countsAsRSObject = true; 557 } 558 break; 559 } 560 case RSExportType::ExportClassPointer: { 561 ExportVarInfo.push_back( 562 llvm::MDString::get( 563 mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET) 564 ->getPointeeType()->getName()).c_str())); 565 break; 566 } 567 case RSExportType::ExportClassMatrix: { 568 ExportVarInfo.push_back( 569 llvm::MDString::get( 570 mLLVMContext, llvm::utostr_32( 571 /* TODO Strange value. This pushes just a number, quite 572 * different than the other cases. What is this used for? 573 * These are the metadata values that some partner drivers 574 * want to reference (for TBAA, etc.). We may want to look 575 * at whether these provide any reasonable value (or have 576 * distinct enough values to actually depend on). 577 */ 578 DataTypeRSMatrix2x2 + 579 static_cast<const RSExportMatrixType*>(ET)->getDim() - 2))); 580 break; 581 } 582 case RSExportType::ExportClassVector: 583 case RSExportType::ExportClassConstantArray: 584 case RSExportType::ExportClassRecord: { 585 ExportVarInfo.push_back( 586 llvm::MDString::get(mLLVMContext, 587 EV->getType()->getName().c_str())); 588 break; 589 } 590 } 591 592 mExportVarMetadata->addOperand( 593 llvm::MDNode::get(mLLVMContext, ExportVarInfo)); 594 ExportVarInfo.clear(); 595 596 if (mRSObjectSlotsMetadata == nullptr) { 597 mRSObjectSlotsMetadata = 598 M->getOrInsertNamedMetadata(RS_OBJECT_SLOTS_MN); 599 } 600 601 if (countsAsRSObject) { 602 mRSObjectSlotsMetadata->addOperand(llvm::MDNode::get(mLLVMContext, 603 llvm::MDString::get(mLLVMContext, llvm::utostr_32(slotCount)))); 604 } 605 606 slotCount++; 607 } 608} 609 610void Backend::dumpExportFunctionInfo(llvm::Module *M) { 611 if (mExportFuncMetadata == nullptr) 612 mExportFuncMetadata = 613 M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN); 614 615 llvm::SmallVector<llvm::Metadata *, 1> ExportFuncInfo; 616 617 for (RSContext::const_export_func_iterator 618 I = mContext->export_funcs_begin(), 619 E = mContext->export_funcs_end(); 620 I != E; 621 I++) { 622 const RSExportFunc *EF = *I; 623 624 // Function name 625 if (!EF->hasParam()) { 626 ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext, 627 EF->getName().c_str())); 628 } else { 629 llvm::Function *F = M->getFunction(EF->getName()); 630 llvm::Function *HelperFunction; 631 const std::string HelperFunctionName(".helper_" + EF->getName()); 632 633 slangAssert(F && "Function marked as exported disappeared in Bitcode"); 634 635 // Create helper function 636 { 637 llvm::StructType *HelperFunctionParameterTy = nullptr; 638 std::vector<bool> isStructInput; 639 640 if (!F->getArgumentList().empty()) { 641 std::vector<llvm::Type*> HelperFunctionParameterTys; 642 for (llvm::Function::arg_iterator AI = F->arg_begin(), 643 AE = F->arg_end(); AI != AE; AI++) { 644 if (AI->getType()->isPointerTy() && AI->getType()->getPointerElementType()->isStructTy()) { 645 HelperFunctionParameterTys.push_back(AI->getType()->getPointerElementType()); 646 isStructInput.push_back(true); 647 } else { 648 HelperFunctionParameterTys.push_back(AI->getType()); 649 isStructInput.push_back(false); 650 } 651 } 652 HelperFunctionParameterTy = 653 llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys); 654 } 655 656 if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) { 657 fprintf(stderr, "Failed to export function %s: parameter type " 658 "mismatch during creation of helper function.\n", 659 EF->getName().c_str()); 660 661 const RSExportRecordType *Expected = EF->getParamPacketType(); 662 if (Expected) { 663 fprintf(stderr, "Expected:\n"); 664 Expected->getLLVMType()->dump(); 665 } 666 if (HelperFunctionParameterTy) { 667 fprintf(stderr, "Got:\n"); 668 HelperFunctionParameterTy->dump(); 669 } 670 } 671 672 std::vector<llvm::Type*> Params; 673 if (HelperFunctionParameterTy) { 674 llvm::PointerType *HelperFunctionParameterTyP = 675 llvm::PointerType::getUnqual(HelperFunctionParameterTy); 676 Params.push_back(HelperFunctionParameterTyP); 677 } 678 679 llvm::FunctionType * HelperFunctionType = 680 llvm::FunctionType::get(F->getReturnType(), 681 Params, 682 /* IsVarArgs = */false); 683 684 HelperFunction = 685 llvm::Function::Create(HelperFunctionType, 686 llvm::GlobalValue::ExternalLinkage, 687 HelperFunctionName, 688 M); 689 690 HelperFunction->addFnAttr(llvm::Attribute::NoInline); 691 HelperFunction->setCallingConv(F->getCallingConv()); 692 693 // Create helper function body 694 { 695 llvm::Argument *HelperFunctionParameter = 696 &(*HelperFunction->arg_begin()); 697 llvm::BasicBlock *BB = 698 llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction); 699 llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB); 700 llvm::SmallVector<llvm::Value*, 6> Params; 701 llvm::Value *Idx[2]; 702 703 Idx[0] = 704 llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0); 705 706 // getelementptr and load instruction for all elements in 707 // parameter .p 708 for (size_t i = 0; i < EF->getNumParameters(); i++) { 709 // getelementptr 710 Idx[1] = llvm::ConstantInt::get( 711 llvm::Type::getInt32Ty(mLLVMContext), i); 712 713 llvm::Value *Ptr = NULL; 714 715 Ptr = IB->CreateInBoundsGEP(HelperFunctionParameter, Idx); 716 717 // Load is only required for non-struct ptrs 718 if (isStructInput[i]) { 719 Params.push_back(Ptr); 720 } else { 721 llvm::Value *V = IB->CreateLoad(Ptr); 722 Params.push_back(V); 723 } 724 } 725 726 // Call and pass the all elements as parameter to F 727 llvm::CallInst *CI = IB->CreateCall(F, Params); 728 729 CI->setCallingConv(F->getCallingConv()); 730 731 if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext)) { 732 IB->CreateRetVoid(); 733 } else { 734 IB->CreateRet(CI); 735 } 736 737 delete IB; 738 } 739 } 740 741 ExportFuncInfo.push_back( 742 llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str())); 743 } 744 745 mExportFuncMetadata->addOperand( 746 llvm::MDNode::get(mLLVMContext, ExportFuncInfo)); 747 ExportFuncInfo.clear(); 748 } 749} 750 751void Backend::dumpExportForEachInfo(llvm::Module *M) { 752 if (mExportForEachNameMetadata == nullptr) { 753 mExportForEachNameMetadata = 754 M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_NAME_MN); 755 } 756 if (mExportForEachSignatureMetadata == nullptr) { 757 mExportForEachSignatureMetadata = 758 M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_MN); 759 } 760 761 llvm::SmallVector<llvm::Metadata *, 1> ExportForEachName; 762 llvm::SmallVector<llvm::Metadata *, 1> ExportForEachInfo; 763 764 for (RSContext::const_export_foreach_iterator 765 I = mContext->export_foreach_begin(), 766 E = mContext->export_foreach_end(); 767 I != E; 768 I++) { 769 const RSExportForEach *EFE = *I; 770 771 ExportForEachName.push_back( 772 llvm::MDString::get(mLLVMContext, EFE->getName().c_str())); 773 774 mExportForEachNameMetadata->addOperand( 775 llvm::MDNode::get(mLLVMContext, ExportForEachName)); 776 ExportForEachName.clear(); 777 778 ExportForEachInfo.push_back( 779 llvm::MDString::get(mLLVMContext, 780 llvm::utostr_32(EFE->getSignatureMetadata()))); 781 782 mExportForEachSignatureMetadata->addOperand( 783 llvm::MDNode::get(mLLVMContext, ExportForEachInfo)); 784 ExportForEachInfo.clear(); 785 } 786} 787 788void Backend::dumpExportReduceNewInfo(llvm::Module *M) { 789 if (!mExportReduceNewMetadata) { 790 mExportReduceNewMetadata = 791 M->getOrInsertNamedMetadata(RS_EXPORT_REDUCE_NEW_MN); 792 } 793 794 llvm::SmallVector<llvm::Metadata *, 6> ExportReduceNewInfo; 795 // Add operand to ExportReduceNewInfo, padding out missing operands with 796 // nullptr. 797 auto addOperand = [&ExportReduceNewInfo](uint32_t Idx, llvm::Metadata *N) { 798 while (Idx > ExportReduceNewInfo.size()) 799 ExportReduceNewInfo.push_back(nullptr); 800 ExportReduceNewInfo.push_back(N); 801 }; 802 // Add string operand to ExportReduceNewInfo, padding out missing operands 803 // with nullptr. 804 // If string is empty, then do not add it unless Always is true. 805 auto addString = [&addOperand, this](uint32_t Idx, const std::string &S, 806 bool Always = true) { 807 if (Always || !S.empty()) 808 addOperand(Idx, llvm::MDString::get(mLLVMContext, S)); 809 }; 810 811 // Add the description of the reduction kernels to the metadata node. 812 for (auto I = mContext->export_reduce_new_begin(), 813 E = mContext->export_reduce_new_end(); 814 I != E; ++I) { 815 ExportReduceNewInfo.clear(); 816 817 int Idx = 0; 818 819 addString(Idx++, (*I)->getNameReduce()); 820 821 addOperand(Idx++, llvm::MDString::get(mLLVMContext, llvm::utostr_32((*I)->getAccumulatorTypeSize()))); 822 823 llvm::SmallVector<llvm::Metadata *, 2> Accumulator; 824 Accumulator.push_back( 825 llvm::MDString::get(mLLVMContext, (*I)->getNameAccumulator())); 826 Accumulator.push_back(llvm::MDString::get( 827 mLLVMContext, 828 llvm::utostr_32((*I)->getAccumulatorSignatureMetadata()))); 829 addOperand(Idx++, llvm::MDTuple::get(mLLVMContext, Accumulator)); 830 831 addString(Idx++, (*I)->getNameInitializer(), false); 832 addString(Idx++, (*I)->getNameCombiner(), false); 833 addString(Idx++, (*I)->getNameOutConverter(), false); 834 addString(Idx++, (*I)->getNameHalter(), false); 835 836 mExportReduceNewMetadata->addOperand( 837 llvm::MDTuple::get(mLLVMContext, ExportReduceNewInfo)); 838 } 839} 840 841void Backend::dumpExportTypeInfo(llvm::Module *M) { 842 llvm::SmallVector<llvm::Metadata *, 1> ExportTypeInfo; 843 844 for (RSContext::const_export_type_iterator 845 I = mContext->export_types_begin(), 846 E = mContext->export_types_end(); 847 I != E; 848 I++) { 849 // First, dump type name list to export 850 const RSExportType *ET = I->getValue(); 851 852 ExportTypeInfo.clear(); 853 // Type name 854 ExportTypeInfo.push_back( 855 llvm::MDString::get(mLLVMContext, ET->getName().c_str())); 856 857 if (ET->getClass() == RSExportType::ExportClassRecord) { 858 const RSExportRecordType *ERT = 859 static_cast<const RSExportRecordType*>(ET); 860 861 if (mExportTypeMetadata == nullptr) 862 mExportTypeMetadata = 863 M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN); 864 865 mExportTypeMetadata->addOperand( 866 llvm::MDNode::get(mLLVMContext, ExportTypeInfo)); 867 868 // Now, export struct field information to %[struct name] 869 std::string StructInfoMetadataName("%"); 870 StructInfoMetadataName.append(ET->getName()); 871 llvm::NamedMDNode *StructInfoMetadata = 872 M->getOrInsertNamedMetadata(StructInfoMetadataName); 873 llvm::SmallVector<llvm::Metadata *, 3> FieldInfo; 874 875 slangAssert(StructInfoMetadata->getNumOperands() == 0 && 876 "Metadata with same name was created before"); 877 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 878 FE = ERT->fields_end(); 879 FI != FE; 880 FI++) { 881 const RSExportRecordType::Field *F = *FI; 882 883 // 1. field name 884 FieldInfo.push_back(llvm::MDString::get(mLLVMContext, 885 F->getName().c_str())); 886 887 // 2. field type name 888 FieldInfo.push_back( 889 llvm::MDString::get(mLLVMContext, 890 F->getType()->getName().c_str())); 891 892 StructInfoMetadata->addOperand( 893 llvm::MDNode::get(mLLVMContext, FieldInfo)); 894 FieldInfo.clear(); 895 } 896 } // ET->getClass() == RSExportType::ExportClassRecord 897 } 898} 899 900void Backend::HandleTranslationUnitPost(llvm::Module *M) { 901 902 if (!mContext->is64Bit()) { 903 M->setDataLayout("e-p:32:32-i64:64-v128:64:128-n32-S64"); 904 } 905 906 if (!mContext->processExports()) 907 return; 908 909 if (mContext->hasExportVar()) 910 dumpExportVarInfo(M); 911 912 if (mContext->hasExportFunc()) 913 dumpExportFunctionInfo(M); 914 915 if (mContext->hasExportForEach()) 916 dumpExportForEachInfo(M); 917 918 if (mContext->hasExportReduceNew()) 919 dumpExportReduceNewInfo(M); 920 921 if (mContext->hasExportType()) 922 dumpExportTypeInfo(M); 923} 924 925} // namespace slang 926