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/Target/TargetMachine.h>
10 #include <mcld/Support/TargetSelect.h>
11 #include <mcld/Support/TargetRegistry.h>
12 #include <mcld/Support/CommandLine.h>
13 #include <mcld/Support/DerivedPositionDependentOptions.h>
14 #include <mcld/Support/Path.h>
15 #include <mcld/Support/RealPath.h>
16 #include <mcld/Support/MsgHandling.h>
17 #include <mcld/Support/FileSystem.h>
18 #include <mcld/Support/raw_ostream.h>
19 #include <mcld/LD/DiagnosticLineInfo.h>
20 #include <mcld/LD/TextDiagnosticPrinter.h>
21 #include <mcld/MC/MCLDInfo.h>
22 #include <mcld/CodeGen/SectLinkerOption.h>
23
24 #include <llvm/Module.h>
25 #include <llvm/PassManager.h>
26 #include <llvm/Pass.h>
27 #include <llvm/ADT/Triple.h>
28 #include <llvm/LLVMContext.h>
29 #include <llvm/MC/SubtargetFeature.h>
30 #include <llvm/Support/CommandLine.h>
31 #include <llvm/Support/Debug.h>
32 #include <llvm/Support/FormattedStream.h>
33 #include <llvm/Support/Host.h>
34 #include <llvm/Support/IRReader.h>
35 #include <llvm/Support/ManagedStatic.h>
36 #include <llvm/Support/Signals.h>
37 #include <llvm/Support/TargetRegistry.h>
38 #include <llvm/Support/TargetSelect.h>
39 #include <llvm/Support/ToolOutputFile.h>
40 #include <llvm/Support/Process.h>
41 #include <llvm/Target/TargetData.h>
42 #include <llvm/Target/TargetMachine.h>
43
44 using namespace llvm;
45
46 #ifdef ENABLE_UNITTEST
47 #include <gtest.h>
48
49 static cl::opt<bool>
50 UnitTest("unittest", cl::desc("do unit test") );
51
unit_test(int argc,char * argv[])52 int unit_test( int argc, char* argv[] )
53 {
54 testing::InitGoogleTest( &argc, argv );
55 return RUN_ALL_TESTS();
56 }
57
58 #endif
59
60 // General options for llc. Other pass-specific options are specified
61 // within the corresponding llc passes, and target-specific options
62 // and back-end code generation options are specified with the target machine.
63 //
64 // Determine optimization level.
65 static cl::opt<char>
66 OptLevel("O",
67 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
68 "(default = '-O2')"),
69 cl::Prefix,
70 cl::ZeroOrMore,
71 cl::init(' '));
72
73 static cl::opt<std::string>
74 TargetTriple("mtriple", cl::desc("Override target triple for module"));
75
76 static cl::opt<std::string>
77 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
78
79 static cl::opt<std::string>
80 MCPU("mcpu",
81 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82 cl::value_desc("cpu-name"),
83 cl::init(""));
84
85 static cl::list<std::string>
86 MAttrs("mattr",
87 cl::CommaSeparated,
88 cl::desc("Target specific attributes (-mattr=help for details)"),
89 cl::value_desc("a1,+a2,-a3,..."));
90
91 static cl::opt<llvm::CodeModel::Model>
92 CMModel("code-model",
93 cl::desc("Choose code model"),
94 cl::init(CodeModel::Default),
95 cl::values(clEnumValN(CodeModel::Default, "default",
96 "Target default code model"),
97 clEnumValN(CodeModel::Small, "small",
98 "Small code model"),
99 clEnumValN(CodeModel::Kernel, "kernel",
100 "Kernel code model"),
101 clEnumValN(CodeModel::Medium, "medium",
102 "Medium code model"),
103 clEnumValN(CodeModel::Large, "large",
104 "Large code model"),
105 clEnumValEnd));
106
107 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
108 cl::desc("Do not verify input module"));
109
110 static cl::opt<bool>
111 EnableFPMAD("enable-fp-mad",
112 cl::desc("Enable less precise MAD instructions to be generated"),
113 cl::init(false));
114
115 static cl::opt<bool>
116 DisableFPElim("disable-fp-elim",
117 cl::desc("Disable frame pointer elimination optimization"),
118 cl::init(false));
119
120 static cl::opt<bool>
121 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
122 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
123 cl::init(false));
124
125 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
126 FuseFPOps("fuse-fp-ops",
127 cl::desc("Enable aggresive formation of fused FP ops"),
128 cl::init(FPOpFusion::Standard),
129 cl::values(
130 clEnumValN(FPOpFusion::Fast, "fast",
131 "Fuse FP ops whenever profitable"),
132 clEnumValN(FPOpFusion::Standard, "standard",
133 "Only fuse 'blessed' FP ops."),
134 clEnumValN(FPOpFusion::Strict, "strict",
135 "Only fuse FP ops when the result won't be effected."),
136 clEnumValEnd));
137
138 static cl::opt<bool>
139 EnableUnsafeFPMath("enable-unsafe-fp-math",
140 cl::desc("Enable optimizations that may decrease FP precision"),
141 cl::init(false));
142
143 static cl::opt<bool>
144 EnableNoInfsFPMath("enable-no-infs-fp-math",
145 cl::desc("Enable FP math optimizations that assume no +-Infs"),
146 cl::init(false));
147
148 static cl::opt<bool>
149 EnableNoNaNsFPMath("enable-no-nans-fp-math",
150 cl::desc("Enable FP math optimizations that assume no NaNs"),
151 cl::init(false));
152
153 static cl::opt<bool>
154 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
155 cl::Hidden,
156 cl::desc("Force codegen to assume rounding mode can change dynamically"),
157 cl::init(false));
158
159 static cl::opt<bool>
160 GenerateSoftFloatCalls("soft-float",
161 cl::desc("Generate software floating point library calls"),
162 cl::init(false));
163
164 static cl::opt<llvm::FloatABI::ABIType>
165 FloatABIForCalls("float-abi",
166 cl::desc("Choose float ABI type"),
167 cl::init(FloatABI::Default),
168 cl::values(
169 clEnumValN(FloatABI::Default, "default",
170 "Target default float ABI type"),
171 clEnumValN(FloatABI::Soft, "soft",
172 "Soft float ABI (implied by -soft-float)"),
173 clEnumValN(FloatABI::Hard, "hard",
174 "Hard float ABI (uses FP registers)"),
175 clEnumValEnd));
176
177 static cl::opt<bool>
178 DontPlaceZerosInBSS("nozero-initialized-in-bss",
179 cl::desc("Don't place zero-initialized symbols into bss section"),
180 cl::init(false));
181
182 static cl::opt<bool>
183 EnableJITExceptionHandling("jit-enable-eh",
184 cl::desc("Emit exception handling information"),
185 cl::init(false));
186
187 // In debug builds, make this default to true.
188 #ifdef NDEBUG
189 #define EMIT_DEBUG false
190 #else
191 #define EMIT_DEBUG true
192 #endif
193 static cl::opt<bool>
194 EmitJitDebugInfo("jit-emit-debug",
195 cl::desc("Emit debug information to debugger"),
196 cl::init(EMIT_DEBUG));
197 #undef EMIT_DEBUG
198
199 static cl::opt<bool>
200 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
201 cl::Hidden,
202 cl::desc("Emit debug info objfiles to disk"),
203 cl::init(false));
204
205 static cl::opt<bool>
206 EnableGuaranteedTailCallOpt("tailcallopt",
207 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
208 cl::init(false));
209
210 static cl::opt<unsigned>
211 OverrideStackAlignment("stack-alignment",
212 cl::desc("Override default stack alignment"),
213 cl::init(0));
214
215 static cl::opt<bool>
216 EnableRealignStack("realign-stack",
217 cl::desc("Realign stack if needed"),
218 cl::init(true));
219
220 static cl::opt<std::string>
221 TrapFuncName("trap-func", cl::Hidden,
222 cl::desc("Emit a call to trap function rather than a trap instruction"),
223 cl::init(""));
224
225 static cl::opt<bool>
226 SegmentedStacks("segmented-stacks",
227 cl::desc("Use segmented stacks if possible."),
228 cl::init(false));
229
230 //===----------------------------------------------------------------------===//
231 // Command Line Options
232 // There are four kinds of command line options:
233 // 1. input, (may be a file, such as -m and /tmp/XXXX.o.)
234 // 2. attribute of inputs, (describing the attributes of inputs, such as
235 // --as-needed and --whole-archive. usually be positional.)
236 // 3. scripting options, (represent a subset of link scripting language, such
237 // as --defsym.)
238 // 4. and general options. (the rest of options)
239 //===----------------------------------------------------------------------===//
240 // General Options
241 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
242 ArgBitcodeFilename("dB",
243 cl::desc("set default bitcode"),
244 cl::value_desc("bitcode"));
245
246 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
247 ArgOutputFilename("o",
248 cl::desc("Output filename"),
249 cl::value_desc("filename"));
250
251 static cl::alias
252 AliasOutputFilename("output",
253 cl::desc("alias for -o"),
254 cl::aliasopt(ArgOutputFilename));
255
256 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
257 ArgSysRoot("sysroot",
258 cl::desc("Use directory as the location of the sysroot, overriding the configure-time default."),
259 cl::value_desc("directory"),
260 cl::ValueRequired);
261
262 static cl::list<mcld::MCLDDirectory, bool, llvm::cl::parser<mcld::MCLDDirectory> >
263 ArgSearchDirList("L",
264 cl::ZeroOrMore,
265 cl::desc("Add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts."),
266 cl::value_desc("searchdir"),
267 cl::Prefix);
268
269 static cl::alias
270 ArgSearchDirListAlias("library-path",
271 cl::desc("alias for -L"),
272 cl::aliasopt(ArgSearchDirList));
273
274 static cl::opt<bool>
275 ArgTrace("t",
276 cl::desc("Print the names of the input files as ld processes them."));
277
278 static cl::alias
279 ArgTraceAlias("trace",
280 cl::desc("alias for -t"),
281 cl::aliasopt(ArgTrace));
282
283 static cl::opt<int>
284 ArgVerbose("verbose",
285 cl::init(-1),
286 cl::desc("Display the version number for ld and list the linker emulations supported."));
287
288 static cl::opt<bool>
289 ArgVersion("V",
290 cl::init(false),
291 cl::desc("Display the version number for MCLinker."));
292
293 static cl::opt<int>
294 ArgMaxErrorNum("error-limit",
295 cl::init(-1),
296 cl::desc("limits the maximum number of erros."));
297
298 static cl::opt<int>
299 ArgMaxWarnNum("warning-limit",
300 cl::init(-1),
301 cl::desc("limits the maximum number of warnings."));
302
303 static cl::opt<std::string>
304 ArgEntry("e",
305 cl::desc("Use entry as the explicit symbol for beginning execution of your program."),
306 cl::value_desc("entry"),
307 cl::ValueRequired);
308
309 static cl::alias
310 ArgEntryAlias("entry",
311 cl::desc("alias for -e"),
312 cl::aliasopt(ArgEntry));
313
314 static cl::opt<bool>
315 ArgBsymbolic("Bsymbolic",
316 cl::desc("Bind references within the shared library."),
317 cl::init(false));
318
319 static cl::opt<bool>
320 ArgBgroup("Bgroup",
321 cl::desc("Info the dynamic linker to perform lookups only inside the group."),
322 cl::init(false));
323
324 static cl::opt<std::string>
325 ArgSOName("soname",
326 cl::desc("Set internal name of shared library"),
327 cl::value_desc("name"));
328
329 static cl::opt<bool>
330 ArgNoUndefined("no-undefined",
331 cl::desc("Do not allow unresolved references"),
332 cl::init(false));
333
334 static cl::opt<bool>
335 ArgAllowMulDefs("allow-multiple-definition",
336 cl::desc("Allow multiple definition"),
337 cl::init(false));
338
339 static cl::opt<bool>
340 ArgEhFrameHdr("eh-frame-hdr",
341 cl::desc("Request creation of \".eh_frame_hdr\" section and ELF \"PT_GNU_EH_FRAME\" segment header."),
342 cl::init(false));
343
344 static cl::list<mcld::ZOption, bool, llvm::cl::parser<mcld::ZOption> >
345 ArgZOptionList("z",
346 cl::ZeroOrMore,
347 cl::desc("The -z options for GNU ld compatibility."),
348 cl::value_desc("keyword"),
349 cl::Prefix);
350
351 cl::opt<mcld::CodeGenFileType>
352 ArgFileType("filetype", cl::init(mcld::CGFT_EXEFile),
353 cl::desc("Choose a file type (not all types are supported by all targets):"),
354 cl::values(
355 clEnumValN(mcld::CGFT_ASMFile, "asm",
356 "Emit an assembly ('.s') file"),
357 clEnumValN(mcld::CGFT_OBJFile, "obj",
358 "Emit a relocatable object ('.o') file"),
359 clEnumValN(mcld::CGFT_DSOFile, "dso",
360 "Emit an dynamic shared object ('.so') file"),
361 clEnumValN(mcld::CGFT_EXEFile, "exe",
362 "Emit a executable ('.exe') file"),
363 clEnumValN(mcld::CGFT_NULLFile, "null",
364 "Emit nothing, for performance testing"),
365 clEnumValEnd));
366
367 static cl::opt<bool>
368 ArgShared("shared",
369 cl::desc("Create a shared library."),
370 cl::init(false));
371
372 static cl::alias
373 ArgSharedAlias("Bshareable",
374 cl::desc("alias for -shared"),
375 cl::aliasopt(ArgShared));
376
377 static cl::opt<bool>
378 ArgPIE("pie",
379 cl::desc("Emit a position-independent executable file"),
380 cl::init(false));
381
382 static cl::opt<Reloc::Model>
383 ArgRelocModel("relocation-model",
384 cl::desc("Choose relocation model"),
385 cl::init(Reloc::Default),
386 cl::values(
387 clEnumValN(Reloc::Default, "default",
388 "Target default relocation model"),
389 clEnumValN(Reloc::Static, "static",
390 "Non-relocatable code"),
391 clEnumValN(Reloc::PIC_, "pic",
392 "Fully relocatable, position independent code"),
393 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
394 "Relocatable external references, non-relocatable code"),
395 clEnumValEnd));
396
397 static cl::opt<bool>
398 ArgFPIC("fPIC",
399 cl::desc("Set relocation model to pic. The same as -relocation-model=pic."),
400 cl::init(false));
401
402 static cl::opt<std::string>
403 ArgDyld("dynamic-linker",
404 cl::desc("Set the name of the dynamic linker."),
405 cl::value_desc("Program"));
406
407 namespace color {
408 enum Color {
409 Never,
410 Always,
411 Auto
412 };
413 } // namespace of color
414
415 static cl::opt<color::Color>
416 ArgColor("color",
417 cl::value_desc("WHEN"),
418 cl::desc("Surround the result strings with the marker"),
419 cl::init(color::Auto),
420 cl::values(
421 clEnumValN(color::Never, "never",
422 "do not surround result strings"),
423 clEnumValN(color::Always, "always",
424 "always surround result strings, even the output is a plain file"),
425 clEnumValN(color::Auto, "auto",
426 "surround result strings only if the output is a tty"),
427 clEnumValEnd));
428
429 //===----------------------------------------------------------------------===//
430 // Inputs
431 static cl::list<mcld::sys::fs::Path>
432 ArgInputObjectFiles(cl::Positional,
433 cl::desc("[input object files]"),
434 cl::ZeroOrMore);
435
436 static cl::list<std::string>
437 ArgNameSpecList("l",
438 cl::ZeroOrMore,
439 cl::desc("Add the archive or object file specified by namespec to the list of files to link."),
440 cl::value_desc("namespec"),
441 cl::Prefix);
442
443 static cl::alias
444 ArgNameSpecListAlias("library",
445 cl::desc("alias for -l"),
446 cl::aliasopt(ArgNameSpecList));
447
448 static cl::list<bool>
449 ArgStartGroupList("start-group",
450 cl::ValueDisallowed,
451 cl::desc("start to record a group of archives"));
452
453 static cl::alias
454 ArgStartGroupListAlias("(",
455 cl::desc("alias for --start-group"),
456 cl::aliasopt(ArgStartGroupList));
457
458 static cl::list<bool>
459 ArgEndGroupList("end-group",
460 cl::ValueDisallowed,
461 cl::desc("stop recording a group of archives"));
462
463 static cl::alias
464 ArgEndGroupListAlias(")",
465 cl::desc("alias for --end-group"),
466 cl::aliasopt(ArgEndGroupList));
467
468 //===----------------------------------------------------------------------===//
469 // Attributes of Inputs
470 static cl::list<bool>
471 ArgWholeArchiveList("whole-archive",
472 cl::ValueDisallowed,
473 cl::desc("For each archive mentioned on the command line after the --whole-archive option, include all object files in the archive."));
474
475 static cl::list<bool>
476 ArgNoWholeArchiveList("no-whole-archive",
477 cl::ValueDisallowed,
478 cl::desc("Turn off the effect of the --whole-archive option for subsequent archive files."));
479
480 static cl::list<bool>
481 ArgAsNeededList("as-needed",
482 cl::ValueDisallowed,
483 cl::desc("This option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option."));
484
485 static cl::list<bool>
486 ArgNoAsNeededList("no-as-needed",
487 cl::ValueDisallowed,
488 cl::desc("Turn off the effect of the --as-needed option for subsequent dynamic libraries"));
489
490 static cl::list<bool>
491 ArgAddNeededList("add-needed",
492 cl::ValueDisallowed,
493 cl::desc("--add-needed causes DT_NEEDED tags are always emitted for those libraries from DT_NEEDED tags. This is the default behavior."));
494
495 static cl::list<bool>
496 ArgNoAddNeededList("no-add-needed",
497 cl::ValueDisallowed,
498 cl::desc("--no-add-needed causes DT_NEEDED tags will never be emitted for those libraries from DT_NEEDED tags"));
499
500 static cl::list<bool>
501 ArgBDynamicList("Bdynamic",
502 cl::ValueDisallowed,
503 cl::desc("Link against dynamic library"));
504
505 static cl::alias
506 ArgBDynamicListAlias1("dy",
507 cl::desc("alias for --Bdynamic"),
508 cl::aliasopt(ArgBDynamicList));
509
510 static cl::alias
511 ArgBDynamicListAlias2("call_shared",
512 cl::desc("alias for --Bdynamic"),
513 cl::aliasopt(ArgBDynamicList));
514
515 static cl::list<bool>
516 ArgBStaticList("Bstatic",
517 cl::ValueDisallowed,
518 cl::desc("Link against static library"));
519
520 static cl::alias
521 ArgBStaticListAlias1("dn",
522 cl::desc("alias for --Bstatic"),
523 cl::aliasopt(ArgBStaticList));
524
525 static cl::alias
526 ArgBStaticListAlias2("static",
527 cl::desc("alias for --Bstatic"),
528 cl::aliasopt(ArgBStaticList));
529
530 static cl::alias
531 ArgBStaticListAlias3("non_shared",
532 cl::desc("alias for --Bstatic"),
533 cl::aliasopt(ArgBStaticList));
534
535 //===----------------------------------------------------------------------===//
536 // Scripting Options
537 static cl::list<std::string>
538 ArgWrapList("wrap",
539 cl::ZeroOrMore,
540 cl::desc("Use a wrap function fo symbol."),
541 cl::value_desc("symbol"));
542
543 static cl::list<std::string>
544 ArgPortList("portable",
545 cl::ZeroOrMore,
546 cl::desc("Use a portable function fo symbol."),
547 cl::value_desc("symbol"));
548
549 //===----------------------------------------------------------------------===//
550 /// non-member functions
551
552 /// GetOutputStream - get the output stream.
GetOutputStream(const char * pTargetName,Triple::OSType pOSType,mcld::CodeGenFileType pFileType,const mcld::sys::fs::Path & pInputFilename,mcld::sys::fs::Path & pOutputFilename)553 static tool_output_file *GetOutputStream(const char* pTargetName,
554 Triple::OSType pOSType,
555 mcld::CodeGenFileType pFileType,
556 const mcld::sys::fs::Path& pInputFilename,
557 mcld::sys::fs::Path& pOutputFilename)
558 {
559 if (pOutputFilename.empty()) {
560 if (0 == pInputFilename.native().compare("-"))
561 pOutputFilename.assign("-");
562 else {
563 switch(pFileType) {
564 case mcld::CGFT_ASMFile: {
565 if (0 == pInputFilename.native().compare("-"))
566 pOutputFilename.assign("_out");
567 else
568 pOutputFilename.assign(pInputFilename.stem().native());
569
570 if (0 == strcmp(pTargetName, "c"))
571 pOutputFilename.native() += ".cbe.c";
572 else if (0 == strcmp(pTargetName, "cpp"))
573 pOutputFilename.native() += ".cpp";
574 else
575 pOutputFilename.native() += ".s";
576 }
577 break;
578
579 case mcld::CGFT_OBJFile: {
580 if (0 == pInputFilename.native().compare("-"))
581 pOutputFilename.assign("_out");
582 else
583 pOutputFilename.assign(pInputFilename.stem().native());
584
585 if (pOSType == Triple::Win32)
586 pOutputFilename.native() += ".obj";
587 else
588 pOutputFilename.native() += ".o";
589 }
590 break;
591
592 case mcld::CGFT_DSOFile: {
593 if (Triple::Win32 == pOSType) {
594 if (0 == pInputFilename.native().compare("-"))
595 pOutputFilename.assign("_out");
596 else
597 pOutputFilename.assign(pInputFilename.stem().native());
598 pOutputFilename.native() += ".dll";
599 }
600 else
601 pOutputFilename.assign("a.out");
602 }
603 break;
604
605 case mcld::CGFT_EXEFile: {
606 if (Triple::Win32 == pOSType) {
607 if (0 == pInputFilename.native().compare("-"))
608 pOutputFilename.assign("_out");
609 else
610 pOutputFilename.assign(pInputFilename.stem().native());
611 pOutputFilename.native() += ".exe";
612 }
613 else
614 pOutputFilename.assign("a.out");
615 }
616 break;
617
618 case mcld::CGFT_NULLFile:
619 break;
620 default:
621 llvm::report_fatal_error("Unknown output file type.\n");
622 } // end of switch
623 } // end of ! pInputFilename == "-"
624 } // end of if empty pOutputFilename
625
626 // Decide if we need "binary" output.
627 unsigned int fd_flags = 0x0;
628 switch (pFileType) {
629 default: assert(0 && "Unknown file type");
630 case mcld::CGFT_ASMFile:
631 break;
632 case mcld::CGFT_OBJFile:
633 case mcld::CGFT_DSOFile:
634 case mcld::CGFT_EXEFile:
635 case mcld::CGFT_NULLFile:
636 fd_flags |= raw_fd_ostream::F_Binary;
637 break;
638 }
639
640 // Open the file.
641 std::string err_mesg;
642 tool_output_file *result_output =
643 new tool_output_file(pOutputFilename.c_str(),
644 err_mesg,
645 fd_flags);
646 if (!err_mesg.empty()) {
647 errs() << err_mesg << '\n';
648 delete result_output;
649 return NULL;
650 }
651
652 return result_output;
653 }
654
ShouldColorize()655 static bool ShouldColorize()
656 {
657 const char* term = getenv("TERM");
658 return term && (0 != strcmp(term, "dumb"));
659 }
660
ProcessLinkerOptionsFromCommand(mcld::MCLDInfo & pLDInfo)661 static bool ProcessLinkerOptionsFromCommand(mcld::MCLDInfo& pLDInfo) {
662 // ----- Set up General Options ----- //
663 // set up soname
664 pLDInfo.output().setSOName(ArgSOName);
665
666 // set up sysroot
667 if (!ArgSysRoot.empty()) {
668 if (exists(ArgSysRoot) && is_directory(ArgSysRoot))
669 pLDInfo.options().setSysroot(ArgSysRoot);
670 }
671
672 // add all search directories
673 cl::list<mcld::MCLDDirectory>::iterator sd;
674 cl::list<mcld::MCLDDirectory>::iterator sdEnd = ArgSearchDirList.end();
675 for (sd=ArgSearchDirList.begin(); sd!=sdEnd; ++sd) {
676 if (sd->isInSysroot())
677 sd->setSysroot(pLDInfo.options().sysroot());
678 if (exists(sd->path()) && is_directory(sd->path())) {
679 pLDInfo.options().directories().add(*sd);
680 }
681 else {
682 // FIXME: need a warning function
683 errs() << "WARNING: can not open search directory `-L"
684 << sd->name()
685 << "'.\n";
686 }
687 }
688
689 pLDInfo.options().setPIE(ArgPIE);
690 pLDInfo.options().setTrace(ArgTrace);
691 pLDInfo.options().setVerbose(ArgVerbose);
692 pLDInfo.options().setMaxErrorNum(ArgMaxErrorNum);
693 pLDInfo.options().setMaxWarnNum(ArgMaxWarnNum);
694 pLDInfo.options().setEntry(ArgEntry);
695 pLDInfo.options().setBsymbolic(ArgBsymbolic);
696 pLDInfo.options().setBgroup(ArgBgroup);
697 pLDInfo.options().setDyld(ArgDyld);
698 pLDInfo.options().setNoUndefined(ArgNoUndefined);
699 pLDInfo.options().setMulDefs(ArgAllowMulDefs);
700 pLDInfo.options().setEhFrameHdr(ArgEhFrameHdr);
701
702 // set up rename map, for --wrap
703 cl::list<std::string>::iterator wname;
704 cl::list<std::string>::iterator wnameEnd = ArgWrapList.end();
705 for (wname = ArgWrapList.begin(); wname != wnameEnd; ++wname) {
706 bool exist = false;
707
708 // add wname -> __wrap_wname
709 mcld::StringEntry<llvm::StringRef>* to_wrap =
710 pLDInfo.scripts().renameMap().insert(*wname, exist);
711
712 std::string to_wrap_str = "__wrap_" + *wname;
713 to_wrap->setValue(to_wrap_str);
714
715 if (exist)
716 mcld::warning(mcld::diag::rewrap) << *wname << to_wrap_str;
717
718 // add __real_wname -> wname
719 std::string from_real_str = "__real_" + *wname;
720 mcld::StringEntry<llvm::StringRef>* from_real =
721 pLDInfo.scripts().renameMap().insert(from_real_str, exist);
722 from_real->setValue(*wname);
723 if (exist)
724 mcld::warning(mcld::diag::rewrap) << *wname << from_real_str;
725 } // end of for
726
727 // set up rename map, for --portable
728 cl::list<std::string>::iterator pname;
729 cl::list<std::string>::iterator pnameEnd = ArgPortList.end();
730 for (pname = ArgPortList.begin(); pname != pnameEnd; ++pname) {
731 bool exist = false;
732
733 // add pname -> pname_portable
734 mcld::StringEntry<llvm::StringRef>* to_port =
735 pLDInfo.scripts().renameMap().insert(*pname, exist);
736
737 std::string to_port_str = *pname + "_portable";
738 to_port->setValue(to_port_str);
739
740 if (exist)
741 mcld::warning(mcld::diag::rewrap) << *pname << to_port_str;
742
743 // add __real_pname -> pname
744 std::string from_real_str = "__real_" + *pname;
745 mcld::StringEntry<llvm::StringRef>* from_real =
746 pLDInfo.scripts().renameMap().insert(from_real_str, exist);
747
748 from_real->setValue(*pname);
749 if (exist)
750 mcld::warning(mcld::diag::rewrap) << *pname << from_real_str;
751 } // end of for
752
753 // set up colorize
754 switch (ArgColor) {
755 case color::Never:
756 pLDInfo.options().setColor(false);
757 break;
758 case color::Always:
759 pLDInfo.options().setColor(true);
760 break;
761 case color::Auto:
762 bool color_option = ShouldColorize() &&
763 llvm::sys::Process::FileDescriptorIsDisplayed(STDOUT_FILENO);
764 pLDInfo.options().setColor(color_option);
765 break;
766 }
767
768 // add -z options
769 cl::list<mcld::ZOption>::iterator zOpt;
770 cl::list<mcld::ZOption>::iterator zOptEnd = ArgZOptionList.end();
771 for (zOpt = ArgZOptionList.begin(); zOpt != zOptEnd; ++zOpt) {
772 pLDInfo.options().addZOption(*zOpt);
773 }
774
775 // ----- Set up Script Options ----- //
776
777 return true;
778 }
779
ProcessLinkerInputsFromCommand(mcld::SectLinkerOption & pOption)780 static bool ProcessLinkerInputsFromCommand(mcld::SectLinkerOption &pOption) {
781 // ----- Set up Inputs ----- //
782 // add all start-group
783 cl::list<bool>::iterator sg;
784 cl::list<bool>::iterator sgEnd = ArgStartGroupList.end();
785 for (sg=ArgStartGroupList.begin(); sg!=sgEnd; ++sg) {
786 // calculate position
787 pOption.appendOption(new mcld::StartGroupOption(
788 ArgStartGroupList.getPosition(sg-ArgStartGroupList.begin())));
789 }
790
791 // add all end-group
792 cl::list<bool>::iterator eg;
793 cl::list<bool>::iterator egEnd = ArgEndGroupList.end();
794 for (eg=ArgEndGroupList.begin(); eg!=egEnd; ++eg) {
795 // calculate position
796 pOption.appendOption(new mcld::EndGroupOption(
797 ArgEndGroupList.getPosition(eg-ArgEndGroupList.begin())));
798 }
799
800 // add all namespecs
801 cl::list<std::string>::iterator ns;
802 cl::list<std::string>::iterator nsEnd = ArgNameSpecList.end();
803 for (ns=ArgNameSpecList.begin(); ns!=nsEnd; ++ns) {
804 // calculate position
805 pOption.appendOption(new mcld::NamespecOption(
806 ArgNameSpecList.getPosition(ns-ArgNameSpecList.begin()),
807 *ns));
808 }
809
810 // add all object files
811 cl::list<mcld::sys::fs::Path>::iterator obj;
812 cl::list<mcld::sys::fs::Path>::iterator objEnd = ArgInputObjectFiles.end();
813 for (obj=ArgInputObjectFiles.begin(); obj!=objEnd; ++obj) {
814 // calculate position
815 pOption.appendOption(new mcld::InputFileOption(
816 ArgInputObjectFiles.getPosition(obj-ArgInputObjectFiles.begin()),
817 *obj));
818 }
819
820 // ----- Set up Attributes of Inputs ----- //
821 // --whole-archive
822 cl::list<bool>::iterator attr = ArgWholeArchiveList.begin();
823 cl::list<bool>::iterator attrEnd = ArgWholeArchiveList.end();
824 for (; attr!=attrEnd; ++attr) {
825 pOption.appendOption(new mcld::WholeArchiveOption(
826 ArgWholeArchiveList.getPosition(attr-ArgWholeArchiveList.begin())));
827 }
828
829 // --no-whole-archive
830 attr = ArgNoWholeArchiveList.begin();
831 attrEnd = ArgNoWholeArchiveList.end();
832 for (; attr!=attrEnd; ++attr) {
833 pOption.appendOption(new mcld::NoWholeArchiveOption(
834 ArgNoWholeArchiveList.getPosition(attr-ArgNoWholeArchiveList.begin())));
835 }
836
837 // --as-needed
838 attr = ArgAsNeededList.begin();
839 attrEnd = ArgAsNeededList.end();
840 while(attr != attrEnd) {
841 pOption.appendOption(new mcld::AsNeededOption(
842 ArgAsNeededList.getPosition(attr-ArgAsNeededList.begin())));
843 ++attr;
844 }
845
846 // --no-as-needed
847 attr = ArgNoAsNeededList.begin();
848 attrEnd = ArgNoAsNeededList.end();
849 while(attr != attrEnd) {
850 pOption.appendOption(new mcld::NoAsNeededOption(
851 ArgNoAsNeededList.getPosition(attr-ArgNoAsNeededList.begin())));
852 ++attr;
853 }
854
855 // --add-needed
856 attr = ArgAddNeededList.begin();
857 attrEnd = ArgAddNeededList.end();
858 while(attr != attrEnd) {
859 pOption.appendOption(new mcld::AddNeededOption(
860 ArgAddNeededList.getPosition(attr-ArgAddNeededList.begin())));
861 ++attr;
862 }
863
864 // --no-add-needed
865 attr = ArgNoAddNeededList.begin();
866 attrEnd = ArgNoAddNeededList.end();
867 while(attr != attrEnd) {
868 pOption.appendOption(new mcld::NoAddNeededOption(
869 ArgNoAddNeededList.getPosition(attr-ArgNoAddNeededList.begin())));
870 ++attr;
871 }
872
873 // -Bdynamic
874 attr = ArgBDynamicList.begin();
875 attrEnd = ArgBDynamicList.end();
876 while(attr != attrEnd) {
877 pOption.appendOption(new mcld::BDynamicOption(
878 ArgBDynamicList.getPosition(attr-ArgBDynamicList.begin())));
879 }
880
881 // -Bstatic
882 attr = ArgBStaticList.begin();
883 attrEnd = ArgBStaticList.end();
884 while(attr != attrEnd) {
885 pOption.appendOption(new mcld::BStaticOption(
886 ArgBStaticList.getPosition(attr-ArgBStaticList.begin())));
887 ++attr;
888 }
889
890 return true;
891 }
892
main(int argc,char * argv[])893 int main( int argc, char* argv[] )
894 {
895 LLVMContext &Context = getGlobalContext();
896 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
897 cl::ParseCommandLineOptions(argc, argv, "MCLinker\n");
898
899 #ifdef ENABLE_UNITTEST
900 if (UnitTest) {
901 return unit_test( argc, argv );
902 }
903 #endif
904
905 // Initialize targets first, so that --version shows registered targets.
906 InitializeAllTargets();
907 InitializeAllAsmPrinters();
908 InitializeAllAsmParsers();
909 InitializeAllTargetMCs();
910 mcld::InitializeAllTargets();
911 mcld::InitializeAllLinkers();
912 mcld::InitializeAllDiagnostics();
913
914 // Load the module to be compiled...
915 std::auto_ptr<Module> M;
916
917 // -shared
918 if (true == ArgShared) {
919 ArgFileType = mcld::CGFT_DSOFile;
920 }
921
922 // -V
923 if (ArgVersion) {
924 outs() << "MCLinker - ";
925 outs() << mcld::MCLDInfo::version();
926 outs() << "\n";
927 }
928
929 if (ArgBitcodeFilename.empty() &&
930 (mcld::CGFT_DSOFile != ArgFileType &&
931 mcld::CGFT_EXEFile != ArgFileType)) {
932 // If the file is not given, forcefully read from stdin
933 if (ArgVerbose >= 0) {
934 errs() << "** The bitcode/llvm asm file is not given. Read from stdin.\n"
935 << "** Specify input bitcode/llvm asm file by\n\n"
936 << " llvm-mcld -dB [the bitcode/llvm asm]\n\n";
937 }
938
939 ArgBitcodeFilename.assign("-");
940 }
941
942 if (!ArgBitcodeFilename.empty()) {
943 SMDiagnostic Err;
944 M.reset(ParseIRFile(ArgBitcodeFilename.native(), Err, Context));
945
946 if (M.get() == 0) {
947 Err.print(argv[0], errs());
948 errs() << "** Failed to to the given bitcode/llvm asm file '"
949 << ArgBitcodeFilename.native() << "'. **\n";
950 return 1;
951 }
952 }
953 else {
954 // If here, output must be dynamic shared object (mcld::CGFT_DSOFile) and
955 // executable file (mcld::CGFT_EXEFile).
956 M.reset(new Module("Empty Module", Context));
957 }
958 Module &mod = *M.get();
959
960 // If we are supposed to override the target triple, do so now.
961 Triple TheTriple;
962 if (!TargetTriple.empty()) {
963 TheTriple.setTriple(TargetTriple);
964 mod.setTargetTriple(TargetTriple);
965 }
966
967 // User doesn't specify the triple from command.
968 if (TheTriple.getTriple().empty()) {
969 // Try to get one from the input Module.
970 const std::string &TripleStr = mod.getTargetTriple();
971
972 if (TripleStr.empty())
973 TheTriple.setTriple(sys::getDefaultTargetTriple());
974 else
975 TheTriple.setTriple(TripleStr);
976 }
977
978 // Allocate target machine. First, check whether the user has explicitly
979 // specified an architecture to compile for. If so we have to look it up by
980 // name, because it might be a backend that has no mapping to a target triple.
981 const mcld::Target *TheTarget = 0;
982 if (!MArch.empty()) {
983 for (mcld::TargetRegistry::iterator it = mcld::TargetRegistry::begin(),
984 ie = mcld::TargetRegistry::end(); it != ie; ++it) {
985 if (MArch == (*it)->get()->getName()) {
986 TheTarget = *it;
987 break;
988 }
989 }
990
991 if (!TheTarget) {
992 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
993 return 1;
994 }
995
996 // Adjust the triple to match (if known), otherwise stick with the
997 // module/host triple.
998 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
999 if (Type != Triple::UnknownArch)
1000 TheTriple.setArch(Type);
1001 }
1002 else {
1003 std::string Err;
1004 TheTarget = mcld::TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
1005 if (TheTarget == 0) {
1006 errs() << "error: auto-selecting target `" << TheTriple.getTriple()
1007 << "'\n"
1008 << "Please use the -march option to explicitly select a target.\n"
1009 << "Example:\n"
1010 << " $ " << argv[0] << " -march=arm\n";
1011 return 1;
1012 }
1013 }
1014
1015 // Package up features to be passed to target/subtarget
1016 std::string FeaturesStr;
1017 if (MAttrs.size()) {
1018 SubtargetFeatures Features;
1019 for (unsigned i = 0; i != MAttrs.size(); ++i)
1020 Features.AddFeature(MAttrs[i]);
1021 FeaturesStr = Features.getString();
1022 }
1023
1024 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
1025 switch (OptLevel) {
1026 default:
1027 errs() << argv[0] << ": invalid optimization level.\n";
1028 return 1;
1029 case ' ': break;
1030 case '0': OLvl = CodeGenOpt::None; break;
1031 case '1': OLvl = CodeGenOpt::Less; break;
1032 case '2': OLvl = CodeGenOpt::Default; break;
1033 case '3': OLvl = CodeGenOpt::Aggressive; break;
1034 }
1035
1036 // set -fPIC
1037 if (ArgFPIC)
1038 ArgRelocModel = Reloc::PIC_;
1039
1040 TargetOptions Options;
1041 Options.LessPreciseFPMADOption = EnableFPMAD;
1042 Options.NoFramePointerElim = DisableFPElim;
1043 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
1044 Options.AllowFPOpFusion = FuseFPOps;
1045 Options.UnsafeFPMath = EnableUnsafeFPMath;
1046 Options.NoInfsFPMath = EnableNoInfsFPMath;
1047 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
1048 Options.HonorSignDependentRoundingFPMathOption =
1049 EnableHonorSignDependentRoundingFPMath;
1050 Options.UseSoftFloat = GenerateSoftFloatCalls;
1051 if (FloatABIForCalls != FloatABI::Default)
1052 Options.FloatABIType = FloatABIForCalls;
1053 Options.NoZerosInBSS = DontPlaceZerosInBSS;
1054 Options.JITExceptionHandling = EnableJITExceptionHandling;
1055 Options.JITEmitDebugInfo = EmitJitDebugInfo;
1056 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
1057 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
1058 Options.StackAlignmentOverride = OverrideStackAlignment;
1059 Options.RealignStack = EnableRealignStack;
1060 Options.TrapFuncName = TrapFuncName;
1061 Options.EnableSegmentedStacks = SegmentedStacks;
1062
1063 std::auto_ptr<mcld::LLVMTargetMachine> target_machine(
1064 TheTarget->createTargetMachine(TheTriple.getTriple(),
1065 MCPU, FeaturesStr, Options,
1066 ArgRelocModel, CMModel, OLvl));
1067 assert(target_machine.get() && "Could not allocate target machine!");
1068 mcld::LLVMTargetMachine &TheTargetMachine = *target_machine.get();
1069
1070 TheTargetMachine.getTM().setMCUseLoc(false);
1071 TheTargetMachine.getTM().setMCUseCFI(false);
1072
1073 // Set up mcld::outs() and mcld::errs()
1074 InitializeOStreams(TheTargetMachine.getLDInfo());
1075
1076 // Set up MsgHandler
1077 OwningPtr<mcld::DiagnosticLineInfo>
1078 diag_line_info(TheTarget->createDiagnosticLineInfo(*TheTarget,
1079 TheTriple.getTriple()));
1080 OwningPtr<mcld::DiagnosticPrinter>
1081 diag_printer(new mcld::TextDiagnosticPrinter(mcld::errs(),
1082 TheTargetMachine.getLDInfo()));
1083
1084 mcld::InitializeDiagnosticEngine(TheTargetMachine.getLDInfo(),
1085 diag_line_info.take(),
1086 diag_printer.get());
1087
1088
1089 // Figure out where we are going to send the output...
1090 OwningPtr<tool_output_file>
1091 Out(GetOutputStream(TheTarget->get()->getName(),
1092 TheTriple.getOS(),
1093 ArgFileType,
1094 ArgBitcodeFilename,
1095 ArgOutputFilename));
1096 if (!Out) {
1097 // FIXME: show some error message pls.
1098 return 1;
1099 }
1100
1101 // Build up all of the passes that we want to do to the module.
1102 PassManager PM;
1103
1104 // Add the target data from the target machine, if it exists, or the module.
1105 if (const TargetData *TD = TheTargetMachine.getTM().getTargetData())
1106 PM.add(new TargetData(*TD));
1107 else
1108 PM.add(new TargetData(&mod));
1109
1110 // Override default to generate verbose assembly.
1111 TheTargetMachine.getTM().setAsmVerbosityDefault(true);
1112
1113 // Process the linker input from the command line
1114 mcld::SectLinkerOption *LinkerOpt =
1115 new mcld::SectLinkerOption(TheTargetMachine.getLDInfo());
1116
1117 if (!ProcessLinkerOptionsFromCommand(TheTargetMachine.getLDInfo())) {
1118 errs() << argv[0] << ": failed to process linker options from command line!\n";
1119 return 1;
1120 }
1121
1122 if (!ProcessLinkerInputsFromCommand(*LinkerOpt)) {
1123 errs() << argv[0] << ": failed to process inputs from command line!\n";
1124 return 1;
1125 }
1126
1127 {
1128 formatted_raw_ostream FOS(Out->os());
1129
1130 // Ask the target to add backend passes as necessary.
1131 if( TheTargetMachine.addPassesToEmitFile(PM,
1132 FOS,
1133 ArgOutputFilename.native(),
1134 ArgFileType,
1135 OLvl,
1136 LinkerOpt,
1137 NoVerify)) {
1138 errs() << argv[0] << ": target does not support generation of this"
1139 << " file type!\n";
1140 return 1;
1141 }
1142
1143 // Before executing passes, print the final values of the LLVM options.
1144 cl::PrintOptionValues();
1145
1146 PM.run(mod);
1147 }
1148
1149 // Declare success.
1150 Out->keep();
1151
1152 // clean up
1153 delete LinkerOpt;
1154
1155 if (0 != diag_printer->getNumErrors()) {
1156 // If we reached here, we are failing ungracefully. Run the interrupt handlers
1157 // to make sure any special cleanups get done, in particular that we remove
1158 // files registered with RemoveFileOnSignal.
1159 llvm::sys::RunInterruptHandlers();
1160 diag_printer->finish();
1161 exit(1);
1162 }
1163
1164 diag_printer->finish();
1165 return 0;
1166 }
1167
1168