slang_backend.cpp revision 5e306b944425a952fe744f59d828538137a59375
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.Visit(FD->getBody()); 370 } 371} 372 373void Backend::LowerRSForEachCall(clang::FunctionDecl *FD) { 374 // Skip this AST walking for lower API levels. 375 if (getTargetAPI() < SLANG_N_TARGET_API) { 376 return; 377 } 378 379 if (!FD || !FD->hasBody() || 380 Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) { 381 return; 382 } 383 384 mForEachHandler.VisitStmt(FD->getBody()); 385} 386 387bool Backend::HandleTopLevelDecl(clang::DeclGroupRef D) { 388 // Find and remember the types for rs_allocation and rs_script_call_t so 389 // they can be used later for translating rsForEach() calls. 390 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); 391 (mContext->getAllocationType().isNull() || 392 mContext->getScriptCallType().isNull()) && 393 I != E; I++) { 394 if (clang::TypeDecl* TD = llvm::dyn_cast<clang::TypeDecl>(*I)) { 395 clang::StringRef TypeName = TD->getName(); 396 if (TypeName.equals("rs_allocation")) { 397 mContext->setAllocationType(TD); 398 } else if (TypeName.equals("rs_script_call_t")) { 399 mContext->setScriptCallType(TD); 400 } 401 } 402 } 403 404 // Disallow user-defined functions with prefix "rs" 405 if (!mAllowRSPrefix) { 406 // Iterate all function declarations in the program. 407 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); 408 I != E; I++) { 409 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 410 if (FD == nullptr) 411 continue; 412 if (!FD->getName().startswith("rs")) // Check prefix 413 continue; 414 if (!Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) 415 mContext->ReportError(FD->getLocation(), 416 "invalid function name prefix, " 417 "\"rs\" is reserved: '%0'") 418 << FD->getName(); 419 } 420 } 421 422 for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; I++) { 423 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 424 if (FD) { 425 // Handle forward reference from pragma (see 426 // RSReducePragmaHandler::HandlePragma for backward reference). 427 mContext->markUsedByReducePragma(FD, RSContext::CheckNameYes); 428 if (FD->isGlobal()) { 429 // Check that we don't have any array parameters being misinterpreted as 430 // kernel pointers due to the C type system's array to pointer decay. 431 size_t numParams = FD->getNumParams(); 432 for (size_t i = 0; i < numParams; i++) { 433 const clang::ParmVarDecl *PVD = FD->getParamDecl(i); 434 clang::QualType QT = PVD->getOriginalType(); 435 if (QT->isArrayType()) { 436 mContext->ReportError( 437 PVD->getTypeSpecStartLoc(), 438 "exported function parameters may not have array type: %0") 439 << QT; 440 } 441 } 442 AnnotateFunction(FD); 443 } 444 } 445 446 if (getTargetAPI() >= SLANG_N_TARGET_API) { 447 if (FD && FD->hasBody() && 448 RSExportForEach::isRSForEachFunc(getTargetAPI(), FD)) { 449 // Log kernels by their names, and assign them slot numbers. 450 if (!Slang::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) { 451 mContext->addForEach(FD); 452 } 453 } else { 454 // Look for any kernel launch calls and translate them into using the 455 // internal API. 456 // TODO: Simply ignores kernel launch inside a kernel for now. 457 // Needs more rigorous and comprehensive checks. 458 LowerRSForEachCall(FD); 459 } 460 } 461 } 462 463 return mGen->HandleTopLevelDecl(D); 464} 465 466void Backend::HandleTranslationUnitPre(clang::ASTContext &C) { 467 clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 468 469 if (!mContext->processReducePragmas(this)) 470 return; 471 472 // If we have an invalid RS/FS AST, don't check further. 473 if (!mASTChecker.Validate()) { 474 return; 475 } 476 477 if (mIsFilterscript) { 478 mContext->addPragma("rs_fp_relaxed", ""); 479 } 480 481 int version = mContext->getVersion(); 482 if (version == 0) { 483 // Not setting a version is an error 484 mDiagEngine.Report( 485 mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()), 486 mDiagEngine.getCustomDiagID( 487 clang::DiagnosticsEngine::Error, 488 "missing pragma for version in source file")); 489 } else { 490 slangAssert(version == 1); 491 } 492 493 if (mContext->getReflectJavaPackageName().empty()) { 494 mDiagEngine.Report( 495 mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()), 496 mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error, 497 "missing \"#pragma rs " 498 "java_package_name(com.foo.bar)\" " 499 "in source file")); 500 return; 501 } 502 503 // Create a static global destructor if necessary (to handle RS object 504 // runtime cleanup). 505 clang::FunctionDecl *FD = mRefCount.CreateStaticGlobalDtor(); 506 if (FD) { 507 HandleTopLevelDecl(clang::DeclGroupRef(FD)); 508 } 509 510 // Process any static function declarations 511 for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(), 512 E = TUDecl->decls_end(); I != E; I++) { 513 if ((I->getKind() >= clang::Decl::firstFunction) && 514 (I->getKind() <= clang::Decl::lastFunction)) { 515 clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I); 516 if (FD && !FD->isGlobal()) { 517 AnnotateFunction(FD); 518 } 519 } 520 } 521} 522 523/////////////////////////////////////////////////////////////////////////////// 524void Backend::dumpExportVarInfo(llvm::Module *M) { 525 int slotCount = 0; 526 if (mExportVarMetadata == nullptr) 527 mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN); 528 529 llvm::SmallVector<llvm::Metadata *, 2> ExportVarInfo; 530 531 // We emit slot information (#rs_object_slots) for any reference counted 532 // RS type or pointer (which can also be bound). 533 534 for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(), 535 E = mContext->export_vars_end(); 536 I != E; 537 I++) { 538 const RSExportVar *EV = *I; 539 const RSExportType *ET = EV->getType(); 540 bool countsAsRSObject = false; 541 542 // Variable name 543 ExportVarInfo.push_back( 544 llvm::MDString::get(mLLVMContext, EV->getName().c_str())); 545 546 // Type name 547 switch (ET->getClass()) { 548 case RSExportType::ExportClassPrimitive: { 549 const RSExportPrimitiveType *PT = 550 static_cast<const RSExportPrimitiveType*>(ET); 551 ExportVarInfo.push_back( 552 llvm::MDString::get( 553 mLLVMContext, llvm::utostr_32(PT->getType()))); 554 if (PT->isRSObjectType()) { 555 countsAsRSObject = true; 556 } 557 break; 558 } 559 case RSExportType::ExportClassPointer: { 560 ExportVarInfo.push_back( 561 llvm::MDString::get( 562 mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET) 563 ->getPointeeType()->getName()).c_str())); 564 break; 565 } 566 case RSExportType::ExportClassMatrix: { 567 ExportVarInfo.push_back( 568 llvm::MDString::get( 569 mLLVMContext, llvm::utostr_32( 570 /* TODO Strange value. This pushes just a number, quite 571 * different than the other cases. What is this used for? 572 * These are the metadata values that some partner drivers 573 * want to reference (for TBAA, etc.). We may want to look 574 * at whether these provide any reasonable value (or have 575 * distinct enough values to actually depend on). 576 */ 577 DataTypeRSMatrix2x2 + 578 static_cast<const RSExportMatrixType*>(ET)->getDim() - 2))); 579 break; 580 } 581 case RSExportType::ExportClassVector: 582 case RSExportType::ExportClassConstantArray: 583 case RSExportType::ExportClassRecord: { 584 ExportVarInfo.push_back( 585 llvm::MDString::get(mLLVMContext, 586 EV->getType()->getName().c_str())); 587 break; 588 } 589 } 590 591 mExportVarMetadata->addOperand( 592 llvm::MDNode::get(mLLVMContext, ExportVarInfo)); 593 ExportVarInfo.clear(); 594 595 if (mRSObjectSlotsMetadata == nullptr) { 596 mRSObjectSlotsMetadata = 597 M->getOrInsertNamedMetadata(RS_OBJECT_SLOTS_MN); 598 } 599 600 if (countsAsRSObject) { 601 mRSObjectSlotsMetadata->addOperand(llvm::MDNode::get(mLLVMContext, 602 llvm::MDString::get(mLLVMContext, llvm::utostr_32(slotCount)))); 603 } 604 605 slotCount++; 606 } 607} 608 609void Backend::dumpExportFunctionInfo(llvm::Module *M) { 610 if (mExportFuncMetadata == nullptr) 611 mExportFuncMetadata = 612 M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN); 613 614 llvm::SmallVector<llvm::Metadata *, 1> ExportFuncInfo; 615 616 for (RSContext::const_export_func_iterator 617 I = mContext->export_funcs_begin(), 618 E = mContext->export_funcs_end(); 619 I != E; 620 I++) { 621 const RSExportFunc *EF = *I; 622 623 // Function name 624 if (!EF->hasParam()) { 625 ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext, 626 EF->getName().c_str())); 627 } else { 628 llvm::Function *F = M->getFunction(EF->getName()); 629 llvm::Function *HelperFunction; 630 const std::string HelperFunctionName(".helper_" + EF->getName()); 631 632 slangAssert(F && "Function marked as exported disappeared in Bitcode"); 633 634 // Create helper function 635 { 636 llvm::StructType *HelperFunctionParameterTy = nullptr; 637 std::vector<bool> isStructInput; 638 639 if (!F->getArgumentList().empty()) { 640 std::vector<llvm::Type*> HelperFunctionParameterTys; 641 for (llvm::Function::arg_iterator AI = F->arg_begin(), 642 AE = F->arg_end(); AI != AE; AI++) { 643 if (AI->getType()->isPointerTy() && AI->getType()->getPointerElementType()->isStructTy()) { 644 HelperFunctionParameterTys.push_back(AI->getType()->getPointerElementType()); 645 isStructInput.push_back(true); 646 } else { 647 HelperFunctionParameterTys.push_back(AI->getType()); 648 isStructInput.push_back(false); 649 } 650 } 651 HelperFunctionParameterTy = 652 llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys); 653 } 654 655 if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) { 656 fprintf(stderr, "Failed to export function %s: parameter type " 657 "mismatch during creation of helper function.\n", 658 EF->getName().c_str()); 659 660 const RSExportRecordType *Expected = EF->getParamPacketType(); 661 if (Expected) { 662 fprintf(stderr, "Expected:\n"); 663 Expected->getLLVMType()->dump(); 664 } 665 if (HelperFunctionParameterTy) { 666 fprintf(stderr, "Got:\n"); 667 HelperFunctionParameterTy->dump(); 668 } 669 } 670 671 std::vector<llvm::Type*> Params; 672 if (HelperFunctionParameterTy) { 673 llvm::PointerType *HelperFunctionParameterTyP = 674 llvm::PointerType::getUnqual(HelperFunctionParameterTy); 675 Params.push_back(HelperFunctionParameterTyP); 676 } 677 678 llvm::FunctionType * HelperFunctionType = 679 llvm::FunctionType::get(F->getReturnType(), 680 Params, 681 /* IsVarArgs = */false); 682 683 HelperFunction = 684 llvm::Function::Create(HelperFunctionType, 685 llvm::GlobalValue::ExternalLinkage, 686 HelperFunctionName, 687 M); 688 689 HelperFunction->addFnAttr(llvm::Attribute::NoInline); 690 HelperFunction->setCallingConv(F->getCallingConv()); 691 692 // Create helper function body 693 { 694 llvm::Argument *HelperFunctionParameter = 695 &(*HelperFunction->arg_begin()); 696 llvm::BasicBlock *BB = 697 llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction); 698 llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB); 699 llvm::SmallVector<llvm::Value*, 6> Params; 700 llvm::Value *Idx[2]; 701 702 Idx[0] = 703 llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0); 704 705 // getelementptr and load instruction for all elements in 706 // parameter .p 707 for (size_t i = 0; i < EF->getNumParameters(); i++) { 708 // getelementptr 709 Idx[1] = llvm::ConstantInt::get( 710 llvm::Type::getInt32Ty(mLLVMContext), i); 711 712 llvm::Value *Ptr = NULL; 713 714 Ptr = IB->CreateInBoundsGEP(HelperFunctionParameter, Idx); 715 716 // Load is only required for non-struct ptrs 717 if (isStructInput[i]) { 718 Params.push_back(Ptr); 719 } else { 720 llvm::Value *V = IB->CreateLoad(Ptr); 721 Params.push_back(V); 722 } 723 } 724 725 // Call and pass the all elements as parameter to F 726 llvm::CallInst *CI = IB->CreateCall(F, Params); 727 728 CI->setCallingConv(F->getCallingConv()); 729 730 if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext)) { 731 IB->CreateRetVoid(); 732 } else { 733 IB->CreateRet(CI); 734 } 735 736 delete IB; 737 } 738 } 739 740 ExportFuncInfo.push_back( 741 llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str())); 742 } 743 744 mExportFuncMetadata->addOperand( 745 llvm::MDNode::get(mLLVMContext, ExportFuncInfo)); 746 ExportFuncInfo.clear(); 747 } 748} 749 750void Backend::dumpExportForEachInfo(llvm::Module *M) { 751 if (mExportForEachNameMetadata == nullptr) { 752 mExportForEachNameMetadata = 753 M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_NAME_MN); 754 } 755 if (mExportForEachSignatureMetadata == nullptr) { 756 mExportForEachSignatureMetadata = 757 M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_MN); 758 } 759 760 llvm::SmallVector<llvm::Metadata *, 1> ExportForEachName; 761 llvm::SmallVector<llvm::Metadata *, 1> ExportForEachInfo; 762 763 for (RSContext::const_export_foreach_iterator 764 I = mContext->export_foreach_begin(), 765 E = mContext->export_foreach_end(); 766 I != E; 767 I++) { 768 const RSExportForEach *EFE = *I; 769 770 ExportForEachName.push_back( 771 llvm::MDString::get(mLLVMContext, EFE->getName().c_str())); 772 773 mExportForEachNameMetadata->addOperand( 774 llvm::MDNode::get(mLLVMContext, ExportForEachName)); 775 ExportForEachName.clear(); 776 777 ExportForEachInfo.push_back( 778 llvm::MDString::get(mLLVMContext, 779 llvm::utostr_32(EFE->getSignatureMetadata()))); 780 781 mExportForEachSignatureMetadata->addOperand( 782 llvm::MDNode::get(mLLVMContext, ExportForEachInfo)); 783 ExportForEachInfo.clear(); 784 } 785} 786 787void Backend::dumpExportReduceNewInfo(llvm::Module *M) { 788 if (!mExportReduceNewMetadata) { 789 mExportReduceNewMetadata = 790 M->getOrInsertNamedMetadata(RS_EXPORT_REDUCE_NEW_MN); 791 } 792 793 llvm::SmallVector<llvm::Metadata *, 6> ExportReduceNewInfo; 794 // Add operand to ExportReduceNewInfo, padding out missing operands with 795 // nullptr. 796 auto addOperand = [&ExportReduceNewInfo](uint32_t Idx, llvm::Metadata *N) { 797 while (Idx > ExportReduceNewInfo.size()) 798 ExportReduceNewInfo.push_back(nullptr); 799 ExportReduceNewInfo.push_back(N); 800 }; 801 // Add string operand to ExportReduceNewInfo, padding out missing operands 802 // with nullptr. 803 // If string is empty, then do not add it unless Always is true. 804 auto addString = [&addOperand, this](uint32_t Idx, const std::string &S, 805 bool Always = true) { 806 if (Always || !S.empty()) 807 addOperand(Idx, llvm::MDString::get(mLLVMContext, S)); 808 }; 809 810 // Add the description of the reduction kernels to the metadata node. 811 for (auto I = mContext->export_reduce_new_begin(), 812 E = mContext->export_reduce_new_end(); 813 I != E; ++I) { 814 ExportReduceNewInfo.clear(); 815 816 int Idx = 0; 817 818 addString(Idx++, (*I)->getNameReduce()); 819 820 addOperand(Idx++, llvm::MDString::get(mLLVMContext, llvm::utostr_32((*I)->getAccumulatorTypeSize()))); 821 822 llvm::SmallVector<llvm::Metadata *, 2> Accumulator; 823 Accumulator.push_back( 824 llvm::MDString::get(mLLVMContext, (*I)->getNameAccumulator())); 825 Accumulator.push_back(llvm::MDString::get( 826 mLLVMContext, 827 llvm::utostr_32((*I)->getAccumulatorSignatureMetadata()))); 828 addOperand(Idx++, llvm::MDTuple::get(mLLVMContext, Accumulator)); 829 830 addString(Idx++, (*I)->getNameInitializer(), false); 831 addString(Idx++, (*I)->getNameCombiner(), false); 832 addString(Idx++, (*I)->getNameOutConverter(), false); 833 addString(Idx++, (*I)->getNameHalter(), false); 834 835 mExportReduceNewMetadata->addOperand( 836 llvm::MDTuple::get(mLLVMContext, ExportReduceNewInfo)); 837 } 838} 839 840void Backend::dumpExportTypeInfo(llvm::Module *M) { 841 llvm::SmallVector<llvm::Metadata *, 1> ExportTypeInfo; 842 843 for (RSContext::const_export_type_iterator 844 I = mContext->export_types_begin(), 845 E = mContext->export_types_end(); 846 I != E; 847 I++) { 848 // First, dump type name list to export 849 const RSExportType *ET = I->getValue(); 850 851 ExportTypeInfo.clear(); 852 // Type name 853 ExportTypeInfo.push_back( 854 llvm::MDString::get(mLLVMContext, ET->getName().c_str())); 855 856 if (ET->getClass() == RSExportType::ExportClassRecord) { 857 const RSExportRecordType *ERT = 858 static_cast<const RSExportRecordType*>(ET); 859 860 if (mExportTypeMetadata == nullptr) 861 mExportTypeMetadata = 862 M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN); 863 864 mExportTypeMetadata->addOperand( 865 llvm::MDNode::get(mLLVMContext, ExportTypeInfo)); 866 867 // Now, export struct field information to %[struct name] 868 std::string StructInfoMetadataName("%"); 869 StructInfoMetadataName.append(ET->getName()); 870 llvm::NamedMDNode *StructInfoMetadata = 871 M->getOrInsertNamedMetadata(StructInfoMetadataName); 872 llvm::SmallVector<llvm::Metadata *, 3> FieldInfo; 873 874 slangAssert(StructInfoMetadata->getNumOperands() == 0 && 875 "Metadata with same name was created before"); 876 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 877 FE = ERT->fields_end(); 878 FI != FE; 879 FI++) { 880 const RSExportRecordType::Field *F = *FI; 881 882 // 1. field name 883 FieldInfo.push_back(llvm::MDString::get(mLLVMContext, 884 F->getName().c_str())); 885 886 // 2. field type name 887 FieldInfo.push_back( 888 llvm::MDString::get(mLLVMContext, 889 F->getType()->getName().c_str())); 890 891 StructInfoMetadata->addOperand( 892 llvm::MDNode::get(mLLVMContext, FieldInfo)); 893 FieldInfo.clear(); 894 } 895 } // ET->getClass() == RSExportType::ExportClassRecord 896 } 897} 898 899void Backend::HandleTranslationUnitPost(llvm::Module *M) { 900 901 if (!mContext->is64Bit()) { 902 M->setDataLayout("e-p:32:32-i64:64-v128:64:128-n32-S64"); 903 } 904 905 if (!mContext->processExports()) 906 return; 907 908 if (mContext->hasExportVar()) 909 dumpExportVarInfo(M); 910 911 if (mContext->hasExportFunc()) 912 dumpExportFunctionInfo(M); 913 914 if (mContext->hasExportForEach()) 915 dumpExportForEachInfo(M); 916 917 if (mContext->hasExportReduceNew()) 918 dumpExportReduceNewInfo(M); 919 920 if (mContext->hasExportType()) 921 dumpExportTypeInfo(M); 922} 923 924} // namespace slang 925