llvm-ld.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
  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 utility is intended to be compatible with GCC, and follows standard
  11. // system 'ld' conventions. As such, the default output file is ./a.out.
  12. // Additionally, this program outputs a shell script that is used to invoke LLI
  13. // to execute the program. In this manner, the generated executable (a.out for
  14. // example), is directly executable, whereas the bitcode file actually lives in
  15. // the a.out.bc file generated by this program. Also, Force is on by default.
  16. //
  17. // Note that if someone (or a script) deletes the executable program generated,
  18. // the .bc file will be left around. Considering that this is a temporary hack,
  19. // I'm not too worried about this.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/LinkAllVMCore.h"
  23. #include "llvm/Linker.h"
  24. #include "llvm/System/Program.h"
  25. #include "llvm/Module.h"
  26. #include "llvm/PassManager.h"
  27. #include "llvm/Bitcode/ReaderWriter.h"
  28. #include "llvm/Target/TargetData.h"
  29. #include "llvm/Target/TargetMachine.h"
  30. #include "llvm/Target/TargetMachineRegistry.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/FileUtilities.h"
  33. #include "llvm/Support/ManagedStatic.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/Streams.h"
  36. #include "llvm/Support/SystemUtils.h"
  37. #include "llvm/System/Signals.h"
  38. #include <fstream>
  39. #include <memory>
  40. #include <cstring>
  41. using namespace llvm;
  42. // Input/Output Options
  43. static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
  44. cl::desc("<input bitcode files>"));
  45. static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
  46. cl::desc("Override output filename"),
  47. cl::value_desc("filename"));
  48. static cl::opt<bool> Verbose("v",
  49. cl::desc("Print information about actions taken"));
  50. static cl::list<std::string> LibPaths("L", cl::Prefix,
  51. cl::desc("Specify a library search path"),
  52. cl::value_desc("directory"));
  53. static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
  54. cl::desc("Specify a framework search path"),
  55. cl::value_desc("directory"));
  56. static cl::list<std::string> Libraries("l", cl::Prefix,
  57. cl::desc("Specify libraries to link to"),
  58. cl::value_desc("library prefix"));
  59. static cl::list<std::string> Frameworks("framework",
  60. cl::desc("Specify frameworks to link to"),
  61. cl::value_desc("framework"));
  62. // Options to control the linking, optimization, and code gen processes
  63. static cl::opt<bool> LinkAsLibrary("link-as-library",
  64. cl::desc("Link the .bc files together as a library, not an executable"));
  65. static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
  66. cl::desc("Alias for -link-as-library"));
  67. static cl::opt<bool> Native("native",
  68. cl::desc("Generate a native binary instead of a shell script"));
  69. static cl::opt<bool>NativeCBE("native-cbe",
  70. cl::desc("Generate a native binary with the C backend and GCC"));
  71. static cl::list<std::string> PostLinkOpts("post-link-opts",
  72. cl::value_desc("path"),
  73. cl::desc("Run one or more optimization programs after linking"));
  74. static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
  75. cl::desc("Pass options to the system linker"));
  76. // Compatibility options that llvm-ld ignores but are supported for
  77. // compatibility with LD
  78. static cl::opt<std::string> CO3("soname", cl::Hidden,
  79. cl::desc("Compatibility option: ignored"));
  80. static cl::opt<std::string> CO4("version-script", cl::Hidden,
  81. cl::desc("Compatibility option: ignored"));
  82. static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
  83. cl::desc("Compatibility option: ignored"));
  84. static cl::opt<std::string> CO6("h", cl::Hidden,
  85. cl::desc("Compatibility option: ignored"));
  86. static cl::opt<bool> CO7("start-group", cl::Hidden,
  87. cl::desc("Compatibility option: ignored"));
  88. static cl::opt<bool> CO8("end-group", cl::Hidden,
  89. cl::desc("Compatibility option: ignored"));
  90. /// This is just for convenience so it doesn't have to be passed around
  91. /// everywhere.
  92. static std::string progname;
  93. /// PrintAndExit - Prints a message to standard error and exits with error code
  94. ///
  95. /// Inputs:
  96. /// Message - The message to print to standard error.
  97. ///
  98. static void PrintAndExit(const std::string &Message, int errcode = 1) {
  99. cerr << progname << ": " << Message << "\n";
  100. llvm_shutdown();
  101. exit(errcode);
  102. }
  103. static void PrintCommand(const std::vector<const char*> &args) {
  104. std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
  105. for (; I != E; ++I)
  106. if (*I)
  107. cout << "'" << *I << "'" << " ";
  108. cout << "\n" << std::flush;
  109. }
  110. /// CopyEnv - This function takes an array of environment variables and makes a
  111. /// copy of it. This copy can then be manipulated any way the caller likes
  112. /// without affecting the process's real environment.
  113. ///
  114. /// Inputs:
  115. /// envp - An array of C strings containing an environment.
  116. ///
  117. /// Return value:
  118. /// NULL - An error occurred.
  119. ///
  120. /// Otherwise, a pointer to a new array of C strings is returned. Every string
  121. /// in the array is a duplicate of the one in the original array (i.e. we do
  122. /// not copy the char *'s from one array to another).
  123. ///
  124. static char ** CopyEnv(char ** const envp) {
  125. // Count the number of entries in the old list;
  126. unsigned entries; // The number of entries in the old environment list
  127. for (entries = 0; envp[entries] != NULL; entries++)
  128. /*empty*/;
  129. // Add one more entry for the NULL pointer that ends the list.
  130. ++entries;
  131. // If there are no entries at all, just return NULL.
  132. if (entries == 0)
  133. return NULL;
  134. // Allocate a new environment list.
  135. char **newenv = new char* [entries];
  136. if ((newenv = new char* [entries]) == NULL)
  137. return NULL;
  138. // Make a copy of the list. Don't forget the NULL that ends the list.
  139. entries = 0;
  140. while (envp[entries] != NULL) {
  141. newenv[entries] = new char[strlen (envp[entries]) + 1];
  142. strcpy (newenv[entries], envp[entries]);
  143. ++entries;
  144. }
  145. newenv[entries] = NULL;
  146. return newenv;
  147. }
  148. /// RemoveEnv - Remove the specified environment variable from the environment
  149. /// array.
  150. ///
  151. /// Inputs:
  152. /// name - The name of the variable to remove. It cannot be NULL.
  153. /// envp - The array of environment variables. It cannot be NULL.
  154. ///
  155. /// Notes:
  156. /// This is mainly done because functions to remove items from the environment
  157. /// are not available across all platforms. In particular, Solaris does not
  158. /// seem to have an unsetenv() function or a setenv() function (or they are
  159. /// undocumented if they do exist).
  160. ///
  161. static void RemoveEnv(const char * name, char ** const envp) {
  162. for (unsigned index=0; envp[index] != NULL; index++) {
  163. // Find the first equals sign in the array and make it an EOS character.
  164. char *p = strchr (envp[index], '=');
  165. if (p == NULL)
  166. continue;
  167. else
  168. *p = '\0';
  169. // Compare the two strings. If they are equal, zap this string.
  170. // Otherwise, restore it.
  171. if (!strcmp(name, envp[index]))
  172. *envp[index] = '\0';
  173. else
  174. *p = '=';
  175. }
  176. return;
  177. }
  178. /// GenerateBitcode - generates a bitcode file from the module provided
  179. void GenerateBitcode(Module* M, const std::string& FileName) {
  180. if (Verbose)
  181. cout << "Generating Bitcode To " << FileName << '\n';
  182. // Create the output file.
  183. std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
  184. std::ios::binary;
  185. std::ofstream Out(FileName.c_str(), io_mode);
  186. if (!Out.good())
  187. PrintAndExit("error opening '" + FileName + "' for writing!");
  188. // Ensure that the bitcode file gets removed from the disk if we get a
  189. // terminating signal.
  190. sys::RemoveFileOnSignal(sys::Path(FileName));
  191. // Write it out
  192. WriteBitcodeToFile(M, Out);
  193. // Close the bitcode file.
  194. Out.close();
  195. }
  196. /// GenerateAssembly - generates a native assembly language source file from the
  197. /// specified bitcode file.
  198. ///
  199. /// Inputs:
  200. /// InputFilename - The name of the input bitcode file.
  201. /// OutputFilename - The name of the file to generate.
  202. /// llc - The pathname to use for LLC.
  203. /// envp - The environment to use when running LLC.
  204. ///
  205. /// Return non-zero value on error.
  206. ///
  207. static int GenerateAssembly(const std::string &OutputFilename,
  208. const std::string &InputFilename,
  209. const sys::Path &llc,
  210. std::string &ErrMsg ) {
  211. // Run LLC to convert the bitcode file into assembly code.
  212. std::vector<const char*> args;
  213. args.push_back(llc.c_str());
  214. args.push_back("-f");
  215. args.push_back("-o");
  216. args.push_back(OutputFilename.c_str());
  217. args.push_back(InputFilename.c_str());
  218. args.push_back(0);
  219. if (Verbose) {
  220. cout << "Generating Assembly With: \n";
  221. PrintCommand(args);
  222. }
  223. return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
  224. }
  225. /// GenerateCFile - generates a C source file from the specified bitcode file.
  226. static int GenerateCFile(const std::string &OutputFile,
  227. const std::string &InputFile,
  228. const sys::Path &llc,
  229. std::string& ErrMsg) {
  230. // Run LLC to convert the bitcode file into C.
  231. std::vector<const char*> args;
  232. args.push_back(llc.c_str());
  233. args.push_back("-march=c");
  234. args.push_back("-f");
  235. args.push_back("-o");
  236. args.push_back(OutputFile.c_str());
  237. args.push_back(InputFile.c_str());
  238. args.push_back(0);
  239. if (Verbose) {
  240. cout << "Generating C Source With: \n";
  241. PrintCommand(args);
  242. }
  243. return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
  244. }
  245. /// GenerateNative - generates a native object file from the
  246. /// specified bitcode file.
  247. ///
  248. /// Inputs:
  249. /// InputFilename - The name of the input bitcode file.
  250. /// OutputFilename - The name of the file to generate.
  251. /// NativeLinkItems - The native libraries, files, code with which to link
  252. /// LibPaths - The list of directories in which to find libraries.
  253. /// FrameworksPaths - The list of directories in which to find frameworks.
  254. /// Frameworks - The list of frameworks (dynamic libraries)
  255. /// gcc - The pathname to use for GGC.
  256. /// envp - A copy of the process's current environment.
  257. ///
  258. /// Outputs:
  259. /// None.
  260. ///
  261. /// Returns non-zero value on error.
  262. ///
  263. static int GenerateNative(const std::string &OutputFilename,
  264. const std::string &InputFilename,
  265. const Linker::ItemList &LinkItems,
  266. const sys::Path &gcc, char ** const envp,
  267. std::string& ErrMsg) {
  268. // Remove these environment variables from the environment of the
  269. // programs that we will execute. It appears that GCC sets these
  270. // environment variables so that the programs it uses can configure
  271. // themselves identically.
  272. //
  273. // However, when we invoke GCC below, we want it to use its normal
  274. // configuration. Hence, we must sanitize its environment.
  275. char ** clean_env = CopyEnv(envp);
  276. if (clean_env == NULL)
  277. return 1;
  278. RemoveEnv("LIBRARY_PATH", clean_env);
  279. RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
  280. RemoveEnv("GCC_EXEC_PREFIX", clean_env);
  281. RemoveEnv("COMPILER_PATH", clean_env);
  282. RemoveEnv("COLLECT_GCC", clean_env);
  283. // Run GCC to assemble and link the program into native code.
  284. //
  285. // Note:
  286. // We can't just assemble and link the file with the system assembler
  287. // and linker because we don't know where to put the _start symbol.
  288. // GCC mysteriously knows how to do it.
  289. std::vector<std::string> args;
  290. args.push_back(gcc.c_str());
  291. args.push_back("-fno-strict-aliasing");
  292. args.push_back("-O3");
  293. args.push_back("-o");
  294. args.push_back(OutputFilename);
  295. args.push_back(InputFilename);
  296. // Add in the library and framework paths
  297. for (unsigned index = 0; index < LibPaths.size(); index++) {
  298. args.push_back("-L" + LibPaths[index]);
  299. }
  300. for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
  301. args.push_back("-F" + FrameworkPaths[index]);
  302. }
  303. // Add the requested options
  304. for (unsigned index = 0; index < XLinker.size(); index++)
  305. args.push_back(XLinker[index]);
  306. // Add in the libraries to link.
  307. for (unsigned index = 0; index < LinkItems.size(); index++)
  308. if (LinkItems[index].first != "crtend") {
  309. if (LinkItems[index].second)
  310. args.push_back("-l" + LinkItems[index].first);
  311. else
  312. args.push_back(LinkItems[index].first);
  313. }
  314. // Add in frameworks to link.
  315. for (unsigned index = 0; index < Frameworks.size(); index++) {
  316. args.push_back("-framework");
  317. args.push_back(Frameworks[index]);
  318. }
  319. // Now that "args" owns all the std::strings for the arguments, call the c_str
  320. // method to get the underlying string array. We do this game so that the
  321. // std::string array is guaranteed to outlive the const char* array.
  322. std::vector<const char *> Args;
  323. for (unsigned i = 0, e = args.size(); i != e; ++i)
  324. Args.push_back(args[i].c_str());
  325. Args.push_back(0);
  326. if (Verbose) {
  327. cout << "Generating Native Executable With:\n";
  328. PrintCommand(Args);
  329. }
  330. // Run the compiler to assembly and link together the program.
  331. int R = sys::Program::ExecuteAndWait(
  332. gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
  333. delete [] clean_env;
  334. return R;
  335. }
  336. /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
  337. /// bitcode file for the program.
  338. static void EmitShellScript(char **argv) {
  339. if (Verbose)
  340. cout << "Emitting Shell Script\n";
  341. #if defined(_WIN32) || defined(__CYGWIN__)
  342. // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
  343. // support windows systems, we copy the llvm-stub.exe executable from the
  344. // build tree to the destination file.
  345. std::string ErrMsg;
  346. sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
  347. if (llvmstub.isEmpty())
  348. PrintAndExit("Could not find llvm-stub.exe executable!");
  349. if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
  350. PrintAndExit(ErrMsg);
  351. return;
  352. #endif
  353. // Output the script to start the program...
  354. std::ofstream Out2(OutputFilename.c_str());
  355. if (!Out2.good())
  356. PrintAndExit("error opening '" + OutputFilename + "' for writing!");
  357. Out2 << "#!/bin/sh\n";
  358. // Allow user to setenv LLVMINTERP if lli is not in their PATH.
  359. Out2 << "lli=${LLVMINTERP-lli}\n";
  360. Out2 << "exec $lli \\\n";
  361. // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
  362. LibPaths.push_back("/lib");
  363. LibPaths.push_back("/usr/lib");
  364. LibPaths.push_back("/usr/X11R6/lib");
  365. // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
  366. // shared object at all! See RH 8: plain text.
  367. std::vector<std::string>::iterator libc =
  368. std::find(Libraries.begin(), Libraries.end(), "c");
  369. if (libc != Libraries.end()) Libraries.erase(libc);
  370. // List all the shared object (native) libraries this executable will need
  371. // on the command line, so that we don't have to do this manually!
  372. for (std::vector<std::string>::iterator i = Libraries.begin(),
  373. e = Libraries.end(); i != e; ++i) {
  374. sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
  375. if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
  376. Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
  377. }
  378. Out2 << " $0.bc ${1+\"$@\"}\n";
  379. Out2.close();
  380. }
  381. // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
  382. // linker function by combining the Files and Libraries in the order they were
  383. // declared on the command line.
  384. static void BuildLinkItems(
  385. Linker::ItemList& Items,
  386. const cl::list<std::string>& Files,
  387. const cl::list<std::string>& Libraries) {
  388. // Build the list of linkage items for LinkItems.
  389. cl::list<std::string>::const_iterator fileIt = Files.begin();
  390. cl::list<std::string>::const_iterator libIt = Libraries.begin();
  391. int libPos = -1, filePos = -1;
  392. while ( libIt != Libraries.end() || fileIt != Files.end() ) {
  393. if (libIt != Libraries.end())
  394. libPos = Libraries.getPosition(libIt - Libraries.begin());
  395. else
  396. libPos = -1;
  397. if (fileIt != Files.end())
  398. filePos = Files.getPosition(fileIt - Files.begin());
  399. else
  400. filePos = -1;
  401. if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
  402. // Add a source file
  403. Items.push_back(std::make_pair(*fileIt++, false));
  404. } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
  405. // Add a library
  406. Items.push_back(std::make_pair(*libIt++, true));
  407. }
  408. }
  409. }
  410. // Rightly this should go in a header file but it just seems such a waste.
  411. namespace llvm {
  412. extern void Optimize(Module*);
  413. }
  414. int main(int argc, char **argv, char **envp) {
  415. llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
  416. try {
  417. // Initial global variable above for convenience printing of program name.
  418. progname = sys::Path(argv[0]).getBasename();
  419. // Parse the command line options
  420. cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
  421. sys::PrintStackTraceOnErrorSignal();
  422. // Construct a Linker (now that Verbose is set)
  423. Linker TheLinker(progname, OutputFilename, Verbose);
  424. // Keep track of the native link items (versus the bitcode items)
  425. Linker::ItemList NativeLinkItems;
  426. // Add library paths to the linker
  427. TheLinker.addPaths(LibPaths);
  428. TheLinker.addSystemPaths();
  429. // Remove any consecutive duplicates of the same library...
  430. Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
  431. Libraries.end());
  432. if (LinkAsLibrary) {
  433. std::vector<sys::Path> Files;
  434. for (unsigned i = 0; i < InputFilenames.size(); ++i )
  435. Files.push_back(sys::Path(InputFilenames[i]));
  436. if (TheLinker.LinkInFiles(Files))
  437. return 1; // Error already printed
  438. // The libraries aren't linked in but are noted as "dependent" in the
  439. // module.
  440. for (cl::list<std::string>::const_iterator I = Libraries.begin(),
  441. E = Libraries.end(); I != E ; ++I) {
  442. TheLinker.getModule()->addLibrary(*I);
  443. }
  444. } else {
  445. // Build a list of the items from our command line
  446. Linker::ItemList Items;
  447. BuildLinkItems(Items, InputFilenames, Libraries);
  448. // Link all the items together
  449. if (TheLinker.LinkInItems(Items, NativeLinkItems) )
  450. return 1; // Error already printed
  451. }
  452. std::auto_ptr<Module> Composite(TheLinker.releaseModule());
  453. // Optimize the module
  454. Optimize(Composite.get());
  455. // Generate the bitcode for the optimized module.
  456. std::string RealBitcodeOutput = OutputFilename;
  457. if (!LinkAsLibrary) RealBitcodeOutput += ".bc";
  458. GenerateBitcode(Composite.get(), RealBitcodeOutput);
  459. // If we are not linking a library, generate either a native executable
  460. // or a JIT shell script, depending upon what the user wants.
  461. if (!LinkAsLibrary) {
  462. // If the user wants to run a post-link optimization, run it now.
  463. if (!PostLinkOpts.empty()) {
  464. std::vector<std::string> opts = PostLinkOpts;
  465. for (std::vector<std::string>::iterator I = opts.begin(),
  466. E = opts.end(); I != E; ++I) {
  467. sys::Path prog(*I);
  468. if (!prog.canExecute()) {
  469. prog = sys::Program::FindProgramByName(*I);
  470. if (prog.isEmpty())
  471. PrintAndExit(std::string("Optimization program '") + *I +
  472. "' is not found or not executable.");
  473. }
  474. // Get the program arguments
  475. sys::Path tmp_output("opt_result");
  476. std::string ErrMsg;
  477. if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
  478. PrintAndExit(ErrMsg);
  479. const char* args[4];
  480. args[0] = I->c_str();
  481. args[1] = RealBitcodeOutput.c_str();
  482. args[2] = tmp_output.c_str();
  483. args[3] = 0;
  484. if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
  485. if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
  486. sys::Path target(RealBitcodeOutput);
  487. target.eraseFromDisk();
  488. if (tmp_output.renamePathOnDisk(target, &ErrMsg))
  489. PrintAndExit(ErrMsg, 2);
  490. } else
  491. PrintAndExit("Post-link optimization output is not bitcode");
  492. } else {
  493. PrintAndExit(ErrMsg);
  494. }
  495. }
  496. }
  497. // If the user wants to generate a native executable, compile it from the
  498. // bitcode file.
  499. //
  500. // Otherwise, create a script that will run the bitcode through the JIT.
  501. if (Native) {
  502. // Name of the Assembly Language output file
  503. sys::Path AssemblyFile ( OutputFilename);
  504. AssemblyFile.appendSuffix("s");
  505. // Mark the output files for removal if we get an interrupt.
  506. sys::RemoveFileOnSignal(AssemblyFile);
  507. sys::RemoveFileOnSignal(sys::Path(OutputFilename));
  508. // Determine the locations of the llc and gcc programs.
  509. sys::Path llc = FindExecutable("llc", argv[0]);
  510. if (llc.isEmpty())
  511. PrintAndExit("Failed to find llc");
  512. sys::Path gcc = FindExecutable("gcc", argv[0]);
  513. if (gcc.isEmpty())
  514. PrintAndExit("Failed to find gcc");
  515. // Generate an assembly language file for the bitcode.
  516. std::string ErrMsg;
  517. if (0 != GenerateAssembly(AssemblyFile.toString(), RealBitcodeOutput,
  518. llc, ErrMsg))
  519. PrintAndExit(ErrMsg);
  520. if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
  521. NativeLinkItems, gcc, envp, ErrMsg))
  522. PrintAndExit(ErrMsg);
  523. // Remove the assembly language file.
  524. AssemblyFile.eraseFromDisk();
  525. } else if (NativeCBE) {
  526. sys::Path CFile (OutputFilename);
  527. CFile.appendSuffix("cbe.c");
  528. // Mark the output files for removal if we get an interrupt.
  529. sys::RemoveFileOnSignal(CFile);
  530. sys::RemoveFileOnSignal(sys::Path(OutputFilename));
  531. // Determine the locations of the llc and gcc programs.
  532. sys::Path llc = FindExecutable("llc", argv[0]);
  533. if (llc.isEmpty())
  534. PrintAndExit("Failed to find llc");
  535. sys::Path gcc = FindExecutable("gcc", argv[0]);
  536. if (gcc.isEmpty())
  537. PrintAndExit("Failed to find gcc");
  538. // Generate an assembly language file for the bitcode.
  539. std::string ErrMsg;
  540. if (0 != GenerateCFile(
  541. CFile.toString(), RealBitcodeOutput, llc, ErrMsg))
  542. PrintAndExit(ErrMsg);
  543. if (0 != GenerateNative(OutputFilename, CFile.toString(),
  544. NativeLinkItems, gcc, envp, ErrMsg))
  545. PrintAndExit(ErrMsg);
  546. // Remove the assembly language file.
  547. CFile.eraseFromDisk();
  548. } else {
  549. EmitShellScript(argv);
  550. }
  551. // Make the script executable...
  552. std::string ErrMsg;
  553. if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
  554. PrintAndExit(ErrMsg);
  555. // Make the bitcode file readable and directly executable in LLEE as well
  556. if (sys::Path(RealBitcodeOutput).makeExecutableOnDisk(&ErrMsg))
  557. PrintAndExit(ErrMsg);
  558. if (sys::Path(RealBitcodeOutput).makeReadableOnDisk(&ErrMsg))
  559. PrintAndExit(ErrMsg);
  560. }
  561. } catch (const std::string& msg) {
  562. PrintAndExit(msg,2);
  563. } catch (...) {
  564. PrintAndExit("Unexpected unknown exception occurred.", 2);
  565. }
  566. // Graceful exit
  567. return 0;
  568. }