Home | History | Annotate | Line # | Download | only in CodeGen
      1      1.1  joerg //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
      2      1.1  joerg //
      3      1.1  joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4      1.1  joerg // See https://llvm.org/LICENSE.txt for license information.
      5      1.1  joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6      1.1  joerg //
      7      1.1  joerg //===----------------------------------------------------------------------===//
      8      1.1  joerg //
      9      1.1  joerg // This builds an AST and converts it to LLVM Code.
     10      1.1  joerg //
     11      1.1  joerg //===----------------------------------------------------------------------===//
     12      1.1  joerg 
     13      1.1  joerg #include "clang/CodeGen/ModuleBuilder.h"
     14      1.1  joerg #include "CGDebugInfo.h"
     15      1.1  joerg #include "CodeGenModule.h"
     16      1.1  joerg #include "clang/AST/ASTContext.h"
     17      1.1  joerg #include "clang/AST/DeclObjC.h"
     18      1.1  joerg #include "clang/AST/Expr.h"
     19      1.1  joerg #include "clang/Basic/CodeGenOptions.h"
     20      1.1  joerg #include "clang/Basic/Diagnostic.h"
     21      1.1  joerg #include "clang/Basic/TargetInfo.h"
     22      1.1  joerg #include "llvm/ADT/StringRef.h"
     23      1.1  joerg #include "llvm/IR/DataLayout.h"
     24      1.1  joerg #include "llvm/IR/LLVMContext.h"
     25      1.1  joerg #include "llvm/IR/Module.h"
     26      1.1  joerg #include <memory>
     27      1.1  joerg 
     28      1.1  joerg using namespace clang;
     29      1.1  joerg using namespace CodeGen;
     30      1.1  joerg 
     31      1.1  joerg namespace {
     32      1.1  joerg   class CodeGeneratorImpl : public CodeGenerator {
     33      1.1  joerg     DiagnosticsEngine &Diags;
     34      1.1  joerg     ASTContext *Ctx;
     35      1.1  joerg     const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
     36      1.1  joerg     const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
     37      1.1  joerg     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
     38      1.1  joerg 
     39      1.1  joerg     unsigned HandlingTopLevelDecls;
     40      1.1  joerg 
     41      1.1  joerg     /// Use this when emitting decls to block re-entrant decl emission. It will
     42      1.1  joerg     /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
     43      1.1  joerg     /// emission must be deferred longer, like at the end of a tag definition.
     44      1.1  joerg     struct HandlingTopLevelDeclRAII {
     45      1.1  joerg       CodeGeneratorImpl &Self;
     46      1.1  joerg       bool EmitDeferred;
     47      1.1  joerg       HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
     48      1.1  joerg                                bool EmitDeferred = true)
     49      1.1  joerg           : Self(Self), EmitDeferred(EmitDeferred) {
     50      1.1  joerg         ++Self.HandlingTopLevelDecls;
     51      1.1  joerg       }
     52      1.1  joerg       ~HandlingTopLevelDeclRAII() {
     53      1.1  joerg         unsigned Level = --Self.HandlingTopLevelDecls;
     54      1.1  joerg         if (Level == 0 && EmitDeferred)
     55      1.1  joerg           Self.EmitDeferredDecls();
     56      1.1  joerg       }
     57      1.1  joerg     };
     58      1.1  joerg 
     59      1.1  joerg     CoverageSourceInfo *CoverageInfo;
     60      1.1  joerg 
     61      1.1  joerg   protected:
     62      1.1  joerg     std::unique_ptr<llvm::Module> M;
     63      1.1  joerg     std::unique_ptr<CodeGen::CodeGenModule> Builder;
     64      1.1  joerg 
     65      1.1  joerg   private:
     66      1.1  joerg     SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
     67      1.1  joerg 
     68      1.1  joerg     static llvm::StringRef ExpandModuleName(llvm::StringRef ModuleName,
     69      1.1  joerg                                             const CodeGenOptions &CGO) {
     70      1.1  joerg       if (ModuleName == "-" && !CGO.MainFileName.empty())
     71      1.1  joerg         return CGO.MainFileName;
     72      1.1  joerg       return ModuleName;
     73      1.1  joerg     }
     74      1.1  joerg 
     75      1.1  joerg   public:
     76      1.1  joerg     CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
     77      1.1  joerg                       const HeaderSearchOptions &HSO,
     78      1.1  joerg                       const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
     79      1.1  joerg                       llvm::LLVMContext &C,
     80      1.1  joerg                       CoverageSourceInfo *CoverageInfo = nullptr)
     81      1.1  joerg         : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
     82      1.1  joerg           PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
     83      1.1  joerg           CoverageInfo(CoverageInfo),
     84      1.1  joerg           M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
     85      1.1  joerg       C.setDiscardValueNames(CGO.DiscardValueNames);
     86      1.1  joerg     }
     87      1.1  joerg 
     88      1.1  joerg     ~CodeGeneratorImpl() override {
     89      1.1  joerg       // There should normally not be any leftover inline method definitions.
     90      1.1  joerg       assert(DeferredInlineMemberFuncDefs.empty() ||
     91      1.1  joerg              Diags.hasErrorOccurred());
     92      1.1  joerg     }
     93      1.1  joerg 
     94      1.1  joerg     CodeGenModule &CGM() {
     95      1.1  joerg       return *Builder;
     96      1.1  joerg     }
     97      1.1  joerg 
     98      1.1  joerg     llvm::Module *GetModule() {
     99      1.1  joerg       return M.get();
    100      1.1  joerg     }
    101      1.1  joerg 
    102      1.1  joerg     CGDebugInfo *getCGDebugInfo() {
    103      1.1  joerg       return Builder->getModuleDebugInfo();
    104      1.1  joerg     }
    105      1.1  joerg 
    106      1.1  joerg     llvm::Module *ReleaseModule() {
    107      1.1  joerg       return M.release();
    108      1.1  joerg     }
    109      1.1  joerg 
    110      1.1  joerg     const Decl *GetDeclForMangledName(StringRef MangledName) {
    111      1.1  joerg       GlobalDecl Result;
    112      1.1  joerg       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
    113      1.1  joerg         return nullptr;
    114      1.1  joerg       const Decl *D = Result.getCanonicalDecl().getDecl();
    115      1.1  joerg       if (auto FD = dyn_cast<FunctionDecl>(D)) {
    116      1.1  joerg         if (FD->hasBody(FD))
    117      1.1  joerg           return FD;
    118      1.1  joerg       } else if (auto TD = dyn_cast<TagDecl>(D)) {
    119      1.1  joerg         if (auto Def = TD->getDefinition())
    120      1.1  joerg           return Def;
    121      1.1  joerg       }
    122      1.1  joerg       return D;
    123      1.1  joerg     }
    124      1.1  joerg 
    125      1.1  joerg     llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
    126      1.1  joerg       return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
    127      1.1  joerg     }
    128      1.1  joerg 
    129      1.1  joerg     llvm::Module *StartModule(llvm::StringRef ModuleName,
    130      1.1  joerg                               llvm::LLVMContext &C) {
    131      1.1  joerg       assert(!M && "Replacing existing Module?");
    132      1.1  joerg       M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
    133      1.1  joerg       Initialize(*Ctx);
    134      1.1  joerg       return M.get();
    135      1.1  joerg     }
    136      1.1  joerg 
    137      1.1  joerg     void Initialize(ASTContext &Context) override {
    138      1.1  joerg       Ctx = &Context;
    139      1.1  joerg 
    140      1.1  joerg       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
    141  1.1.1.2  joerg       M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
    142      1.1  joerg       const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
    143      1.1  joerg       if (!SDKVersion.empty())
    144      1.1  joerg         M->setSDKVersion(SDKVersion);
    145      1.1  joerg       Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
    146      1.1  joerg                                                PreprocessorOpts, CodeGenOpts,
    147      1.1  joerg                                                *M, Diags, CoverageInfo));
    148      1.1  joerg 
    149      1.1  joerg       for (auto &&Lib : CodeGenOpts.DependentLibraries)
    150      1.1  joerg         Builder->AddDependentLib(Lib);
    151      1.1  joerg       for (auto &&Opt : CodeGenOpts.LinkerOptions)
    152      1.1  joerg         Builder->AppendLinkerOptions(Opt);
    153      1.1  joerg     }
    154      1.1  joerg 
    155      1.1  joerg     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
    156      1.1  joerg       if (Diags.hasErrorOccurred())
    157      1.1  joerg         return;
    158      1.1  joerg 
    159      1.1  joerg       Builder->HandleCXXStaticMemberVarInstantiation(VD);
    160      1.1  joerg     }
    161      1.1  joerg 
    162      1.1  joerg     bool HandleTopLevelDecl(DeclGroupRef DG) override {
    163      1.1  joerg       if (Diags.hasErrorOccurred())
    164      1.1  joerg         return true;
    165      1.1  joerg 
    166      1.1  joerg       HandlingTopLevelDeclRAII HandlingDecl(*this);
    167      1.1  joerg 
    168      1.1  joerg       // Make sure to emit all elements of a Decl.
    169      1.1  joerg       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
    170      1.1  joerg         Builder->EmitTopLevelDecl(*I);
    171      1.1  joerg 
    172      1.1  joerg       return true;
    173      1.1  joerg     }
    174      1.1  joerg 
    175      1.1  joerg     void EmitDeferredDecls() {
    176      1.1  joerg       if (DeferredInlineMemberFuncDefs.empty())
    177      1.1  joerg         return;
    178      1.1  joerg 
    179      1.1  joerg       // Emit any deferred inline method definitions. Note that more deferred
    180      1.1  joerg       // methods may be added during this loop, since ASTConsumer callbacks
    181      1.1  joerg       // can be invoked if AST inspection results in declarations being added.
    182      1.1  joerg       HandlingTopLevelDeclRAII HandlingDecl(*this);
    183      1.1  joerg       for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
    184      1.1  joerg         Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
    185      1.1  joerg       DeferredInlineMemberFuncDefs.clear();
    186      1.1  joerg     }
    187      1.1  joerg 
    188      1.1  joerg     void HandleInlineFunctionDefinition(FunctionDecl *D) override {
    189      1.1  joerg       if (Diags.hasErrorOccurred())
    190      1.1  joerg         return;
    191      1.1  joerg 
    192      1.1  joerg       assert(D->doesThisDeclarationHaveABody());
    193      1.1  joerg 
    194      1.1  joerg       // We may want to emit this definition. However, that decision might be
    195      1.1  joerg       // based on computing the linkage, and we have to defer that in case we
    196      1.1  joerg       // are inside of something that will change the method's final linkage,
    197      1.1  joerg       // e.g.
    198      1.1  joerg       //   typedef struct {
    199      1.1  joerg       //     void bar();
    200      1.1  joerg       //     void foo() { bar(); }
    201      1.1  joerg       //   } A;
    202      1.1  joerg       DeferredInlineMemberFuncDefs.push_back(D);
    203      1.1  joerg 
    204      1.1  joerg       // Provide some coverage mapping even for methods that aren't emitted.
    205      1.1  joerg       // Don't do this for templated classes though, as they may not be
    206      1.1  joerg       // instantiable.
    207      1.1  joerg       if (!D->getLexicalDeclContext()->isDependentContext())
    208      1.1  joerg         Builder->AddDeferredUnusedCoverageMapping(D);
    209      1.1  joerg     }
    210      1.1  joerg 
    211      1.1  joerg     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
    212      1.1  joerg     /// to (e.g. struct, union, enum, class) is completed. This allows the
    213      1.1  joerg     /// client hack on the type, which can occur at any point in the file
    214      1.1  joerg     /// (because these can be defined in declspecs).
    215      1.1  joerg     void HandleTagDeclDefinition(TagDecl *D) override {
    216      1.1  joerg       if (Diags.hasErrorOccurred())
    217      1.1  joerg         return;
    218      1.1  joerg 
    219      1.1  joerg       // Don't allow re-entrant calls to CodeGen triggered by PCH
    220      1.1  joerg       // deserialization to emit deferred decls.
    221      1.1  joerg       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
    222      1.1  joerg 
    223      1.1  joerg       Builder->UpdateCompletedType(D);
    224      1.1  joerg 
    225      1.1  joerg       // For MSVC compatibility, treat declarations of static data members with
    226      1.1  joerg       // inline initializers as definitions.
    227      1.1  joerg       if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
    228      1.1  joerg         for (Decl *Member : D->decls()) {
    229      1.1  joerg           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
    230      1.1  joerg             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
    231      1.1  joerg                 Ctx->DeclMustBeEmitted(VD)) {
    232      1.1  joerg               Builder->EmitGlobal(VD);
    233      1.1  joerg             }
    234      1.1  joerg           }
    235      1.1  joerg         }
    236      1.1  joerg       }
    237      1.1  joerg       // For OpenMP emit declare reduction functions, if required.
    238      1.1  joerg       if (Ctx->getLangOpts().OpenMP) {
    239      1.1  joerg         for (Decl *Member : D->decls()) {
    240      1.1  joerg           if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
    241      1.1  joerg             if (Ctx->DeclMustBeEmitted(DRD))
    242      1.1  joerg               Builder->EmitGlobal(DRD);
    243      1.1  joerg           } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
    244      1.1  joerg             if (Ctx->DeclMustBeEmitted(DMD))
    245      1.1  joerg               Builder->EmitGlobal(DMD);
    246      1.1  joerg           }
    247      1.1  joerg         }
    248      1.1  joerg       }
    249      1.1  joerg     }
    250      1.1  joerg 
    251      1.1  joerg     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
    252      1.1  joerg       if (Diags.hasErrorOccurred())
    253      1.1  joerg         return;
    254      1.1  joerg 
    255      1.1  joerg       // Don't allow re-entrant calls to CodeGen triggered by PCH
    256      1.1  joerg       // deserialization to emit deferred decls.
    257      1.1  joerg       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
    258      1.1  joerg 
    259      1.1  joerg       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
    260      1.1  joerg         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
    261      1.1  joerg           DI->completeRequiredType(RD);
    262      1.1  joerg     }
    263      1.1  joerg 
    264      1.1  joerg     void HandleTranslationUnit(ASTContext &Ctx) override {
    265      1.1  joerg       // Release the Builder when there is no error.
    266      1.1  joerg       if (!Diags.hasErrorOccurred() && Builder)
    267      1.1  joerg         Builder->Release();
    268      1.1  joerg 
    269      1.1  joerg       // If there are errors before or when releasing the Builder, reset
    270      1.1  joerg       // the module to stop here before invoking the backend.
    271      1.1  joerg       if (Diags.hasErrorOccurred()) {
    272      1.1  joerg         if (Builder)
    273      1.1  joerg           Builder->clear();
    274      1.1  joerg         M.reset();
    275      1.1  joerg         return;
    276      1.1  joerg       }
    277      1.1  joerg     }
    278      1.1  joerg 
    279      1.1  joerg     void AssignInheritanceModel(CXXRecordDecl *RD) override {
    280      1.1  joerg       if (Diags.hasErrorOccurred())
    281      1.1  joerg         return;
    282      1.1  joerg 
    283      1.1  joerg       Builder->RefreshTypeCacheForClass(RD);
    284      1.1  joerg     }
    285      1.1  joerg 
    286      1.1  joerg     void CompleteTentativeDefinition(VarDecl *D) override {
    287      1.1  joerg       if (Diags.hasErrorOccurred())
    288      1.1  joerg         return;
    289      1.1  joerg 
    290      1.1  joerg       Builder->EmitTentativeDefinition(D);
    291      1.1  joerg     }
    292      1.1  joerg 
    293  1.1.1.2  joerg     void CompleteExternalDeclaration(VarDecl *D) override {
    294  1.1.1.2  joerg       Builder->EmitExternalDeclaration(D);
    295  1.1.1.2  joerg     }
    296  1.1.1.2  joerg 
    297      1.1  joerg     void HandleVTable(CXXRecordDecl *RD) override {
    298      1.1  joerg       if (Diags.hasErrorOccurred())
    299      1.1  joerg         return;
    300      1.1  joerg 
    301      1.1  joerg       Builder->EmitVTable(RD);
    302      1.1  joerg     }
    303      1.1  joerg   };
    304      1.1  joerg }
    305      1.1  joerg 
    306      1.1  joerg void CodeGenerator::anchor() { }
    307      1.1  joerg 
    308      1.1  joerg CodeGenModule &CodeGenerator::CGM() {
    309      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->CGM();
    310      1.1  joerg }
    311      1.1  joerg 
    312      1.1  joerg llvm::Module *CodeGenerator::GetModule() {
    313      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->GetModule();
    314      1.1  joerg }
    315      1.1  joerg 
    316      1.1  joerg llvm::Module *CodeGenerator::ReleaseModule() {
    317      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
    318      1.1  joerg }
    319      1.1  joerg 
    320      1.1  joerg CGDebugInfo *CodeGenerator::getCGDebugInfo() {
    321      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
    322      1.1  joerg }
    323      1.1  joerg 
    324      1.1  joerg const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
    325      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
    326      1.1  joerg }
    327      1.1  joerg 
    328      1.1  joerg llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
    329      1.1  joerg                                                bool isForDefinition) {
    330      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)
    331      1.1  joerg            ->GetAddrOfGlobal(global, isForDefinition);
    332      1.1  joerg }
    333      1.1  joerg 
    334      1.1  joerg llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
    335      1.1  joerg                                          llvm::LLVMContext &C) {
    336      1.1  joerg   return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
    337      1.1  joerg }
    338      1.1  joerg 
    339      1.1  joerg CodeGenerator *clang::CreateLLVMCodeGen(
    340      1.1  joerg     DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
    341      1.1  joerg     const HeaderSearchOptions &HeaderSearchOpts,
    342      1.1  joerg     const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
    343      1.1  joerg     llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
    344      1.1  joerg   return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
    345      1.1  joerg                                PreprocessorOpts, CGO, C, CoverageInfo);
    346      1.1  joerg }
    347