cc1_main.cpp revision 206084
1//===-- cc1_main.cpp - Clang CC1 Driver -----------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This is the entry point to the clang -cc1 functionality, which implements the 11// core compiler functionality along with a number of additional tools for 12// demonstration and testing purposes. 13// 14//===----------------------------------------------------------------------===// 15 16#include "clang/Basic/Diagnostic.h" 17#include "clang/Driver/Arg.h" 18#include "clang/Driver/ArgList.h" 19#include "clang/Driver/CC1Options.h" 20#include "clang/Driver/DriverDiagnostic.h" 21#include "clang/Driver/OptTable.h" 22#include "clang/Frontend/CodeGenAction.h" 23#include "clang/Frontend/CompilerInstance.h" 24#include "clang/Frontend/CompilerInvocation.h" 25#include "clang/Frontend/FrontendActions.h" 26#include "clang/Frontend/FrontendDiagnostic.h" 27#include "clang/Frontend/FrontendPluginRegistry.h" 28#include "clang/Frontend/TextDiagnosticBuffer.h" 29#include "clang/Frontend/TextDiagnosticPrinter.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/ADT/OwningPtr.h" 32#include "llvm/ADT/Statistic.h" 33#include "llvm/Support/ErrorHandling.h" 34#include "llvm/Support/ManagedStatic.h" 35#include "llvm/Support/Timer.h" 36#include "llvm/Support/raw_ostream.h" 37#include "llvm/System/DynamicLibrary.h" 38#include "llvm/Target/TargetSelect.h" 39#include <cstdio> 40using namespace clang; 41 42//===----------------------------------------------------------------------===// 43// Main driver 44//===----------------------------------------------------------------------===// 45 46void LLVMErrorHandler(void *UserData, const std::string &Message) { 47 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData); 48 49 Diags.Report(diag::err_fe_error_backend) << Message; 50 51 // We cannot recover from llvm errors. 52 exit(1); 53} 54 55static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) { 56 using namespace clang::frontend; 57 58 switch (CI.getFrontendOpts().ProgramAction) { 59 default: 60 llvm_unreachable("Invalid program action!"); 61 62 case ASTDump: return new ASTDumpAction(); 63 case ASTPrint: return new ASTPrintAction(); 64 case ASTPrintXML: return new ASTPrintXMLAction(); 65 case ASTView: return new ASTViewAction(); 66 case DumpRawTokens: return new DumpRawTokensAction(); 67 case DumpRecordLayouts: return new DumpRecordAction(); 68 case DumpTokens: return new DumpTokensAction(); 69 case EmitAssembly: return new EmitAssemblyAction(); 70 case EmitBC: return new EmitBCAction(); 71 case EmitHTML: return new HTMLPrintAction(); 72 case EmitLLVM: return new EmitLLVMAction(); 73 case EmitLLVMOnly: return new EmitLLVMOnlyAction(); 74 case EmitObj: return new EmitObjAction(); 75 case FixIt: return new FixItAction(); 76 case GeneratePCH: return new GeneratePCHAction(); 77 case GeneratePTH: return new GeneratePTHAction(); 78 case InheritanceView: return new InheritanceViewAction(); 79 case InitOnly: return new InitOnlyAction(); 80 case ParseNoop: return new ParseOnlyAction(); 81 case ParsePrintCallbacks: return new PrintParseAction(); 82 case ParseSyntaxOnly: return new SyntaxOnlyAction(); 83 84 case PluginAction: { 85 if (CI.getFrontendOpts().ActionName == "help") { 86 llvm::errs() << "clang -cc1 plugins:\n"; 87 for (FrontendPluginRegistry::iterator it = 88 FrontendPluginRegistry::begin(), 89 ie = FrontendPluginRegistry::end(); 90 it != ie; ++it) 91 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n"; 92 return 0; 93 } 94 95 for (FrontendPluginRegistry::iterator it = 96 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end(); 97 it != ie; ++it) { 98 if (it->getName() == CI.getFrontendOpts().ActionName) 99 return it->instantiate(); 100 } 101 102 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) 103 << CI.getFrontendOpts().ActionName; 104 return 0; 105 } 106 107 case PrintDeclContext: return new DeclContextPrintAction(); 108 case PrintPreprocessedInput: return new PrintPreprocessedAction(); 109 case RewriteMacros: return new RewriteMacrosAction(); 110 case RewriteObjC: return new RewriteObjCAction(); 111 case RewriteTest: return new RewriteTestAction(); 112 case RunAnalysis: return new AnalysisAction(); 113 case RunPreprocessorOnly: return new PreprocessOnlyAction(); 114 } 115} 116 117static FrontendAction *CreateFrontendAction(CompilerInstance &CI) { 118 // Create the underlying action. 119 FrontendAction *Act = CreateFrontendBaseAction(CI); 120 if (!Act) 121 return 0; 122 123 // If there are any AST files to merge, create a frontend action 124 // adaptor to perform the merge. 125 if (!CI.getFrontendOpts().ASTMergeFiles.empty()) 126 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0], 127 CI.getFrontendOpts().ASTMergeFiles.size()); 128 129 return Act; 130} 131 132// FIXME: Define the need for this testing away. 133static int cc1_test(Diagnostic &Diags, 134 const char **ArgBegin, const char **ArgEnd) { 135 using namespace clang::driver; 136 137 llvm::errs() << "cc1 argv:"; 138 for (const char **i = ArgBegin; i != ArgEnd; ++i) 139 llvm::errs() << " \"" << *i << '"'; 140 llvm::errs() << "\n"; 141 142 // Parse the arguments. 143 OptTable *Opts = createCC1OptTable(); 144 unsigned MissingArgIndex, MissingArgCount; 145 InputArgList *Args = Opts->ParseArgs(ArgBegin, ArgEnd, 146 MissingArgIndex, MissingArgCount); 147 148 // Check for missing argument error. 149 if (MissingArgCount) 150 Diags.Report(clang::diag::err_drv_missing_argument) 151 << Args->getArgString(MissingArgIndex) << MissingArgCount; 152 153 // Dump the parsed arguments. 154 llvm::errs() << "cc1 parsed options:\n"; 155 for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 156 it != ie; ++it) 157 (*it)->dump(); 158 159 // Create a compiler invocation. 160 llvm::errs() << "cc1 creating invocation.\n"; 161 CompilerInvocation Invocation; 162 CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Diags); 163 164 // Convert the invocation back to argument strings. 165 std::vector<std::string> InvocationArgs; 166 Invocation.toArgs(InvocationArgs); 167 168 // Dump the converted arguments. 169 llvm::SmallVector<const char*, 32> Invocation2Args; 170 llvm::errs() << "invocation argv :"; 171 for (unsigned i = 0, e = InvocationArgs.size(); i != e; ++i) { 172 Invocation2Args.push_back(InvocationArgs[i].c_str()); 173 llvm::errs() << " \"" << InvocationArgs[i] << '"'; 174 } 175 llvm::errs() << "\n"; 176 177 // Convert those arguments to another invocation, and check that we got the 178 // same thing. 179 CompilerInvocation Invocation2; 180 CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(), 181 Invocation2Args.end(), Diags); 182 183 // FIXME: Implement CompilerInvocation comparison. 184 if (true) { 185 //llvm::errs() << "warning: Invocations differ!\n"; 186 187 std::vector<std::string> Invocation2Args; 188 Invocation2.toArgs(Invocation2Args); 189 llvm::errs() << "invocation2 argv:"; 190 for (unsigned i = 0, e = Invocation2Args.size(); i != e; ++i) 191 llvm::errs() << " \"" << Invocation2Args[i] << '"'; 192 llvm::errs() << "\n"; 193 } 194 195 return 0; 196} 197 198int cc1_main(const char **ArgBegin, const char **ArgEnd, 199 const char *Argv0, void *MainAddr) { 200 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 201 202 Clang->setLLVMContext(new llvm::LLVMContext); 203 204 // Run clang -cc1 test. 205 if (ArgBegin != ArgEnd && llvm::StringRef(ArgBegin[0]) == "-cc1test") { 206 TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions()); 207 Diagnostic Diags(&DiagClient); 208 return cc1_test(Diags, ArgBegin + 1, ArgEnd); 209 } 210 211 // Initialize targets first, so that --version shows registered targets. 212 llvm::InitializeAllTargets(); 213 llvm::InitializeAllAsmPrinters(); 214 215 // Buffer diagnostics from argument parsing so that we can output them using a 216 // well formed diagnostic object. 217 TextDiagnosticBuffer DiagsBuffer; 218 Diagnostic Diags(&DiagsBuffer); 219 CompilerInvocation::CreateFromArgs(Clang->getInvocation(), ArgBegin, ArgEnd, 220 Diags); 221 222 // Infer the builtin include path if unspecified. 223 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && 224 Clang->getHeaderSearchOpts().ResourceDir.empty()) 225 Clang->getHeaderSearchOpts().ResourceDir = 226 CompilerInvocation::GetResourcesPath(Argv0, MainAddr); 227 228 // Honor -help. 229 if (Clang->getFrontendOpts().ShowHelp) { 230 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable()); 231 Opts->PrintHelp(llvm::outs(), "clang -cc1", 232 "LLVM 'Clang' Compiler: http://clang.llvm.org"); 233 return 0; 234 } 235 236 // Honor -version. 237 // 238 // FIXME: Use a better -version message? 239 if (Clang->getFrontendOpts().ShowVersion) { 240 llvm::cl::PrintVersionMessage(); 241 return 0; 242 } 243 244 // Create the actual diagnostics engine. 245 Clang->createDiagnostics(ArgEnd - ArgBegin, const_cast<char**>(ArgBegin)); 246 if (!Clang->hasDiagnostics()) 247 return 1; 248 249 // Set an error handler, so that any LLVM backend diagnostics go through our 250 // error handler. 251 llvm::llvm_install_error_handler(LLVMErrorHandler, 252 static_cast<void*>(&Clang->getDiagnostics())); 253 254 DiagsBuffer.FlushDiagnostics(Clang->getDiagnostics()); 255 256 // Load any requested plugins. 257 for (unsigned i = 0, 258 e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) { 259 const std::string &Path = Clang->getFrontendOpts().Plugins[i]; 260 std::string Error; 261 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error)) 262 Diags.Report(diag::err_fe_unable_to_load_plugin) << Path << Error; 263 } 264 265 // If there were errors in processing arguments, don't do anything else. 266 bool Success = false; 267 if (!Clang->getDiagnostics().getNumErrors()) { 268 // Create and execute the frontend action. 269 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang)); 270 if (Act) { 271 Success = Clang->ExecuteAction(*Act); 272 if (Clang->getFrontendOpts().DisableFree) 273 Act.take(); 274 } 275 } 276 277 // If any timers were active but haven't been destroyed yet, print their 278 // results now. This happens in -disable-free mode. 279 llvm::TimerGroup::printAll(llvm::errs()); 280 281 // When running with -disable-free, don't do any destruction or shutdown. 282 if (Clang->getFrontendOpts().DisableFree) { 283 if (Clang->getFrontendOpts().ShowStats) 284 llvm::PrintStatistics(); 285 Clang.take(); 286 return !Success; 287 } 288 289 // Managed static deconstruction. Useful for making things like 290 // -time-passes usable. 291 llvm::llvm_shutdown(); 292 293 return !Success; 294} 295