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