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