summaryrefslogtreecommitdiffstats
path: root/clang/Driver/LLVMCodegen.cpp
blob: b969ff81cad659ba7c2d7971e11206f7d0d6d981 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//===--- LLVMCodegen.cpp - Emit LLVM Code from ASTs -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This builds an AST and converts it to LLVM Code.
//
//===----------------------------------------------------------------------===//

#include "clang.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Sema/ASTStreamer.h"
#include "clang/AST/AST.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/Module.h"
#include <iostream>
using namespace clang;

//===----------------------------------------------------------------------===//
// LLVM Emission
//===----------------------------------------------------------------------===//

void clang::EmitLLVMFromASTs(Preprocessor &PP, unsigned MainFileID,
                             bool PrintStats) {
  Diagnostic &Diags = PP.getDiagnostics();
  // Create the streamer to read the file.
  ASTContext Context(PP.getTargetInfo(), PP.getIdentifierTable());
  ASTStreamerTy *Streamer = ASTStreamer_Init(PP, Context, MainFileID);
  
  // Create the module to codegen into.
  llvm::Module M("foo");
  
  CodeGen::BuilderTy *Builder = CodeGen::Init(Context, M);
  
  while (Decl *D = ASTStreamer_ReadTopLevelDecl(Streamer)) {
    // If an error occurred, stop code generation, but continue parsing and
    // semantic analysis (to ensure all warnings and errors are emitted).
    if (Diags.hasErrorOccurred())
      continue;
    
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
      CodeGen::CodeGenFunction(Builder, FD);
    } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
      CodeGen::CodeGenGlobalVar(Builder, FVD);
    } else {
      assert(isa<TypedefDecl>(D) && "Only expected typedefs here");
      // don't codegen for now, eventually pass down for debug info.
      //std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n";
    }
  }
  
  if (PrintStats) {
    std::cerr << "\nSTATISTICS:\n";
    CodeGen::PrintStats(Builder);
    ASTStreamer_PrintStats(Streamer);
    Context.PrintStats();
  }
  
  CodeGen::Terminate(Builder);
  ASTStreamer_Terminate(Streamer);
  
  // Print the generated code.
  M.print(std::cout);
}

OpenPOWER on IntegriCloud