main.cpp revision 551ae4ebd3e9d137ea668fb83ae4a55b8cfba451
1//===- llvm-mcld.cpp ------------------------------------------------------===//
2//
3//                     The MCLinker Project
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include <mcld/Module.h>
10#include <mcld/LinkerConfig.h>
11#include <mcld/LinkerScript.h>
12#include <mcld/CodeGen/TargetMachine.h>
13#include <mcld/Support/TargetSelect.h>
14#include <mcld/Support/TargetRegistry.h>
15#include <mcld/Support/CommandLine.h>
16#include <mcld/Support/Path.h>
17#include <mcld/Support/RealPath.h>
18#include <mcld/Support/MsgHandling.h>
19#include <mcld/Support/FileHandle.h>
20#include <mcld/Support/FileSystem.h>
21#include <mcld/Support/raw_ostream.h>
22#include <mcld/Support/SystemUtils.h>
23#include <mcld/Support/ToolOutputFile.h>
24#include <mcld/LD/DiagnosticLineInfo.h>
25#include <mcld/LD/TextDiagnosticPrinter.h>
26
27#include <llvm/PassManager.h>
28#include <llvm/Pass.h>
29#include <llvm/IR/Module.h>
30#include <llvm/IR/DataLayout.h>
31#include <llvm/IR/LLVMContext.h>
32#include <llvm/IRReader/IRReader.h>
33#include <llvm/ADT/Triple.h>
34#include <llvm/ADT/StringSwitch.h>
35#include <llvm/MC/SubtargetFeature.h>
36#include <llvm/Support/CommandLine.h>
37#include <llvm/Support/Debug.h>
38#include <llvm/Support/FormattedStream.h>
39#include <llvm/Support/Host.h>
40#include <llvm/Support/ManagedStatic.h>
41#include <llvm/Support/Signals.h>
42#include <llvm/Support/SourceMgr.h>
43#include <llvm/Support/TargetSelect.h>
44#include <llvm/Support/TargetRegistry.h>
45#include <llvm/Support/Process.h>
46#include <llvm/Target/TargetMachine.h>
47
48#include <iostream>
49
50using namespace std;
51
52#if defined(HAVE_UNISTD_H)
53# include <unistd.h>
54#endif
55
56#if defined(_MSC_VER) || defined(__MINGW32__)
57#include <io.h>
58#ifndef STDIN_FILENO
59# define STDIN_FILENO 0
60#endif
61#ifndef STDOUT_FILENO
62# define STDOUT_FILENO 1
63#endif
64#ifndef STDERR_FILENO
65# define STDERR_FILENO 2
66#endif
67#endif
68
69using namespace llvm;
70
71#ifdef ENABLE_UNITTEST
72#include <gtest.h>
73
74static cl::opt<bool>
75UnitTest("unittest",  cl::desc("do unit test") );
76
77int unit_test( int argc, char* argv[] )
78{
79  testing::InitGoogleTest( &argc, argv );
80  return RUN_ALL_TESTS();
81}
82
83#endif
84
85// General options for llc.  Other pass-specific options are specified
86// within the corresponding llc passes, and target-specific options
87// and back-end code generation options are specified with the target machine.
88//
89// Determine optimization level.
90static cl::opt<char>
91OptLevel("O",
92         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93                  "(default = '-O2')"),
94         cl::Prefix,
95         cl::ZeroOrMore,
96         cl::init(' '));
97
98static cl::opt<std::string>
99TargetTriple("mtriple", cl::desc("Override target triple for module"));
100
101static cl::opt<std::string>
102MArch("march", cl::desc("Architecture to generate code for (see --version)"));
103
104static cl::opt<std::string>
105MCPU("mcpu",
106  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
107  cl::value_desc("cpu-name"),
108  cl::init(""));
109
110static cl::list<std::string>
111MAttrs("mattr",
112  cl::CommaSeparated,
113  cl::desc("Target specific attributes (-mattr=help for details)"),
114  cl::value_desc("a1,+a2,-a3,..."));
115
116static cl::opt<llvm::CodeModel::Model>
117CMModel("code-model",
118        cl::desc("Choose code model"),
119        cl::init(CodeModel::Default),
120        cl::values(clEnumValN(CodeModel::Default, "default",
121                              "Target default code model"),
122                   clEnumValN(CodeModel::Small, "small",
123                              "Small code model"),
124                   clEnumValN(CodeModel::Kernel, "kernel",
125                              "Kernel code model"),
126                   clEnumValN(CodeModel::Medium, "medium",
127                              "Medium code model"),
128                   clEnumValN(CodeModel::Large, "large",
129                              "Large code model"),
130                   clEnumValEnd));
131
132cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
133                       cl::desc("Do not verify input module"));
134
135static cl::opt<bool>
136EnableFPMAD("enable-fp-mad",
137  cl::desc("Enable less precise MAD instructions to be generated"),
138  cl::init(false));
139
140static cl::opt<bool>
141DisableFPElim("disable-fp-elim",
142  cl::desc("Disable frame pointer elimination optimization"),
143  cl::init(false));
144
145static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
146FuseFPOps("fuse-fp-ops",
147  cl::desc("Enable aggresive formation of fused FP ops"),
148  cl::init(FPOpFusion::Standard),
149  cl::values(
150    clEnumValN(FPOpFusion::Fast, "fast",
151               "Fuse FP ops whenever profitable"),
152    clEnumValN(FPOpFusion::Standard, "standard",
153               "Only fuse 'blessed' FP ops."),
154    clEnumValN(FPOpFusion::Strict, "strict",
155               "Only fuse FP ops when the result won't be effected."),
156    clEnumValEnd));
157
158static cl::opt<bool>
159EnableUnsafeFPMath("enable-unsafe-fp-math",
160  cl::desc("Enable optimizations that may decrease FP precision"),
161  cl::init(false));
162
163static cl::opt<bool>
164EnableNoInfsFPMath("enable-no-infs-fp-math",
165  cl::desc("Enable FP math optimizations that assume no +-Infs"),
166  cl::init(false));
167
168static cl::opt<bool>
169EnableNoNaNsFPMath("enable-no-nans-fp-math",
170  cl::desc("Enable FP math optimizations that assume no NaNs"),
171  cl::init(false));
172
173static cl::opt<bool>
174EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
175  cl::Hidden,
176  cl::desc("Force codegen to assume rounding mode can change dynamically"),
177  cl::init(false));
178
179static cl::opt<bool>
180GenerateSoftFloatCalls("soft-float",
181  cl::desc("Generate software floating point library calls"),
182  cl::init(false));
183
184static cl::opt<llvm::FloatABI::ABIType>
185FloatABIForCalls("float-abi",
186  cl::desc("Choose float ABI type"),
187  cl::init(FloatABI::Default),
188  cl::values(
189    clEnumValN(FloatABI::Default, "default",
190               "Target default float ABI type"),
191    clEnumValN(FloatABI::Soft, "soft",
192               "Soft float ABI (implied by -soft-float)"),
193    clEnumValN(FloatABI::Hard, "hard",
194               "Hard float ABI (uses FP registers)"),
195    clEnumValEnd));
196
197static cl::opt<bool>
198DontPlaceZerosInBSS("nozero-initialized-in-bss",
199  cl::desc("Don't place zero-initialized symbols into bss section"),
200  cl::init(false));
201
202// In debug builds, make this default to true.
203#ifdef NDEBUG
204#define EMIT_DEBUG false
205#else
206#define EMIT_DEBUG true
207#endif
208static cl::opt<bool>
209EmitJitDebugInfo("jit-emit-debug",
210  cl::desc("Emit debug information to debugger"),
211  cl::init(EMIT_DEBUG));
212#undef EMIT_DEBUG
213
214static cl::opt<bool>
215EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
216  cl::Hidden,
217  cl::desc("Emit debug info objfiles to disk"),
218  cl::init(false));
219
220static cl::opt<bool>
221EnableGuaranteedTailCallOpt("tailcallopt",
222  cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
223  cl::init(false));
224
225static cl::opt<unsigned>
226OverrideStackAlignment("stack-alignment",
227  cl::desc("Override default stack alignment"),
228  cl::init(0));
229
230// --script is an alias, but cl::alias doesn't work correctly with cl::list.
231static cl::list<std::string>
232ArgLinkerScript("T",
233                cl::ZeroOrMore,
234                cl::desc("Linker script"),
235                cl::value_desc("file"));
236
237static cl::opt<std::string>
238TrapFuncName("trap-func", cl::Hidden,
239  cl::desc("Emit a call to trap function rather than a trap instruction"),
240  cl::init(""));
241
242static cl::opt<bool>
243SegmentedStacks("segmented-stacks",
244  cl::desc("Use segmented stacks if possible."),
245  cl::init(false));
246
247//===----------------------------------------------------------------------===//
248// Command Line Options
249// There are four kinds of command line options:
250//   1. Bitcode option. Used to represent a bitcode.
251//   2. Attribute options. Attributes describes the input file after them. For
252//      example, --as-needed affects the input file after this option. Attribute
253//      options are not attributes. Attribute options are the options that is
254//      used to define a legal attribute.
255//   3. Scripting options, Used to represent a subset of link scripting
256//      language, such as --defsym.
257//   4. General options. (the rest of options)
258//===----------------------------------------------------------------------===//
259// Bitcode Options
260//===----------------------------------------------------------------------===//
261static
262cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
263ArgBitcodeFilename("dB",
264                   cl::desc("set default bitcode"),
265                   cl::value_desc("bitcode"));
266
267//===----------------------------------------------------------------------===//
268// General Options
269//===----------------------------------------------------------------------===//
270static
271cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
272ArgOutputFilename("o",
273                  cl::desc("Output filename"),
274                  cl::value_desc("filename"));
275
276static cl::alias
277AliasOutputFilename("output",
278                    cl::desc("alias for -o"),
279                    cl::aliasopt(ArgOutputFilename));
280
281static
282cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
283ArgSysRoot("sysroot",
284           cl::desc("Use directory as the location of the sysroot, overriding "
285                    "the configure-time default."),
286           cl::value_desc("directory"),
287           cl::ValueRequired);
288
289static cl::list<std::string, bool, llvm::cl::SearchDirParser>
290ArgSearchDirList("L",
291  cl::ZeroOrMore,
292  cl::desc("Add path searchdir to the list of paths that ld will search for "
293           "archive libraries and ld control scripts."),
294  cl::value_desc("searchdir"),
295  cl::Prefix);
296
297static cl::alias
298ArgSearchDirListAlias("library-path",
299                      cl::desc("alias for -L"),
300                      cl::aliasopt(ArgSearchDirList));
301
302static cl::opt<bool>
303ArgTrace("t",
304         cl::desc("Print the names of the input files as ld processes them."));
305
306static cl::alias
307ArgTraceAlias("trace",
308              cl::desc("alias for -t"),
309              cl::aliasopt(ArgTrace));
310
311static cl::opt<int>
312ArgVerbose("verbose",
313           cl::init(-1),
314           cl::desc("Display the version number for ld and list the linker "
315                    "emulations supported."));
316
317static cl::opt<bool>
318ArgVersion("V",
319           cl::init(false),
320           cl::desc("Display the version number for MCLinker."));
321
322static cl::opt<int>
323ArgMaxErrorNum("error-limit",
324               cl::init(-1),
325               cl::desc("limits the maximum number of erros."));
326
327static cl::opt<int>
328ArgMaxWarnNum("warning-limit",
329               cl::init(-1),
330               cl::desc("limits the maximum number of warnings."));
331
332static cl::opt<std::string>
333ArgEntry("e",
334         cl::desc("Use entry as the explicit symbol for beginning execution of "
335                  "your program."),
336         cl::value_desc("entry"),
337         cl::ValueRequired);
338
339static cl::alias
340ArgEntryAlias("entry",
341              cl::desc("alias for -e"),
342              cl::aliasopt(ArgEntry));
343
344static cl::opt<bool>
345ArgBsymbolic("Bsymbolic",
346             cl::ZeroOrMore,
347             cl::desc("Bind references within the shared library."),
348             cl::init(false));
349
350static cl::opt<bool>
351ArgBgroup("Bgroup",
352  cl::desc("Info the dynamic linker to perform lookups only inside the group."),
353  cl::init(false));
354
355static cl::opt<std::string>
356ArgSOName("soname",
357          cl::desc("Set internal name of shared library"),
358          cl::value_desc("name"));
359
360static cl::opt<bool>
361ArgNoUndefined("no-undefined",
362               cl::ZeroOrMore,
363               cl::desc("Do not allow unresolved references"),
364               cl::init(false));
365
366static cl::opt<bool>
367ArgAllowMulDefs("allow-multiple-definition",
368                cl::desc("Allow multiple definition"),
369                cl::init(false));
370
371static cl::opt<bool>
372ArgEhFrameHdr("eh-frame-hdr",
373  cl::ZeroOrMore,
374  cl::desc("Request creation of \".eh_frame_hdr\" section and ELF \""
375           "PT_GNU_EH_FRAME\" segment header."),
376  cl::init(false));
377
378static cl::list<mcld::ZOption, bool, llvm::cl::parser<mcld::ZOption> >
379ArgZOptionList("z",
380               cl::ZeroOrMore,
381               cl::desc("The -z options for GNU ld compatibility."),
382               cl::value_desc("keyword"),
383               cl::Prefix);
384
385cl::opt<mcld::CodeGenFileType>
386ArgFileType("filetype", cl::init(mcld::CGFT_EXEFile),
387  cl::desc("Choose a file type (not all types are supported by all targets):"),
388  cl::values(
389    clEnumValN(mcld::CGFT_ASMFile, "asm",
390               "Emit an assembly ('.s') file"),
391    clEnumValN(mcld::CGFT_OBJFile, "obj",
392               "Emit a relocatable object ('.o') file"),
393    clEnumValN(mcld::CGFT_DSOFile, "dso",
394               "Emit an dynamic shared object ('.so') file"),
395    clEnumValN(mcld::CGFT_EXEFile, "exe",
396               "Emit a executable ('.exe') file"),
397    clEnumValN(mcld::CGFT_NULLFile, "null",
398               "Emit nothing, for performance testing"),
399    clEnumValEnd));
400
401static cl::opt<bool>
402ArgShared("shared",
403          cl::ZeroOrMore,
404          cl::desc("Create a shared library."),
405          cl::init(false));
406
407static cl::alias
408ArgSharedAlias("Bshareable",
409               cl::desc("alias for -shared"),
410               cl::aliasopt(ArgShared));
411
412static cl::opt<bool>
413ArgPIE("pie",
414       cl::desc("Emit a position-independent executable file"),
415       cl::init(false));
416
417static cl::opt<bool>
418ArgRelocatable("relocatable",
419               cl::desc("Generate relocatable output"),
420               cl::init(false));
421
422static cl::alias
423ArgRelocatableAlias("r",
424                    cl::desc("alias for --relocatable"),
425                    cl::aliasopt(ArgRelocatable));
426
427static cl::opt<Reloc::Model>
428ArgRelocModel("relocation-model",
429             cl::desc("Choose relocation model"),
430             cl::init(Reloc::Default),
431             cl::values(
432               clEnumValN(Reloc::Default, "default",
433                 "Target default relocation model"),
434               clEnumValN(Reloc::Static, "static",
435                 "Non-relocatable code"),
436               clEnumValN(Reloc::PIC_, "pic",
437                 "Fully relocatable, position independent code"),
438               clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
439                 "Relocatable external references, non-relocatable code"),
440               clEnumValEnd));
441
442static cl::opt<bool>
443ArgFPIC("fPIC",
444  cl::desc("Set relocation model to pic. The same as -relocation-model=pic."),
445  cl::init(false));
446
447static cl::opt<std::string>
448ArgDyld("dynamic-linker",
449        cl::ZeroOrMore,
450        cl::desc("Set the name of the dynamic linker."),
451        cl::value_desc("Program"));
452
453namespace color {
454enum Color {
455  Never,
456  Always,
457  Auto
458};
459} // namespace of color
460
461static cl::opt<color::Color>
462ArgColor("color",
463  cl::value_desc("WHEN"),
464  cl::desc("Surround the result strings with the marker"),
465  cl::init(color::Auto),
466  cl::values(
467    clEnumValN(color::Never, "never",
468      "do not surround result strings"),
469    clEnumValN(color::Always, "always",
470      "always surround result strings, even the output is a plain file"),
471    clEnumValN(color::Auto, "auto",
472      "surround result strings only if the output is a tty"),
473    clEnumValEnd));
474
475static cl::opt<bool>
476ArgDiscardLocals("discard-locals",
477                 cl::desc("Delete all temporary local symbols."),
478                 cl::init(false));
479
480static cl::alias
481ArgDiscardLocalsAlias("X",
482                      cl::desc("alias for --discard-locals"),
483                      cl::aliasopt(ArgDiscardLocals));
484
485static cl::opt<bool>
486ArgDiscardAll("discard-all",
487              cl::desc("Delete all local symbols."),
488              cl::init(false));
489
490static cl::alias
491ArgDiscardAllAlias("x",
492                   cl::desc("alias for --discard-all"),
493                   cl::aliasopt(ArgDiscardAll));
494
495static cl::opt<bool>
496ArgStripDebug("strip-debug",
497              cl::desc("Omit debug symbol information from the output file."),
498              cl::init(false));
499
500static cl::alias
501ArgStripDebugAlias("S",
502                   cl::desc("alias for --strip-debug"),
503                   cl::aliasopt(ArgStripDebug));
504
505static cl::opt<bool>
506ArgStripAll("strip-all",
507            cl::desc("Omit all symbol information from the output file."),
508            cl::init(false));
509
510static cl::alias
511ArgStripAllAlias("s",
512                 cl::desc("alias for --strip-all"),
513                 cl::aliasopt(ArgStripAll));
514
515static cl::opt<bool>
516ArgNMagic("nmagic",
517          cl::desc("Do not page align data"),
518          cl::init(false));
519
520static cl::alias
521ArgNMagicAlias("n",
522               cl::desc("alias for --nmagic"),
523               cl::aliasopt(ArgNMagic));
524
525static cl::opt<bool>
526ArgOMagic("omagic",
527          cl::desc("Do not page align data, do not make text readonly"),
528          cl::init(false));
529
530static cl::alias
531ArgOMagicAlias("N",
532               cl::desc("alias for --omagic"),
533               cl::aliasopt(ArgOMagic));
534
535
536static cl::opt<int>
537ArgGPSize("G",
538          cl::desc("Set the maximum size of objects to be optimized using GP"),
539          cl::init(8));
540
541static bool ArgGenUnwindInfo;
542
543static cl::opt<bool, true, cl::FalseParser>
544ArgNoGenUnwindInfoFlag("no-ld-generated-unwind-info",
545                       cl::ZeroOrMore, cl::location(ArgGenUnwindInfo),
546                       cl::desc("Don't create unwind info for linker generated"
547                                " sections to save size"),
548                       cl::init(false),
549                       cl::ValueDisallowed);
550static cl::opt<bool, true>
551ArgGenUnwindInfoFlag("ld-generated-unwind-info",
552                     cl::ZeroOrMore, cl::location(ArgGenUnwindInfo),
553                     cl::desc("Request creation of unwind info for linker"
554                              " generated code sections like PLT."),
555                     cl::init(true),
556                     cl::ValueDisallowed);
557
558static cl::opt<bool>
559ArgGCSections("gc-sections",
560  cl::ZeroOrMore,
561  cl::desc("Enable garbage collection of unused input sections."),
562  cl::init(false));
563
564static cl::opt<bool>
565ArgNoGCSections("no-gc-sections",
566  cl::ZeroOrMore,
567  cl::desc("disable garbage collection of unused input sections."),
568  cl::init(false));
569
570static cl::opt<std::string>
571ArgEmulation("m",
572             cl::ZeroOrMore,
573             cl::desc("Set GNU linker emulation"),
574             cl::value_desc("emulation"),
575             cl::Prefix);
576
577static cl::opt<mcld::GeneralOptions::HashStyle>
578ArgHashStyle("hash-style", cl::init(mcld::GeneralOptions::SystemV),
579  cl::desc("Set the type of linker's hash table(s)."),
580  cl::values(
581    clEnumValN(mcld::GeneralOptions::SystemV, "sysv",
582      "classic ELF .hash section"),
583    clEnumValN(mcld::GeneralOptions::GNU, "gnu",
584      "new style GNU .gnu.hash section"),
585    clEnumValN(mcld::GeneralOptions::Both, "both",
586      "both the classic ELF and new style GNU hash tables"),
587    clEnumValEnd));
588
589/// @{
590/// @{
591/// @name FIXME: begin of unsupported options
592/// @}
593
594namespace icf {
595enum Mode {
596  None,
597  All,
598  Safe
599};
600} // namespace of icf
601
602static cl::opt<icf::Mode>
603ArgICF("icf",
604  cl::ZeroOrMore,
605  cl::desc("Identical Code Folding"),
606  cl::init(icf::None),
607  cl::values(
608    clEnumValN(icf::None, "none",
609      "do not perform cold folding"),
610    clEnumValN(icf::All, "all",
611      "always preform cold folding"),
612    clEnumValN(icf::Safe, "safe",
613      "Folds ctors, dtors and functions whose pointers are definitely not "
614      "taken."),
615    clEnumValEnd));
616
617// FIXME: add this to target options?
618static cl::opt<bool>
619ArgFIXCA8("fix-cortex-a8",
620          cl::desc("Enable Cortex-A8 Thumb-2 branch erratum fix"),
621          cl::init(false));
622
623static cl::opt<bool>
624ArgExportDynamic("export-dynamic",
625                 cl::desc("Export all dynamic symbols"),
626                 cl::init(false));
627
628static cl::alias
629ArgExportDynamicAlias("E",
630                      cl::desc("alias for --export-dynamic"),
631                      cl::aliasopt(ArgExportDynamic));
632
633static cl::list<std::string, bool, llvm::cl::SearchDirParser>
634ArgRuntimePathLink("rpath-link",
635  cl::ZeroOrMore,
636  cl::desc("Add a directory to the link time library search path"),
637  cl::value_desc("dir"));
638
639static cl::list<std::string>
640ArgExcludeLIBS("exclude-libs",
641               cl::CommaSeparated,
642               cl::desc("Exclude libraries from automatic export"),
643               cl::value_desc("lib1,lib2,..."));
644
645static cl::opt<std::string>
646ArgBuildID("build-id",
647  cl::desc("Request creation of \".note.gnu.build-id\" ELF note section."),
648  cl::value_desc("style"),
649  cl::ValueOptional);
650
651static cl::opt<std::string>
652ArgForceUndefined("u",
653                  cl::desc("Force symbol to be undefined in the output file"),
654                  cl::value_desc("symbol"));
655
656static cl::alias
657ArgForceUndefinedAlias("undefined",
658                       cl::desc("alias for -u"),
659                       cl::aliasopt(ArgForceUndefined));
660
661static cl::opt<std::string>
662ArgVersionScript("version-script",
663                 cl::desc("Version script."),
664                 cl::value_desc("Version script"));
665
666static cl::opt<bool>
667ArgWarnCommon("warn-common",
668              cl::desc("warn common symbol"),
669              cl::init(false));
670
671static cl::opt<std::string>
672ArgFilter("F",
673          cl::desc("Filter for shared object symbol table"),
674          cl::value_desc("name"));
675
676static cl::alias
677ArgFilterAlias("filter",
678               cl::desc("alias for -F"),
679               cl::aliasopt(ArgFilterAlias));
680
681static cl::list<std::string>
682ArgAuxiliary("f",
683             cl::ZeroOrMore,
684             cl::desc("Auxiliary filter for shared object symbol table"),
685             cl::value_desc("name"));
686
687static cl::alias
688ArgAuxiliaryAlias("auxiliary",
689                  cl::desc("alias for -f"),
690                  cl::aliasopt(ArgAuxiliary));
691
692static cl::opt<bool>
693ArgUseGold("use-gold",
694          cl::desc("GCC/collect2 compatibility: uses ld.gold. Ignored"),
695          cl::init(false));
696
697static cl::opt<bool>
698ArgUseMCLD("use-mcld",
699          cl::desc("GCC/collect2 compatibility: uses ld.mcld. Ignored"),
700          cl::init(false));
701
702static cl::opt<bool>
703ArgUseLD("use-ld",
704          cl::desc("GCC/collect2 compatibility: uses ld.bfd. Ignored"),
705          cl::init(false));
706
707static cl::opt<bool>
708ArgEB("EB",
709  cl::desc("Link big-endian objects. This affects the default output format."),
710  cl::init(false));
711
712static cl::opt<bool>
713ArgEL("EL",
714  cl::desc("Link little-endian objects. This affects the default output "
715           "format."),
716  cl::init(false));
717
718static cl::list<std::string>
719ArgPlugin("plugin",
720          cl::desc("Load a plugin library."),
721          cl::value_desc("plugin"));
722
723static cl::list<std::string>
724ArgPluginOpt("plugin-opt",
725             cl::desc("	Pass an option to the plugin."),
726             cl::value_desc("option"));
727
728static cl::opt<bool>
729ArgSVR4Compatibility("Qy",
730                     cl::desc("This option is ignored for SVR4 compatibility"),
731                     cl::init(false));
732
733static cl::list<std::string>
734ArgY("Y",
735     cl::desc("Add path to the default library search path"),
736     cl::value_desc("default-search-path"));
737
738static cl::opt<bool>
739ArgARMCompatibility("p",
740                    cl::desc("Ignore for ARM backward compatibility"),
741                    cl::init(false));
742
743/// @{
744/// @name FIXME: end of unsupported options
745/// @}
746
747static cl::opt<bool>
748ArgNoWarnMismatch("no-warn-mismatch",
749                  cl::desc("Allow linking together mismatched input files."),
750                  cl::init(false));
751
752static cl::opt<bool>
753ArgNoStdlib("nostdlib",
754            cl::desc("Only search lib dirs explicitly specified on cmdline"),
755            cl::init(false));
756
757static cl::list<std::string, bool, llvm::cl::SearchDirParser>
758ArgRuntimePath("rpath",
759               cl::ZeroOrMore,
760               cl::desc("Add a directory to the runtime library search path"),
761               cl::value_desc("dir"));
762
763static cl::alias
764ArgRuntimePathAlias("R",
765                    cl::desc("alias for --rpath"),
766                    cl::aliasopt(ArgRuntimePath), cl::Prefix);
767
768static cl::opt<bool>
769ArgEnableNewDTags("enable-new-dtags",
770                  cl::desc("Enable use of DT_RUNPATH and DT_FLAGS"),
771                  cl::init(false));
772
773static cl::opt<bool>
774ArgPrintMap("M",
775            cl::desc("Print a link map to the standard output."),
776            cl::init(false));
777
778static cl::alias
779ArgPrintMapAlias("print-map",
780                 cl::desc("alias for -M"),
781                 cl::aliasopt(ArgPrintMap));
782
783static bool ArgFatalWarnings;
784
785static cl::opt<bool, true, cl::FalseParser>
786ArgNoFatalWarnings("no-fatal-warnings",
787                   cl::location(ArgFatalWarnings),
788                   cl::desc("do not turn warnings into errors"),
789                   cl::init(false),
790                   cl::ValueDisallowed);
791
792static cl::opt<bool, true>
793ArgFatalWarningsFlag("fatal-warnings",
794                     cl::ZeroOrMore,
795                     cl::location(ArgFatalWarnings),
796                     cl::desc("turn all warnings into errors"),
797                     cl::init(false),
798                     cl::ValueDisallowed);
799
800static cl::opt<bool>
801ArgWarnSharedTextrel("warn-shared-textrel",
802                     cl::ZeroOrMore,
803                     cl::desc("Warn if adding DT_TEXTREL in a shared object."),
804                     cl::init(false));
805
806namespace format {
807enum Format {
808  Binary,
809  Unknown // decided by triple
810};
811} // namespace of format
812
813static cl::opt<format::Format>
814ArgFormat("b",
815  cl::value_desc("Format"),
816  cl::desc("set input format"),
817  cl::init(format::Unknown),
818  cl::values(
819    clEnumValN(format::Binary, "binary",
820      "read in binary machine code."),
821    clEnumValEnd));
822
823static cl::alias
824ArgFormatAlias("format",
825               cl::desc("alias for -b"),
826               cl::aliasopt(ArgFormat));
827
828static cl::opt<format::Format>
829ArgOFormat("oformat",
830  cl::value_desc("Format"),
831  cl::desc("set output format"),
832  cl::init(format::Unknown),
833  cl::values(
834    clEnumValN(format::Binary, "binary",
835      "generate binary machine code."),
836    clEnumValEnd));
837
838static cl::opt<bool>
839ArgDefineCommon("d",
840                cl::ZeroOrMore,
841                cl::desc("Define common symbol"),
842                cl::init(false));
843
844static cl::alias
845ArgDefineCommonAlias1("dc",
846                      cl::ZeroOrMore,
847                      cl::desc("alias for -d"),
848                      cl::aliasopt(ArgDefineCommon));
849
850static cl::alias
851ArgDefineCommonAlias2("dp",
852                      cl::ZeroOrMore,
853                      cl::desc("alias for -d"),
854                      cl::aliasopt(ArgDefineCommon));
855
856//===----------------------------------------------------------------------===//
857// Scripting Options
858//===----------------------------------------------------------------------===//
859static cl::list<std::string>
860ArgWrapList("wrap",
861            cl::ZeroOrMore,
862            cl::desc("Use a wrap function fo symbol."),
863            cl::value_desc("symbol"));
864
865static cl::list<std::string>
866ArgPortList("portable",
867            cl::ZeroOrMore,
868            cl::desc("Use a portable function fo symbol."),
869            cl::value_desc("symbol"));
870
871static cl::list<std::string>
872ArgAddressMapList("section-start",
873  cl::ZeroOrMore,
874  cl::desc("Locate a output section at the given absolute address"),
875  cl::value_desc("Set address of section"),
876  cl::Prefix);
877
878static cl::opt<unsigned long long>
879ArgBssSegAddr("Tbss",
880              cl::desc("Set the address of the bss segment"),
881              cl::init(-1U));
882
883static cl::opt<unsigned long long>
884ArgDataSegAddr("Tdata",
885               cl::desc("Set the address of the data segment"),
886               cl::init(-1U));
887
888static cl::opt<unsigned long long>
889ArgTextSegAddr("Ttext",
890               cl::desc("Set the address of the text segment"),
891               cl::init(-1U));
892
893static cl::alias
894ArgTextSegAddrAlias("Ttext-segment",
895                    cl::desc("alias for -Ttext"),
896                    cl::aliasopt(ArgTextSegAddr));
897
898//===----------------------------------------------------------------------===//
899// non-member functions
900//===----------------------------------------------------------------------===//
901/// GetOutputStream - get the output stream.
902static
903mcld::ToolOutputFile *GetOutputStream(const char* pTargetName,
904                                      Triple::OSType pOSType,
905                                      mcld::CodeGenFileType pFileType,
906                                      const mcld::sys::fs::Path& pInputFilename,
907                                      mcld::sys::fs::Path& pOutputFilename)
908{
909  if (pOutputFilename.empty()) {
910    if (0 == pInputFilename.native().compare("-"))
911      pOutputFilename.assign("-");
912    else {
913      switch(pFileType) {
914      case mcld::CGFT_ASMFile: {
915        if (0 == pInputFilename.native().compare("-"))
916          pOutputFilename.assign("_out");
917        else
918          pOutputFilename.assign(pInputFilename.stem().native());
919
920        if (0 == strcmp(pTargetName, "c"))
921          pOutputFilename.native() += ".cbe.c";
922        else if (0 == strcmp(pTargetName, "cpp"))
923          pOutputFilename.native() += ".cpp";
924        else
925          pOutputFilename.native() += ".s";
926      }
927      break;
928
929      case mcld::CGFT_OBJFile: {
930        if (0 == pInputFilename.native().compare("-"))
931          pOutputFilename.assign("_out");
932        else
933          pOutputFilename.assign(pInputFilename.stem().native());
934
935        if (pOSType == Triple::Win32)
936          pOutputFilename.native() += ".obj";
937        else
938          pOutputFilename.native() += ".o";
939      }
940      break;
941
942      case mcld::CGFT_PARTIAL: {
943        if (Triple::Win32 == pOSType) {
944          if (0 == pInputFilename.native().compare("-"))
945            pOutputFilename.assign("_out");
946          else
947            pOutputFilename.assign(pInputFilename.stem().native());
948          pOutputFilename.native() += ".obj";
949        }
950        else
951          pOutputFilename.assign("a.out");
952      }
953      break;
954
955      case mcld::CGFT_DSOFile: {
956        if (Triple::Win32 == pOSType) {
957          if (0 == pInputFilename.native().compare("-"))
958            pOutputFilename.assign("_out");
959          else
960            pOutputFilename.assign(pInputFilename.stem().native());
961          pOutputFilename.native() += ".dll";
962        }
963        else
964          pOutputFilename.assign("a.out");
965      }
966      break;
967
968      case mcld::CGFT_EXEFile: {
969        if (Triple::Win32 == pOSType) {
970          if (0 == pInputFilename.native().compare("-"))
971            pOutputFilename.assign("_out");
972          else
973            pOutputFilename.assign(pInputFilename.stem().native());
974          pOutputFilename.native() += ".exe";
975        }
976        else
977          pOutputFilename.assign("a.out");
978      }
979      break;
980
981      case mcld::CGFT_NULLFile:
982        break;
983      default:
984        llvm::report_fatal_error("Unknown output file type.\n");
985      } // end of switch
986    } // end of ! pInputFilename == "-"
987  } // end of if empty pOutputFilename
988
989  mcld::FileHandle::Permission permission;
990  switch (pFileType) {
991  default: assert(0 && "Unknown file type");
992  case mcld::CGFT_ASMFile:
993  case mcld::CGFT_OBJFile:
994  case mcld::CGFT_PARTIAL:
995    permission = mcld::FileHandle::Permission(0x644);
996    break;
997  case mcld::CGFT_DSOFile:
998  case mcld::CGFT_EXEFile:
999  case mcld::CGFT_BINARY:
1000  case mcld::CGFT_NULLFile:
1001    permission = mcld::FileHandle::Permission(0x755);
1002    break;
1003  }
1004
1005  // Open the file.
1006  mcld::ToolOutputFile* result_output =
1007    new mcld::ToolOutputFile(pOutputFilename,
1008                             mcld::FileHandle::ReadWrite |
1009                               mcld::FileHandle::Create |
1010                               mcld::FileHandle::Truncate,
1011                             permission);
1012
1013  return result_output;
1014}
1015
1016/// ParseProgName - Parse program name
1017/// This function simplifies cross-compiling by reading triple from the program
1018/// name. For example, if the program name is `arm-linux-eabi-ld.mcld', we can
1019/// get the triple is arm-linux-eabi by the program name.
1020static std::string ParseProgName(const char *progname)
1021{
1022  static const char *suffixes[] = {
1023    "ld",
1024    "ld.mcld",
1025  };
1026
1027  std::string ProgName(mcld::sys::fs::Path(progname).stem().native());
1028
1029  for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
1030    if (ProgName == suffixes[i])
1031      return std::string();
1032  }
1033
1034  StringRef ProgNameRef(ProgName);
1035  StringRef Prefix;
1036
1037  for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
1038    if (!ProgNameRef.endswith(suffixes[i]))
1039      continue;
1040
1041    StringRef::size_type LastComponent = ProgNameRef.rfind('-',
1042      ProgNameRef.size() - strlen(suffixes[i]));
1043    if (LastComponent == StringRef::npos)
1044      continue;
1045    StringRef Prefix = ProgNameRef.slice(0, LastComponent);
1046    std::string IgnoredError;
1047    if (!mcld::TargetRegistry::lookupTarget(Prefix, IgnoredError))
1048      continue;
1049    return Prefix.str();
1050  }
1051  return std::string();
1052}
1053
1054static Triple ParseEmulation(const std::string& pEmulation)
1055{
1056  Triple result = StringSwitch<Triple>(pEmulation)
1057    .Case("aarch64linux",      Triple("aarch64", "", "linux", "gnu"))
1058    .Case("armelf_linux_eabi", Triple("arm", "", "linux", "gnueabi"))
1059    .Case("elf_i386",          Triple("i386", "", "", "gnu"))
1060    .Case("elf_x86_64",        Triple("x86_64", "", "", "gnu"))
1061    .Case("elf32_x86_64",      Triple("x86_64", "", "", "gnux32"))
1062    .Case("elf_i386_fbsd",     Triple("i386", "", "freebsd", "gnu"))
1063    .Case("elf_x86_64_fbsd",   Triple("x86_64", "", "freebsd", "gnu"))
1064    .Case("elf32ltsmip",       Triple("mipsel", "", "", "gnu"))
1065    .Default(Triple());
1066
1067  if (result.getArch()        == Triple::UnknownArch &&
1068      result.getOS()          == Triple::UnknownOS &&
1069      result.getEnvironment() == Triple::UnknownEnvironment)
1070    mcld::error(mcld::diag::err_invalid_emulation) << pEmulation << "\n";
1071
1072  return result;
1073}
1074
1075static bool ShouldColorize()
1076{
1077   const char* term = getenv("TERM");
1078   return term && (0 != strcmp(term, "dumb"));
1079}
1080
1081static bool ProcessLinkerOptionsFromCommand(mcld::LinkerScript& pScript,
1082                                            mcld::LinkerConfig& pConfig)
1083{
1084  // -----  Set up General Options  ----- //
1085  // set up colorize
1086  switch (ArgColor) {
1087    case color::Never:
1088      pConfig.options().setColor(false);
1089    break;
1090    case color::Always:
1091      pConfig.options().setColor(true);
1092    break;
1093    case color::Auto:
1094      bool color_option = ShouldColorize() &&
1095        llvm::sys::Process::FileDescriptorIsDisplayed(STDOUT_FILENO);
1096      pConfig.options().setColor(color_option);
1097    break;
1098  }
1099
1100  mcld::outs().setColor(pConfig.options().color());
1101  mcld::errs().setColor(pConfig.options().color());
1102
1103  // set up soname
1104  pConfig.options().setSOName(ArgSOName);
1105
1106  // add all rpath entries
1107  cl::list<std::string>::iterator rp;
1108  cl::list<std::string>::iterator rpEnd = ArgRuntimePath.end();
1109  for (rp = ArgRuntimePath.begin(); rp != rpEnd; ++rp) {
1110    pConfig.options().getRpathList().push_back(*rp);
1111  }
1112
1113  // add all linker scripts
1114  cl::list<std::string>::iterator sp;
1115  cl::list<std::string>::iterator spEnd = ArgLinkerScript.end();
1116  for (sp = ArgLinkerScript.begin(); sp != spEnd; ++sp) {
1117    pConfig.options().getScriptList().push_back(*sp);
1118  }
1119
1120  pConfig.options().setGenUnwindInfo(ArgGenUnwindInfo);
1121
1122  // --fatal-warnings
1123  // pConfig.options().setFatalWarnings(ArgFatalWarnings);
1124
1125  // -shared or -pie
1126  if (true == ArgShared || true == ArgPIE) {
1127    ArgFileType = mcld::CGFT_DSOFile;
1128  }
1129  else if (true == ArgRelocatable) {
1130    ArgFileType = mcld::CGFT_PARTIAL;
1131  }
1132  else if (format::Binary == ArgOFormat) {
1133    ArgFileType = mcld::CGFT_BINARY;
1134  }
1135
1136  // -b [input-format], --format=[input-format]
1137  if (format::Binary == ArgFormat)
1138    pConfig.options().setBinaryInput();
1139
1140  // -V
1141  if (ArgVersion) {
1142    mcld::outs() << "MCLinker - "
1143                 << mcld::LinkerConfig::version()
1144                 << "\n";
1145  }
1146
1147  // set up sysroot
1148  if (!ArgSysRoot.empty()) {
1149    if (exists(ArgSysRoot) && is_directory(ArgSysRoot))
1150      pScript.setSysroot(ArgSysRoot);
1151  }
1152
1153  // add all search directories
1154  cl::list<std::string>::iterator sd;
1155  cl::list<std::string>::iterator sdEnd = ArgSearchDirList.end();
1156  for (sd=ArgSearchDirList.begin(); sd!=sdEnd; ++sd) {
1157    if (!pScript.directories().insert(*sd)) {
1158      // FIXME: need a warning function
1159      errs() << "WARNING: can not open search directory `-L"
1160             << *sd
1161             << "'.\n";
1162    }
1163  }
1164
1165  pConfig.options().setPIE(ArgPIE);
1166  pConfig.options().setTrace(ArgTrace);
1167  pConfig.options().setVerbose(ArgVerbose);
1168  pConfig.options().setMaxErrorNum(ArgMaxErrorNum);
1169  pConfig.options().setMaxWarnNum(ArgMaxWarnNum);
1170  pConfig.options().setBsymbolic(ArgBsymbolic);
1171  pConfig.options().setBgroup(ArgBgroup);
1172  pConfig.options().setDyld(ArgDyld);
1173  pConfig.options().setNoUndefined(ArgNoUndefined);
1174  pConfig.options().setMulDefs(ArgAllowMulDefs);
1175  pConfig.options().setEhFrameHdr(ArgEhFrameHdr);
1176  pConfig.options().setNMagic(ArgNMagic);
1177  pConfig.options().setOMagic(ArgOMagic);
1178  pConfig.options().setStripDebug(ArgStripDebug || ArgStripAll);
1179  pConfig.options().setExportDynamic(ArgExportDynamic);
1180  pConfig.options().setWarnSharedTextrel(ArgWarnSharedTextrel);
1181  pConfig.options().setDefineCommon(ArgDefineCommon);
1182  pConfig.options().setNewDTags(ArgEnableNewDTags);
1183  pConfig.options().setHashStyle(ArgHashStyle);
1184  pConfig.options().setNoStdlib(ArgNoStdlib);
1185  pConfig.options().setPrintMap(ArgPrintMap);
1186  pConfig.options().setGCSections(ArgGCSections);
1187  pConfig.options().setGPSize(ArgGPSize);
1188  if (ArgNoWarnMismatch)
1189    pConfig.options().setWarnMismatch(false);
1190  else
1191    pConfig.options().setWarnMismatch(true);
1192
1193  if (ArgStripAll)
1194    pConfig.options().setStripSymbols(mcld::GeneralOptions::StripAllSymbols);
1195  else if (ArgDiscardAll)
1196    pConfig.options().setStripSymbols(mcld::GeneralOptions::StripLocals);
1197  else if (ArgDiscardLocals)
1198    pConfig.options().setStripSymbols(mcld::GeneralOptions::StripTemporaries);
1199  else
1200    pConfig.options().setStripSymbols(mcld::GeneralOptions::KeepAllSymbols);
1201
1202  // set up entry point from -e
1203  pScript.setEntry(ArgEntry);
1204
1205  // set up rename map, for --wrap
1206  cl::list<std::string>::iterator wname;
1207  cl::list<std::string>::iterator wnameEnd = ArgWrapList.end();
1208  for (wname = ArgWrapList.begin(); wname != wnameEnd; ++wname) {
1209    bool exist = false;
1210
1211    // add wname -> __wrap_wname
1212    mcld::StringEntry<llvm::StringRef>* to_wrap =
1213      pScript.renameMap().insert(*wname, exist);
1214
1215    std::string to_wrap_str = "__wrap_" + *wname;
1216    to_wrap->setValue(to_wrap_str);
1217
1218    if (exist)
1219      mcld::warning(mcld::diag::rewrap) << *wname << to_wrap_str;
1220
1221    // add __real_wname -> wname
1222    std::string from_real_str = "__real_" + *wname;
1223    mcld::StringEntry<llvm::StringRef>* from_real =
1224      pScript.renameMap().insert(from_real_str, exist);
1225    from_real->setValue(*wname);
1226    if (exist)
1227      mcld::warning(mcld::diag::rewrap) << *wname << from_real_str;
1228  } // end of for
1229
1230  // set up rename map, for --portable
1231  cl::list<std::string>::iterator pname;
1232  cl::list<std::string>::iterator pnameEnd = ArgPortList.end();
1233  for (pname = ArgPortList.begin(); pname != pnameEnd; ++pname) {
1234    bool exist = false;
1235
1236    // add pname -> pname_portable
1237    mcld::StringEntry<llvm::StringRef>* to_port =
1238      pScript.renameMap().insert(*pname, exist);
1239
1240    std::string to_port_str = *pname + "_portable";
1241    to_port->setValue(to_port_str);
1242
1243    if (exist)
1244      mcld::warning(mcld::diag::rewrap) << *pname << to_port_str;
1245
1246    // add __real_pname -> pname
1247    std::string from_real_str = "__real_" + *pname;
1248    mcld::StringEntry<llvm::StringRef>* from_real =
1249      pScript.renameMap().insert(from_real_str, exist);
1250
1251    from_real->setValue(*pname);
1252    if (exist)
1253      mcld::warning(mcld::diag::rewrap) << *pname << from_real_str;
1254  } // end of for
1255
1256  // add -z options
1257  cl::list<mcld::ZOption>::iterator zOpt;
1258  cl::list<mcld::ZOption>::iterator zOptEnd = ArgZOptionList.end();
1259  for (zOpt = ArgZOptionList.begin(); zOpt != zOptEnd; ++zOpt) {
1260    pConfig.options().addZOption(*zOpt);
1261  }
1262
1263  // set up icf mode
1264  switch (ArgICF) {
1265    case icf::None:
1266      break;
1267    case icf::All:
1268    case icf::Safe:
1269    default:
1270      mcld::warning(mcld::diag::warn_unsupported_option) << ArgICF.ArgStr;
1271      break;
1272  }
1273
1274  if (ArgFIXCA8) {
1275    mcld::warning(mcld::diag::warn_unsupported_option) << ArgFIXCA8.ArgStr;
1276  }
1277
1278  // add address mappings
1279  // -Ttext
1280  if (-1U != ArgTextSegAddr) {
1281    bool exist = false;
1282    mcld::StringEntry<uint64_t>* text_mapping =
1283      pScript.addressMap().insert(".text", exist);
1284    text_mapping->setValue(ArgTextSegAddr);
1285  }
1286  // -Tdata
1287  if (-1U != ArgDataSegAddr) {
1288    bool exist = false;
1289    mcld::StringEntry<uint64_t>* data_mapping =
1290      pScript.addressMap().insert(".data", exist);
1291    data_mapping->setValue(ArgDataSegAddr);
1292  }
1293  // -Tbss
1294  if (-1U != ArgBssSegAddr) {
1295    bool exist = false;
1296    mcld::StringEntry<uint64_t>* bss_mapping =
1297      pScript.addressMap().insert(".bss", exist);
1298    bss_mapping->setValue(ArgBssSegAddr);
1299  }
1300  // --section-start SECTION=ADDRESS
1301  for (cl::list<std::string>::iterator
1302       it = ArgAddressMapList.begin(), ie = ArgAddressMapList.end();
1303       it != ie; ++it) {
1304    // FIXME: Add a cl::parser
1305    size_t pos = (*it).find_last_of('=');
1306    llvm::StringRef script(*it);
1307    uint64_t address = 0x0;
1308    script.substr(pos + 1).getAsInteger(0, address);
1309    bool exist = false;
1310    mcld::StringEntry<uint64_t>* addr_mapping =
1311      pScript.addressMap().insert(script.substr(0, pos), exist);
1312    addr_mapping->setValue(address);
1313  }
1314
1315  // set up filter/aux filter for shared object
1316  pConfig.options().setFilter(ArgFilter);
1317
1318  cl::list<std::string>::iterator aux;
1319  cl::list<std::string>::iterator auxEnd = ArgAuxiliary.end();
1320  for (aux = ArgAuxiliary.begin(); aux != auxEnd; ++aux)
1321    pConfig.options().getAuxiliaryList().push_back(*aux);
1322
1323  return true;
1324}
1325
1326int main(int argc, char* argv[])
1327{
1328  sys::PrintStackTraceOnErrorSignal();
1329
1330  LLVMContext &Context = getGlobalContext();
1331  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1332
1333  // Initialize targets first, so that --version shows registered targets.
1334  InitializeAllTargets();
1335  InitializeAllAsmPrinters();
1336  InitializeAllAsmParsers();
1337  InitializeAllTargetMCs();
1338  mcld::InitializeAllTargets();
1339  mcld::InitializeAllLinkers();
1340  mcld::InitializeAllEmulations();
1341  mcld::InitializeAllDiagnostics();
1342
1343  cl::ParseCommandLineOptions(argc, argv, "MCLinker\n");
1344
1345#ifdef ENABLE_UNITTEST
1346  if (UnitTest) {
1347    return unit_test( argc, argv );
1348  }
1349#endif
1350
1351  // Load the module to be compiled...
1352  std::auto_ptr<llvm::Module> M;
1353
1354  // Load the module to be linked...
1355  mcld::LinkerScript LDScript;
1356  mcld::Module LDIRModule(LDScript);
1357  mcld::LinkerConfig LDConfig;
1358
1359  // Process the linker input from the command line
1360  if (!ProcessLinkerOptionsFromCommand(LDScript, LDConfig)) {
1361    errs() << argv[0] << ": failed to process linker options from command line!\n";
1362    return 1;
1363  }
1364
1365  if (ArgBitcodeFilename.empty() &&
1366      (mcld::CGFT_DSOFile != ArgFileType &&
1367       mcld::CGFT_EXEFile != ArgFileType &&
1368       mcld::CGFT_PARTIAL != ArgFileType &&
1369       mcld::CGFT_BINARY  != ArgFileType)) {
1370    // If the file is not given, forcefully read from stdin
1371    if (ArgVerbose >= 0) {
1372      errs() << "** The bitcode/llvm asm file is not given. Read from stdin.\n"
1373             << "** Specify input bitcode/llvm asm file by\n\n"
1374             << "          llvm-mcld -dB [the bitcode/llvm asm]\n\n";
1375    }
1376
1377    ArgBitcodeFilename.assign("-");
1378  }
1379
1380  if (!ArgBitcodeFilename.empty()) {
1381    SMDiagnostic Err;
1382    M.reset(ParseIRFile(ArgBitcodeFilename.native(), Err, Context));
1383
1384    if (M.get() == 0) {
1385      Err.print(argv[0], errs());
1386      errs() << "** Failed to to the given bitcode/llvm asm file '"
1387             << ArgBitcodeFilename.native() << "'. **\n";
1388      return 1;
1389    }
1390  }
1391  else {
1392    // If here, output must be dynamic shared object (mcld::CGFT_DSOFile) and
1393    // executable file (mcld::CGFT_EXEFile).
1394    M.reset(new Module("Empty Module", Context));
1395  }
1396  Module &mod = *M.get();
1397
1398  // If we are supposed to override the target triple, do so now.
1399  Triple TheTriple;
1400  if (!TargetTriple.empty()) {
1401    // 1. Use the triple from command.
1402    TheTriple.setTriple(TargetTriple);
1403    mod.setTargetTriple(TargetTriple);
1404  } else if (!mod.getTargetTriple().empty()) {
1405    // 2. Use the triple in the input Module.
1406    TheTriple.setTriple(mod.getTargetTriple());
1407  } else {
1408    std::string ProgNameTriple = ParseProgName(argv[0]);
1409    if (!ProgNameTriple.empty()) {
1410      // 3. Use the triple from the program name prefix.
1411      TheTriple.setTriple(ProgNameTriple);
1412      mod.setTargetTriple(ProgNameTriple);
1413    } else {
1414      // 4. Use the default target triple.
1415      TheTriple.setTriple(mcld::sys::getDefaultTargetTriple());
1416    }
1417  }
1418
1419  // If a specific emulation was requested, apply it now.
1420  if (!ArgEmulation.empty()) {
1421    Triple EmulationTriple = ParseEmulation(ArgEmulation);
1422    if (EmulationTriple.getArch() != Triple::UnknownArch)
1423      TheTriple.setArch(EmulationTriple.getArch());
1424    if (EmulationTriple.getOS() != Triple::UnknownOS)
1425      TheTriple.setOS(EmulationTriple.getOS());
1426    if (EmulationTriple.getEnvironment() != Triple::UnknownEnvironment)
1427      TheTriple.setEnvironment(EmulationTriple.getEnvironment());
1428  }
1429
1430  // Get the target specific parser.
1431  std::string error;
1432  const llvm::Target *LLVMTarget = llvm::TargetRegistry::lookupTarget(MArch,
1433                                                                      TheTriple,
1434                                                                      error);
1435  if (NULL == LLVMTarget) {
1436    errs() << argv[0] << ": " << error;
1437    return 1;
1438  }
1439
1440  // Allocate target machine.  First, check whether the user has explicitly
1441  // specified an architecture to compile for. If so we have to look it up by
1442  // name, because it might be a backend that has no mapping to a target triple.
1443  const mcld::Target *MCLDTarget = mcld::TargetRegistry::lookupTarget(MArch,
1444                                                                      TheTriple,
1445                                                                      error);
1446  if (NULL == MCLDTarget) {
1447    errs() << argv[0] << ": " << error;
1448    return 1;
1449  }
1450
1451
1452  LDConfig.targets().setTriple(TheTriple);
1453
1454  // Package up features to be passed to target/subtarget
1455  std::string FeaturesStr;
1456  if (MAttrs.size()) {
1457    SubtargetFeatures Features;
1458    for (unsigned i = 0; i != MAttrs.size(); ++i)
1459      Features.AddFeature(MAttrs[i]);
1460    FeaturesStr = Features.getString();
1461  }
1462
1463  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
1464  switch (OptLevel) {
1465  default:
1466    errs() << argv[0] << ": invalid optimization level.\n";
1467    return 1;
1468  case ' ': break;
1469  case '0': OLvl = CodeGenOpt::None; break;
1470  case '1': OLvl = CodeGenOpt::Less; break;
1471  case '2': OLvl = CodeGenOpt::Default; break;
1472  case '3': OLvl = CodeGenOpt::Aggressive; break;
1473  }
1474
1475  // set -fPIC
1476  if (ArgFPIC)
1477    ArgRelocModel = Reloc::PIC_;
1478
1479  TargetOptions Options;
1480  Options.LessPreciseFPMADOption = EnableFPMAD;
1481  Options.NoFramePointerElim = DisableFPElim;
1482  Options.AllowFPOpFusion = FuseFPOps;
1483  Options.UnsafeFPMath = EnableUnsafeFPMath;
1484  Options.NoInfsFPMath = EnableNoInfsFPMath;
1485  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
1486  Options.HonorSignDependentRoundingFPMathOption =
1487    EnableHonorSignDependentRoundingFPMath;
1488  Options.UseSoftFloat = GenerateSoftFloatCalls;
1489  if (FloatABIForCalls != FloatABI::Default)
1490    Options.FloatABIType = FloatABIForCalls;
1491  Options.NoZerosInBSS = DontPlaceZerosInBSS;
1492  Options.JITEmitDebugInfo = EmitJitDebugInfo;
1493  Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
1494  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
1495  Options.StackAlignmentOverride = OverrideStackAlignment;
1496  Options.TrapFuncName = TrapFuncName;
1497  Options.EnableSegmentedStacks = SegmentedStacks;
1498
1499  OwningPtr<llvm::TargetMachine>
1500    TM(LLVMTarget->createTargetMachine(TheTriple.getTriple(),
1501                                       MCPU, FeaturesStr, Options,
1502                                       ArgRelocModel, CMModel, OLvl));
1503
1504  std::auto_ptr<mcld::MCLDTargetMachine>
1505    target_machine(MCLDTarget->createTargetMachine(TheTriple.getTriple(),
1506                                                   *LLVMTarget,
1507                                                   *TM.get()));
1508
1509  assert(target_machine.get() && "Could not allocate target machine!");
1510  mcld::MCLDTargetMachine &TheTargetMachine = *target_machine.get();
1511
1512  LDConfig.targets().setTargetCPU(MCPU);
1513  LDConfig.targets().setTargetFeatureString(FeaturesStr);
1514
1515  TheTargetMachine.getTM().setMCUseLoc(false);
1516  TheTargetMachine.getTM().setMCUseCFI(false);
1517
1518  // FIXME: Move the initialization of LineInfo to mcld::Linker when we
1519  // finish LineInfo's implementation.
1520  OwningPtr<mcld::DiagnosticLineInfo>
1521    diag_line_info(MCLDTarget->createDiagnosticLineInfo(*MCLDTarget,
1522                                                        TheTriple.getTriple()));
1523
1524  mcld::getDiagnosticEngine().setLineInfo(*diag_line_info.take());
1525
1526  // Figure out where we are going to send the output...
1527  OwningPtr<mcld::ToolOutputFile>
1528  Out(GetOutputStream(MCLDTarget->name(),
1529                      TheTriple.getOS(),
1530                      ArgFileType,
1531                      ArgBitcodeFilename,
1532                      ArgOutputFilename));
1533  if (!Out) {
1534    // FIXME: show some error message pls.
1535    return 1;
1536  }
1537
1538  // Build up all of the passes that we want to do to the module.
1539  PassManager PM;
1540
1541  // Add the data layout from the target machine, if it exists, or the module.
1542  if (const DataLayout *DL = TheTargetMachine.getTM().getDataLayout())
1543    PM.add(new DataLayout(*DL));
1544   else
1545    PM.add(new DataLayout(&mod));
1546
1547  // Override default to generate verbose assembly.
1548  TheTargetMachine.getTM().setAsmVerbosityDefault(true);
1549
1550  {
1551    // Ask the target to add backend passes as necessary.
1552    if(TheTargetMachine.addPassesToEmitFile(PM,
1553                                            *Out,
1554                                            ArgFileType,
1555                                            OLvl,
1556                                            LDIRModule,
1557                                            LDConfig,
1558                                            NoVerify)) {
1559      errs() << argv[0] << ": target does not support generation of this"
1560             << " file type!\n";
1561      return 1;
1562    }
1563
1564    // Before executing passes, print the final values of the LLVM options.
1565    cl::PrintOptionValues();
1566
1567    PM.run(mod);
1568  }
1569
1570  if (mcld::getDiagnosticEngine().getPrinter()->getNumErrors())
1571    return 1;
1572
1573  // Declare success.
1574  Out->keep();
1575  return 0;
1576}
1577