diff options
author | Dimitry Andric <dim@FreeBSD.org> | 2016-07-23 20:48:50 +0000 |
---|---|---|
committer | Dimitry Andric <dim@FreeBSD.org> | 2016-07-23 20:48:50 +0000 |
commit | 1c98619801a5705c688e683be3ef9d70169a0686 (patch) | |
tree | 8422105cd1a94c368315f2db16b9ac746cf7c000 /include/lld/Core | |
parent | f4f3ce4613680903220815690ad79fc7ba0a2e26 (diff) |
Notes
Diffstat (limited to 'include/lld/Core')
-rw-r--r-- | include/lld/Core/Alias.h | 100 | ||||
-rw-r--r-- | include/lld/Core/ArchiveLibraryFile.h | 15 | ||||
-rw-r--r-- | include/lld/Core/Atom.h | 53 | ||||
-rw-r--r-- | include/lld/Core/DefinedAtom.h | 50 | ||||
-rw-r--r-- | include/lld/Core/Error.h | 42 | ||||
-rw-r--r-- | include/lld/Core/File.h | 120 | ||||
-rw-r--r-- | include/lld/Core/LLVM.h | 6 | ||||
-rw-r--r-- | include/lld/Core/LinkingContext.h | 150 | ||||
-rw-r--r-- | include/lld/Core/Node.h | 6 | ||||
-rw-r--r-- | include/lld/Core/Parallel.h | 36 | ||||
-rw-r--r-- | include/lld/Core/Pass.h | 4 | ||||
-rw-r--r-- | include/lld/Core/PassManager.h | 7 | ||||
-rw-r--r-- | include/lld/Core/Reader.h | 9 | ||||
-rw-r--r-- | include/lld/Core/Reference.h | 18 | ||||
-rw-r--r-- | include/lld/Core/Resolver.h | 41 | ||||
-rw-r--r-- | include/lld/Core/STDExtras.h | 29 | ||||
-rw-r--r-- | include/lld/Core/SharedLibraryAtom.h | 4 | ||||
-rw-r--r-- | include/lld/Core/SharedLibraryFile.h | 21 | ||||
-rw-r--r-- | include/lld/Core/Simple.h | 150 | ||||
-rw-r--r-- | include/lld/Core/SymbolTable.h | 11 | ||||
-rw-r--r-- | include/lld/Core/UndefinedAtom.h | 10 | ||||
-rw-r--r-- | include/lld/Core/Writer.h | 11 | ||||
-rw-r--r-- | include/lld/Core/range.h | 738 |
23 files changed, 335 insertions, 1296 deletions
diff --git a/include/lld/Core/Alias.h b/include/lld/Core/Alias.h deleted file mode 100644 index fa999292fbd3..000000000000 --- a/include/lld/Core/Alias.h +++ /dev/null @@ -1,100 +0,0 @@ -//===- lld/Core/Alias.h - Alias atoms -------------------------------------===// -// -// The LLVM Linker -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file -/// \brief Provide alias atoms. -/// -//===----------------------------------------------------------------------===// - -#ifndef LLD_CORE_ALIAS_H -#define LLD_CORE_ALIAS_H - -#include "lld/Core/LLVM.h" -#include "lld/Core/Simple.h" -#include "llvm/ADT/Optional.h" -#include <string> - -namespace lld { - -// An AliasAtom is a zero-size atom representing an alias for other atom. It has -// a LayoutAfter reference to the target atom, so that this atom and the target -// atom will be laid out at the same location in the final result. Initially -// the target atom is an undefined atom. Resolver will replace it with a defined -// one. -// -// It does not have attributes itself. Most member function calls are forwarded -// to the target atom. -class AliasAtom : public SimpleDefinedAtom { -public: - AliasAtom(const File &file, StringRef name) - : SimpleDefinedAtom(file), _name(name) {} - - StringRef name() const override { return _name; } - uint64_t size() const override { return 0; } - ArrayRef<uint8_t> rawContent() const override { return ArrayRef<uint8_t>(); } - - Scope scope() const override { - getTarget(); - return _target ? _target->scope() : scopeLinkageUnit; - } - - Merge merge() const override { - if (_merge.hasValue()) - return _merge.getValue(); - getTarget(); - return _target ? _target->merge() : mergeNo; - } - - void setMerge(Merge val) { _merge = val; } - - ContentType contentType() const override { - getTarget(); - return _target ? _target->contentType() : typeUnknown; - } - - Interposable interposable() const override { - getTarget(); - return _target ? _target->interposable() : interposeNo; - } - - SectionChoice sectionChoice() const override { - getTarget(); - return _target ? _target->sectionChoice() : sectionBasedOnContent; - } - - StringRef customSectionName() const override { - getTarget(); - return _target ? _target->customSectionName() : StringRef(""); - } - - DeadStripKind deadStrip() const override { return _deadStrip; } - void setDeadStrip(DeadStripKind val) { _deadStrip = val; } - -private: - void getTarget() const { - if (_target) - return; - for (const Reference *r : *this) { - if (r->kindNamespace() == lld::Reference::KindNamespace::all && - r->kindValue() == lld::Reference::kindLayoutAfter) { - _target = dyn_cast<DefinedAtom>(r->target()); - return; - } - } - } - - std::string _name; - mutable const DefinedAtom *_target = nullptr; - llvm::Optional<Merge> _merge = DefinedAtom::mergeNo; - DeadStripKind _deadStrip = DefinedAtom::deadStripNormal; -}; - -} // end namespace lld - -#endif diff --git a/include/lld/Core/ArchiveLibraryFile.h b/include/lld/Core/ArchiveLibraryFile.h index ff379d4f3ecf..2c736e7d6c61 100644 --- a/include/lld/Core/ArchiveLibraryFile.h +++ b/include/lld/Core/ArchiveLibraryFile.h @@ -11,7 +11,6 @@ #define LLD_CORE_ARCHIVE_LIBRARY_FILE_H #include "lld/Core/File.h" -#include "lld/Core/Parallel.h" #include <set> namespace lld { @@ -33,23 +32,11 @@ public: /// Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. - virtual File *find(StringRef name, bool dataSymbolOnly) = 0; + virtual File *find(StringRef name) = 0; virtual std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) = 0; - // Parses a member file containing a given symbol, so that when you - // need the file find() can return that immediately. Calling this function - // has no side effect other than pre-instantiating a file. Calling this - // function doesn't affect correctness. - virtual void preload(TaskGroup &group, StringRef symbolName) {} - - /// Returns a set of all defined symbols in the archive, i.e. all - /// resolvable symbol using this file. - virtual std::set<StringRef> getDefinedSymbols() { - return std::set<StringRef>(); - } - protected: /// only subclasses of ArchiveLibraryFile can be instantiated ArchiveLibraryFile(StringRef path) : File(path, kindArchiveLibrary) {} diff --git a/include/lld/Core/Atom.h b/include/lld/Core/Atom.h index 27fdde022ba7..42ca2bb8af8c 100644 --- a/include/lld/Core/Atom.h +++ b/include/lld/Core/Atom.h @@ -16,6 +16,9 @@ namespace lld { class File; +template<typename T> +class OwningAtomPtr; + /// /// The linker has a Graph Theory model of linking. An object file is seen /// as a set of Atoms with References to other Atoms. Each Atom is a node @@ -24,6 +27,7 @@ class File; /// undefined symbol (extern declaration). /// class Atom { + template<typename T> friend class OwningAtomPtr; public: /// Whether this atom is defined or a proxy for an undefined symbol enum Definition { @@ -71,6 +75,55 @@ private: Definition _definition; }; +/// Class which owns an atom pointer and runs the atom destructor when the +/// owning pointer goes out of scope. +template<typename T> +class OwningAtomPtr { +private: + OwningAtomPtr(const OwningAtomPtr &) = delete; + void operator=(const OwningAtomPtr&) = delete; +public: + OwningAtomPtr() : atom(nullptr) { } + OwningAtomPtr(T *atom) : atom(atom) { } + + ~OwningAtomPtr() { + if (atom) + runDestructor(atom); + } + + void runDestructor(Atom *atom) { + atom->~Atom(); + } + + OwningAtomPtr(OwningAtomPtr &&ptr) : atom(ptr.atom) { + ptr.atom = nullptr; + } + + void operator=(OwningAtomPtr&& ptr) { + if (atom) + runDestructor(atom); + atom = ptr.atom; + ptr.atom = nullptr; + } + + T *const &get() const { + return atom; + } + + T *&get() { + return atom; + } + + T *release() { + auto *v = atom; + atom = nullptr; + return v; + } + +private: + T *atom; +}; + } // namespace lld #endif // LLD_CORE_ATOM_H diff --git a/include/lld/Core/DefinedAtom.h b/include/lld/Core/DefinedAtom.h index e4d4488ccdca..e3193f8aaf2e 100644 --- a/include/lld/Core/DefinedAtom.h +++ b/include/lld/Core/DefinedAtom.h @@ -11,11 +11,12 @@ #define LLD_CORE_DEFINED_ATOM_H #include "lld/Core/Atom.h" +#include "lld/Core/Reference.h" #include "lld/Core/LLVM.h" +#include "llvm/Support/ErrorHandling.h" namespace lld { class File; -class Reference; /// \brief The fundamental unit of linking. /// @@ -105,6 +106,7 @@ public: enum ContentType { typeUnknown, // for use with definitionUndefined + typeMachHeader, // atom representing mach_header [Darwin] typeCode, // executable code typeResolver, // function which returns address of target typeBranchIsland, // linker created for large binaries @@ -127,6 +129,7 @@ public: typeObjC1Class, // ObjC1 class [Darwin] typeLazyPointer, // pointer through which a stub jumps typeLazyDylibPointer, // pointer through which a stub jumps [Darwin] + typeNonLazyPointer, // pointer to external symbol typeCFString, // NS/CFString object [Darwin] typeGOT, // pointer to external symbol typeInitializerPtr, // pointer to initializer function @@ -134,6 +137,8 @@ public: typeCStringPtr, // pointer to UTF8 C string [Darwin] typeObjCClassPtr, // pointer to ObjC class [Darwin] typeObjC2CategoryList, // pointers to ObjC category [Darwin] + typeObjCImageInfo, // pointer to ObjC class [Darwin] + typeObjCMethodList, // pointer to ObjC method list [Darwin] typeDTraceDOF, // runtime data for Dtrace [Darwin] typeInterposingTuples, // tuples of interposing info for dyld [Darwin] typeTempLTO, // temporary atom for bitcode reader @@ -143,14 +148,7 @@ public: typeTLVInitialData, // initial data for a TLV [Darwin] typeTLVInitialZeroFill, // TLV initial zero fill data [Darwin] typeTLVInitializerPtr, // pointer to thread local initializer [Darwin] - typeMachHeader, // atom representing mach_header [Darwin] - typeThreadZeroFill, // Uninitialized thread local data(TBSS) [ELF] - typeThreadData, // Initialized thread local data(TDATA) [ELF] - typeRONote, // Identifies readonly note sections [ELF] - typeRWNote, // Identifies readwrite note sections [ELF] - typeNoAlloc, // Identifies non allocatable sections [ELF] - typeGroupComdat, // Identifies a section group [ELF, COFF] - typeGnuLinkOnce, // Identifies a gnu.linkonce section [ELF] + typeDSOHandle, // atom representing DSO handle [Darwin] typeSectCreate, // Created via the -sectcreate option [Darwin] }; @@ -218,11 +216,6 @@ public: /// /// This is used by the linker to order the layout of Atoms so that the /// resulting image is stable and reproducible. - /// - /// Note that this should not be confused with ordinals of exported symbols in - /// Windows DLLs. In Windows terminology, ordinals are symbols' export table - /// indices (small integers) which can be used instead of symbol names to - /// refer items in a DLL. virtual uint64_t ordinal() const = 0; /// \brief the number of bytes of space this atom's content will occupy in the @@ -307,8 +300,12 @@ public: return _atom.derefIterator(_it); } + bool operator==(const reference_iterator &other) const { + return _it == other._it; + } + bool operator!=(const reference_iterator &other) const { - return _it != other._it; + return !(*this == other); } reference_iterator &operator++() { @@ -326,6 +323,14 @@ public: /// \brief Returns an iterator to the end of this Atom's References. virtual reference_iterator end() const = 0; + /// Adds a reference to this atom. + virtual void addReference(Reference::KindNamespace ns, + Reference::KindArch arch, + Reference::KindValue kindValue, uint64_t off, + const Atom *target, Reference::Addend a) { + llvm_unreachable("Subclass does not permit adding references"); + } + static bool classof(const Atom *a) { return a->definition() == definitionRegular; } @@ -338,16 +343,15 @@ public: ContentType atomContentType = contentType(); return !(atomContentType == DefinedAtom::typeZeroFill || atomContentType == DefinedAtom::typeZeroFillFast || - atomContentType == DefinedAtom::typeTLVInitialZeroFill || - atomContentType == DefinedAtom::typeThreadZeroFill); + atomContentType == DefinedAtom::typeTLVInitialZeroFill); } - /// Utility function to check if the atom belongs to a group section - /// that represents section groups or .gnu.linkonce sections. - bool isGroupParent() const { + /// Utility function to check if relocations in this atom to other defined + /// atoms can be implicitly generated, and so we don't need to explicitly + /// emit those relocations. + bool relocsToDefinedCanBeImplicit() const { ContentType atomContentType = contentType(); - return (atomContentType == DefinedAtom::typeGroupComdat || - atomContentType == DefinedAtom::typeGnuLinkOnce); + return atomContentType == typeCFI; } // Returns true if lhs should be placed before rhs in the final output. @@ -359,6 +363,8 @@ protected: // constructor. DefinedAtom() : Atom(definitionRegular) { } + ~DefinedAtom() override = default; + /// \brief Returns a pointer to the Reference object that the abstract /// iterator "points" to. virtual const Reference *derefIterator(const void *iter) const = 0; diff --git a/include/lld/Core/Error.h b/include/lld/Core/Error.h index a7e61f91d8e9..b0bf73b1cb7b 100644 --- a/include/lld/Core/Error.h +++ b/include/lld/Core/Error.h @@ -15,6 +15,8 @@ #define LLD_CORE_ERROR_H #include "lld/Core/LLVM.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/Error.h" #include <system_error> namespace lld { @@ -30,39 +32,37 @@ inline std::error_code make_error_code(YamlReaderError e) { return std::error_code(static_cast<int>(e), YamlReaderCategory()); } -const std::error_category &LinkerScriptReaderCategory(); - -enum class LinkerScriptReaderError { - success = 0, - parse_error, - unknown_symbol_in_expr, - unrecognized_function_in_expr, - unknown_phdr_ids, - extra_program_phdr, - misplaced_program_phdr, - program_phdr_wrong_phdrs, -}; - -inline std::error_code make_error_code(LinkerScriptReaderError e) { - return std::error_code(static_cast<int>(e), LinkerScriptReaderCategory()); -} - /// Creates an error_code object that has associated with it an arbitrary /// error messsage. The value() of the error_code will always be non-zero /// but its value is meaningless. The messsage() will be (a copy of) the /// supplied error string. /// Note: Once ErrorOr<> is updated to work with errors other than error_code, /// this can be updated to return some other kind of error. -std::error_code make_dynamic_error_code(const char *msg); std::error_code make_dynamic_error_code(StringRef msg); -std::error_code make_dynamic_error_code(const Twine &msg); + +/// Generic error. +/// +/// For errors that don't require their own specific sub-error (most errors) +/// this class can be used to describe the error via a string message. +class GenericError : public llvm::ErrorInfo<GenericError> { +public: + static char ID; + GenericError(Twine Msg); + const std::string &getMessage() const { return Msg; } + void log(llvm::raw_ostream &OS) const override; + + std::error_code convertToErrorCode() const override { + return make_dynamic_error_code(getMessage()); + } + +private: + std::string Msg; +}; } // end namespace lld namespace std { template <> struct is_error_code_enum<lld::YamlReaderError> : std::true_type {}; -template <> -struct is_error_code_enum<lld::LinkerScriptReaderError> : std::true_type {}; } #endif diff --git a/include/lld/Core/File.h b/include/lld/Core/File.h index 494e50065340..20418688dfa0 100644 --- a/include/lld/Core/File.h +++ b/include/lld/Core/File.h @@ -14,8 +14,8 @@ #include "lld/Core/DefinedAtom.h" #include "lld/Core/SharedLibraryAtom.h" #include "lld/Core/UndefinedAtom.h" -#include "lld/Core/range.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ErrorHandling.h" #include <functional> @@ -45,9 +45,18 @@ public: /// \brief Kinds of files that are supported. enum Kind { - kindObject, ///< object file (.o) - kindSharedLibrary, ///< shared library (.so) - kindArchiveLibrary ///< archive (.a) + kindErrorObject, ///< a error object file (.o) + kindNormalizedObject, ///< a normalized file (.o) + kindMachObject, ///< a MachO object file (.o) + kindCEntryObject, ///< a file for CEntries + kindHeaderObject, ///< a file for file headers + kindEntryObject, ///< a file for the entry + kindUndefinedSymsObject, ///< a file for undefined symbols + kindStubHelperObject, ///< a file for stub helpers + kindResolverMergedObject, ///< the resolver merged file. + kindSectCreateObject, ///< a sect create object file (.o) + kindSharedLibrary, ///< shared library (.so) + kindArchiveLibrary ///< archive (.a) }; /// \brief Returns file kind. Need for dyn_cast<> on File objects. @@ -97,17 +106,69 @@ public: } /// The type of atom mutable container. - template <typename T> using AtomVector = std::vector<const T *>; + template <typename T> using AtomVector = std::vector<OwningAtomPtr<T>>; - /// The range type for the atoms. It's backed by a std::vector, but hides - /// its member functions so that you can only call begin or end. + /// The range type for the atoms. template <typename T> class AtomRange { public: - AtomRange(AtomVector<T> v) : _v(v) {} - typename AtomVector<T>::const_iterator begin() const { return _v.begin(); } - typename AtomVector<T>::const_iterator end() const { return _v.end(); } - typename AtomVector<T>::iterator begin() { return _v.begin(); } - typename AtomVector<T>::iterator end() { return _v.end(); } + AtomRange(AtomVector<T> &v) : _v(v) {} + AtomRange(const AtomVector<T> &v) : _v(const_cast<AtomVector<T> &>(v)) {} + + typedef std::pointer_to_unary_function<const OwningAtomPtr<T>&, + const T*> ConstDerefFn; + + typedef std::pointer_to_unary_function<OwningAtomPtr<T>&, T*> DerefFn; + + typedef llvm::mapped_iterator<typename AtomVector<T>::const_iterator, + ConstDerefFn> ConstItTy; + typedef llvm::mapped_iterator<typename AtomVector<T>::iterator, + DerefFn> ItTy; + + static const T* DerefConst(const OwningAtomPtr<T> &p) { + return p.get(); + } + + static T* Deref(OwningAtomPtr<T> &p) { + return p.get(); + } + + ConstItTy begin() const { + return ConstItTy(_v.begin(), ConstDerefFn(DerefConst)); + } + ConstItTy end() const { + return ConstItTy(_v.end(), ConstDerefFn(DerefConst)); + } + + ItTy begin() { + return ItTy(_v.begin(), DerefFn(Deref)); + } + ItTy end() { + return ItTy(_v.end(), DerefFn(Deref)); + } + + llvm::iterator_range<typename AtomVector<T>::iterator> owning_ptrs() { + return llvm::make_range(_v.begin(), _v.end()); + } + + llvm::iterator_range<typename AtomVector<T>::iterator> owning_ptrs() const { + return llvm::make_range(_v.begin(), _v.end()); + } + + bool empty() const { + return _v.empty(); + } + + size_t size() const { + return _v.size(); + } + + const OwningAtomPtr<T> &operator[](size_t idx) const { + return _v[idx]; + } + + OwningAtomPtr<T> &operator[](size_t idx) { + return _v[idx]; + } private: AtomVector<T> &_v; @@ -115,19 +176,25 @@ public: /// \brief Must be implemented to return the AtomVector object for /// all DefinedAtoms in this File. - virtual const AtomVector<DefinedAtom> &defined() const = 0; + virtual const AtomRange<DefinedAtom> defined() const = 0; /// \brief Must be implemented to return the AtomVector object for /// all UndefinedAtomw in this File. - virtual const AtomVector<UndefinedAtom> &undefined() const = 0; + virtual const AtomRange<UndefinedAtom> undefined() const = 0; /// \brief Must be implemented to return the AtomVector object for /// all SharedLibraryAtoms in this File. - virtual const AtomVector<SharedLibraryAtom> &sharedLibrary() const = 0; + virtual const AtomRange<SharedLibraryAtom> sharedLibrary() const = 0; /// \brief Must be implemented to return the AtomVector object for /// all AbsoluteAtoms in this File. - virtual const AtomVector<AbsoluteAtom> &absolute() const = 0; + virtual const AtomRange<AbsoluteAtom> absolute() const = 0; + + /// Drop all of the atoms owned by this file. This will result in all of + /// the atoms running their destructors. + /// This is required because atoms may be allocated on a BumpPtrAllocator + /// of a different file. We need to destruct all atoms before any files. + virtual void clearAtoms() = 0; /// \brief If a file is parsed using a different method than doParse(), /// one must use this method to set the last error status, so that @@ -137,14 +204,6 @@ public: std::error_code parse(); - // This function is called just before the core linker tries to use - // a file. Currently the PECOFF reader uses this to trigger the - // driver to parse .drectve section (which contains command line options). - // If you want to do something having side effects, don't do that in - // doParse() because a file could be pre-loaded speculatively. - // Use this hook instead. - virtual void beforeLink() {} - // Usually each file owns a std::unique_ptr<MemoryBuffer>. // However, there's one special case. If a file is an archive file, // the archive file and its children all shares the same memory buffer. @@ -190,23 +249,26 @@ private: class ErrorFile : public File { public: ErrorFile(StringRef path, std::error_code ec) - : File(path, kindObject), _ec(ec) {} + : File(path, kindErrorObject), _ec(ec) {} std::error_code doParse() override { return _ec; } - const AtomVector<DefinedAtom> &defined() const override { + const AtomRange<DefinedAtom> defined() const override { llvm_unreachable("internal error"); } - const AtomVector<UndefinedAtom> &undefined() const override { + const AtomRange<UndefinedAtom> undefined() const override { llvm_unreachable("internal error"); } - const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { + const AtomRange<SharedLibraryAtom> sharedLibrary() const override { llvm_unreachable("internal error"); } - const AtomVector<AbsoluteAtom> &absolute() const override { + const AtomRange<AbsoluteAtom> absolute() const override { llvm_unreachable("internal error"); } + void clearAtoms() override { + } + private: std::error_code _ec; }; diff --git a/include/lld/Core/LLVM.h b/include/lld/Core/LLVM.h index d532c17fbfdf..ccf08859f4ae 100644 --- a/include/lld/Core/LLVM.h +++ b/include/lld/Core/LLVM.h @@ -23,6 +23,7 @@ namespace llvm { // ADT's. + class Error; class StringRef; class Twine; class MemoryBuffer; @@ -38,6 +39,9 @@ namespace llvm { template<typename T> class ErrorOr; + template<typename T> + class Expected; + class raw_ostream; // TODO: DenseMap, ... } @@ -51,6 +55,7 @@ namespace lld { using llvm::cast_or_null; // ADT's. + using llvm::Error; using llvm::StringRef; using llvm::Twine; using llvm::MemoryBuffer; @@ -61,6 +66,7 @@ namespace lld { using llvm::SmallVectorImpl; using llvm::SaveAndRestore; using llvm::ErrorOr; + using llvm::Expected; using llvm::raw_ostream; } // end namespace lld. diff --git a/include/lld/Core/LinkingContext.h b/include/lld/Core/LinkingContext.h index a723854b3c91..7e4edaf22cf3 100644 --- a/include/lld/Core/LinkingContext.h +++ b/include/lld/Core/LinkingContext.h @@ -13,9 +13,7 @@ #include "lld/Core/Error.h" #include "lld/Core/LLVM.h" #include "lld/Core/Node.h" -#include "lld/Core/Parallel.h" #include "lld/Core/Reference.h" -#include "lld/Core/range.h" #include "lld/Core/Reader.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/raw_ostream.h" @@ -33,16 +31,9 @@ class SharedLibraryFile; /// /// The base class LinkingContext contains the options needed by core linking. /// Subclasses of LinkingContext have additional options needed by specific -/// Writers. For example, ELFLinkingContext has methods that supplies -/// options to the ELF Writer and ELF Passes. +/// Writers. class LinkingContext { public: - /// \brief The types of output file that the linker creates. - enum class OutputFileType : uint8_t { - Default, // The default output type for this target - YAML, // The output type is set to YAML - }; - virtual ~LinkingContext(); /// \name Methods needed by core linking @@ -78,28 +69,6 @@ public: _deadStripRoots.push_back(symbolName); } - /// Archive files (aka static libraries) are normally lazily loaded. That is, - /// object files within an archive are only loaded and linked in, if the - /// object file contains a DefinedAtom which will replace an existing - /// UndefinedAtom. If this method returns true, core linking will also look - /// for archive members to replace existing tentative definitions in addition - /// to replacing undefines. Note: a "tentative definition" (also called a - /// "common" symbols) is a C (but not C++) concept. They are modeled in lld - /// as a DefinedAtom with merge() of mergeAsTentative. - bool searchArchivesToOverrideTentativeDefinitions() const { - return _searchArchivesToOverrideTentativeDefinitions; - } - - /// Normally core linking will turn a tentative definition into a real - /// definition if not replaced by a real DefinedAtom from some object file. - /// If this method returns true, core linking will search all supplied - /// dynamic shared libraries for symbol names that match remaining tentative - /// definitions. If any are found, the corresponding tentative definition - /// atom is replaced with SharedLibraryAtom. - bool searchSharedLibrariesToOverrideTentativeDefinitions() const { - return _searchSharedLibrariesToOverrideTentativeDefinitions; - } - /// Normally, every UndefinedAtom must be replaced by a DefinedAtom or a /// SharedLibraryAtom for the link to be successful. This method controls /// whether core linking prints out a list of remaining UndefinedAtoms. @@ -114,35 +83,6 @@ public: /// whether core linking considers remaining undefines to be an error. bool allowRemainingUndefines() const { return _allowRemainingUndefines; } - /// In the lld model, a SharedLibraryAtom is a proxy atom for something - /// that will be found in a dynamic shared library when the program runs. - /// A SharedLibraryAtom optionally contains the name of the shared library - /// in which to find the symbol name at runtime. Core linking may merge - /// two SharedLibraryAtom with the same name. If this method returns true, - /// when merging core linking will also verify that they both have the same - /// loadName() and if not print a warning. - /// - /// \todo This should be a method core linking calls so that drivers can - /// format the warning as needed. - bool warnIfCoalesableAtomsHaveDifferentLoadName() const { - return _warnIfCoalesableAtomsHaveDifferentLoadName; - } - - /// In C/C++ you can mark a function's prototype with - /// __attribute__((weak_import)) or __attribute__((weak)) to say the function - /// may not be available at runtime and/or build time and in which case its - /// address will evaluate to NULL. In lld this is modeled using the - /// UndefinedAtom::canBeNull() method. During core linking, UndefinedAtom - /// with the same name are automatically merged. If this method returns - /// true, core link also verfies that the canBeNull() value for merged - /// UndefinedAtoms are the same and warns if not. - /// - /// \todo This should be a method core linking calls so that drivers can - /// format the warning as needed. - bool warnIfCoalesableAtomsHaveDifferentCanBeNull() const { - return _warnIfCoalesableAtomsHaveDifferentCanBeNull; - } - /// Normally, every UndefinedAtom must be replaced by a DefinedAtom or a /// SharedLibraryAtom for the link to be successful. This method controls /// whether core linking considers remaining undefines from the shared library @@ -176,20 +116,7 @@ public: } void setDeadStripping(bool enable) { _deadStrip = enable; } - void setAllowDuplicates(bool enable) { _allowDuplicates = enable; } void setGlobalsAreDeadStripRoots(bool v) { _globalsAreDeadStripRoots = v; } - void setSearchArchivesToOverrideTentativeDefinitions(bool search) { - _searchArchivesToOverrideTentativeDefinitions = search; - } - void setSearchSharedLibrariesToOverrideTentativeDefinitions(bool search) { - _searchSharedLibrariesToOverrideTentativeDefinitions = search; - } - void setWarnIfCoalesableAtomsHaveDifferentCanBeNull(bool warn) { - _warnIfCoalesableAtomsHaveDifferentCanBeNull = warn; - } - void setWarnIfCoalesableAtomsHaveDifferentLoadName(bool warn) { - _warnIfCoalesableAtomsHaveDifferentLoadName = warn; - } void setPrintRemainingUndefines(bool print) { _printRemainingUndefines = print; } @@ -199,27 +126,11 @@ public: void setAllowShlibUndefines(bool allow) { _allowShlibUndefines = allow; } void setLogInputFiles(bool log) { _logInputFiles = log; } - // Returns true if multiple definitions should not be treated as a - // fatal error. - bool getAllowDuplicates() const { return _allowDuplicates; } - void appendLLVMOption(const char *opt) { _llvmOptions.push_back(opt); } - void addAlias(StringRef from, StringRef to) { _aliasSymbols[from] = to; } - const std::map<std::string, std::string> &getAliases() const { - return _aliasSymbols; - } - std::vector<std::unique_ptr<Node>> &getNodes() { return _nodes; } const std::vector<std::unique_ptr<Node>> &getNodes() const { return _nodes; } - /// Notify the LinkingContext when the symbol table found a name collision. - /// The useNew parameter specifies which the symbol table plans to keep, - /// but that can be changed by the LinkingContext. This is also an - /// opportunity for flavor specific processing. - virtual void notifySymbolTableCoalesce(const Atom *existingAtom, - const Atom *newAtom, bool &useNew) {} - /// This method adds undefined symbols specified by the -u option to the to /// the list of undefined symbols known to the linker. This option essentially /// forces an undefined symbol to be created. You may also need to call @@ -242,7 +153,7 @@ public: /// Return the list of undefined symbols that are specified in the /// linker command line, using the -u option. - range<const StringRef *> initialUndefinedSymbols() const { + ArrayRef<StringRef> initialUndefinedSymbols() const { return _initialUndefinedSymbols; } @@ -255,9 +166,7 @@ public: bool validate(raw_ostream &diagnostics); /// Formats symbol name for use in error messages. - virtual std::string demangle(StringRef symbolName) const { - return symbolName; - } + virtual std::string demangle(StringRef symbolName) const = 0; /// @} /// \name Methods used by Driver::link() @@ -269,19 +178,6 @@ public: /// the linker to write to an in-memory buffer. StringRef outputPath() const { return _outputPath; } - /// Set the various output file types that the linker would - /// create - bool setOutputFileType(StringRef outputFileType) { - if (outputFileType.equals_lower("yaml")) { - _outputFileType = OutputFileType::YAML; - return true; - } - return false; - } - - /// Returns the output file type that that the linker needs to create. - OutputFileType outputFileType() const { return _outputFileType; } - /// Accessor for Register object embedded in LinkingContext. const Registry ®istry() const { return _registry; } Registry ®istry() { return _registry; } @@ -289,25 +185,30 @@ public: /// This method is called by core linking to give the Writer a chance /// to add file format specific "files" to set of files to be linked. This is /// how file format specific atoms can be added to the link. - virtual void createImplicitFiles(std::vector<std::unique_ptr<File>> &); + virtual void createImplicitFiles(std::vector<std::unique_ptr<File>> &) = 0; /// This method is called by core linking to build the list of Passes to be /// run on the merged/linked graph of all input files. - virtual void addPasses(PassManager &pm); + virtual void addPasses(PassManager &pm) = 0; /// Calls through to the writeFile() method on the specified Writer. /// /// \param linkedFile This is the merged/linked graph of all input file Atoms. - virtual std::error_code writeFile(const File &linkedFile) const; + virtual llvm::Error writeFile(const File &linkedFile) const; /// Return the next ordinal and Increment it. virtual uint64_t getNextOrdinalAndIncrement() const { return _nextOrdinal++; } // This function is called just before the Resolver kicks in. // Derived classes may use it to change the list of input files. - virtual void finalizeInputFiles() {} + virtual void finalizeInputFiles() = 0; - TaskGroup &getTaskGroup() { return _taskGroup; } + /// Callback invoked for each file the Resolver decides we are going to load. + /// This can be used to update context state based on the file, and emit + /// errors for any differences between the context state and a loaded file. + /// For example, we can error if we try to load a file which is a different + /// arch from that being linked. + virtual llvm::Error handleLoadedFile(File &file) = 0; /// @} protected: @@ -324,36 +225,25 @@ protected: virtual std::unique_ptr<File> createUndefinedSymbolFile() const; std::unique_ptr<File> createUndefinedSymbolFile(StringRef filename) const; - /// Method to create an internal file for alias symbols - std::unique_ptr<File> createAliasSymbolFile() const; - StringRef _outputPath; StringRef _entrySymbolName; - bool _deadStrip; - bool _allowDuplicates; - bool _globalsAreDeadStripRoots; - bool _searchArchivesToOverrideTentativeDefinitions; - bool _searchSharedLibrariesToOverrideTentativeDefinitions; - bool _warnIfCoalesableAtomsHaveDifferentCanBeNull; - bool _warnIfCoalesableAtomsHaveDifferentLoadName; - bool _printRemainingUndefines; - bool _allowRemainingUndefines; - bool _logInputFiles; - bool _allowShlibUndefines; - OutputFileType _outputFileType; + bool _deadStrip = false; + bool _globalsAreDeadStripRoots = false; + bool _printRemainingUndefines = true; + bool _allowRemainingUndefines = false; + bool _logInputFiles = false; + bool _allowShlibUndefines = false; std::vector<StringRef> _deadStripRoots; - std::map<std::string, std::string> _aliasSymbols; std::vector<const char *> _llvmOptions; StringRefVector _initialUndefinedSymbols; std::vector<std::unique_ptr<Node>> _nodes; mutable llvm::BumpPtrAllocator _allocator; - mutable uint64_t _nextOrdinal; + mutable uint64_t _nextOrdinal = 0; Registry _registry; private: /// Validate the subclass bits. Only called by validate. virtual bool validateImpl(raw_ostream &diagnostics) = 0; - TaskGroup _taskGroup; }; } // end namespace lld diff --git a/include/lld/Core/Node.h b/include/lld/Core/Node.h index cd38fbd4a482..8de0ecdbba6a 100644 --- a/include/lld/Core/Node.h +++ b/include/lld/Core/Node.h @@ -57,7 +57,7 @@ private: class FileNode : public Node { public: explicit FileNode(std::unique_ptr<File> f) - : Node(Node::Kind::File), _file(std::move(f)), _asNeeded(false) {} + : Node(Node::Kind::File), _file(std::move(f)) {} static bool classof(const Node *a) { return a->kind() == Node::Kind::File; @@ -65,12 +65,8 @@ public: File *getFile() { return _file.get(); } - void setAsNeeded(bool val) { _asNeeded = val; } - bool asNeeded() const { return _asNeeded; } - protected: std::unique_ptr<File> _file; - bool _asNeeded; }; } // namespace lld diff --git a/include/lld/Core/Parallel.h b/include/lld/Core/Parallel.h index e2c38308b768..2dde97d9e3f0 100644 --- a/include/lld/Core/Parallel.h +++ b/include/lld/Core/Parallel.h @@ -12,7 +12,6 @@ #include "lld/Core/Instrumentation.h" #include "lld/Core/LLVM.h" -#include "lld/Core/range.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/thread.h" @@ -63,41 +62,6 @@ public: } }; -/// \brief An implementation of future. std::future and std::promise in -/// old libstdc++ have a threading bug; there is a small chance that a -/// call of future::get throws an exception in the normal use case. -/// We want to use our own future implementation until we drop support -/// of old versions of libstdc++. -/// https://gcc.gnu.org/ml/gcc-patches/2014-05/msg01389.html -template<typename T> class Future { -public: - Future() : _hasValue(false) {} - - void set(T &&val) { - assert(!_hasValue); - { - std::unique_lock<std::mutex> lock(_mutex); - _val = val; - _hasValue = true; - } - _cond.notify_all(); - } - - T &get() { - std::unique_lock<std::mutex> lock(_mutex); - if (_hasValue) - return _val; - _cond.wait(lock, [&] { return _hasValue; }); - return _val; - } - -private: - T _val; - bool _hasValue; - std::mutex _mutex; - std::condition_variable _cond; -}; - // Classes in this namespace are implementation details of this header. namespace internal { diff --git a/include/lld/Core/Pass.h b/include/lld/Core/Pass.h index 2e49cd1b8eee..0527f02cd362 100644 --- a/include/lld/Core/Pass.h +++ b/include/lld/Core/Pass.h @@ -13,7 +13,7 @@ #include "lld/Core/Atom.h" #include "lld/Core/File.h" #include "lld/Core/Reference.h" -#include "lld/Core/range.h" +#include "llvm/Support/Error.h" #include <vector> namespace lld { @@ -34,7 +34,7 @@ public: virtual ~Pass() { } /// Do the actual work of the Pass. - virtual std::error_code perform(SimpleFile &mergedFile) = 0; + virtual llvm::Error perform(SimpleFile &mergedFile) = 0; protected: // Only subclassess can be instantiated. diff --git a/include/lld/Core/PassManager.h b/include/lld/Core/PassManager.h index 62aa119f8f76..71a25cc7f3cd 100644 --- a/include/lld/Core/PassManager.h +++ b/include/lld/Core/PassManager.h @@ -12,6 +12,7 @@ #include "lld/Core/LLVM.h" #include "lld/Core/Pass.h" +#include "llvm/Support/Error.h" #include <memory> #include <vector> @@ -31,11 +32,11 @@ public: _passes.push_back(std::move(pass)); } - std::error_code runOnFile(SimpleFile &file) { + llvm::Error runOnFile(SimpleFile &file) { for (std::unique_ptr<Pass> &pass : _passes) - if (std::error_code EC = pass->perform(file)) + if (llvm::Error EC = pass->perform(file)) return EC; - return std::error_code(); + return llvm::Error(); } private: diff --git a/include/lld/Core/Reader.h b/include/lld/Core/Reader.h index 9324da475e3d..66df4380dc76 100644 --- a/include/lld/Core/Reader.h +++ b/include/lld/Core/Reader.h @@ -27,17 +27,14 @@ class IO; } namespace lld { -class ELFLinkingContext; class File; class LinkingContext; -class PECOFFLinkingContext; class MachOLinkingContext; /// \brief An abstract class for reading object files, library files, and /// executable files. /// -/// Each file format (e.g. ELF, mach-o, PECOFF, etc) have a concrete -/// subclass of Reader. +/// Each file format (e.g. mach-o, etc) has a concrete subclass of Reader. class Reader { public: virtual ~Reader() {} @@ -114,11 +111,7 @@ public: // as parameters to the addSupport*() method. void addSupportArchives(bool logLoading); void addSupportYamlFiles(); - void addSupportCOFFObjects(PECOFFLinkingContext &); - void addSupportCOFFImportLibraries(PECOFFLinkingContext &); void addSupportMachOObjects(MachOLinkingContext &); - void addSupportELFObjects(ELFLinkingContext &); - void addSupportELFDynamicSharedObjects(ELFLinkingContext &); /// To convert between kind values and names, the registry walks the list /// of registered kind tables. Each table is a zero terminated array of diff --git a/include/lld/Core/Reference.h b/include/lld/Core/Reference.h index 971721eb7d54..86de4f6a4236 100644 --- a/include/lld/Core/Reference.h +++ b/include/lld/Core/Reference.h @@ -25,15 +25,13 @@ class Atom; /// the Atom, then the function Atom will have a Reference of: offsetInAtom=40, /// kind=callsite, target=malloc, addend=0. /// -/// Besides supporting traditional "relocations", References are also used -/// grouping atoms (group comdat), forcing layout (one atom must follow -/// another), marking data-in-code (jump tables or ARM constants), etc. +/// Besides supporting traditional "relocations", references are also used +/// forcing layout (one atom must follow another), marking data-in-code +/// (jump tables or ARM constants), etc. /// /// The "kind" of a reference is a tuple of <namespace, arch, value>. This /// enable us to re-use existing relocation types definded for various -/// file formats and architectures. For instance, in ELF the relocation type 10 -/// means R_X86_64_32 for x86_64, and R_386_GOTPC for i386. For PE/COFF -/// relocation 10 means IMAGE_REL_AMD64_SECTION. +/// file formats and architectures. /// /// References and atoms form a directed graph. The dead-stripping pass /// traverses them starting from dead-strip root atoms to garbage collect @@ -47,16 +45,14 @@ public: enum class KindNamespace { all = 0, testing = 1, - ELF = 2, - COFF = 3, - mach_o = 4, + mach_o = 2, }; KindNamespace kindNamespace() const { return (KindNamespace)_kindNamespace; } void setKindNamespace(KindNamespace ns) { _kindNamespace = (uint8_t)ns; } // Which architecture the kind value is for. - enum class KindArch { all, AArch64, AMDGPU, ARM, Hexagon, Mips, x86, x86_64 }; + enum class KindArch { all, AArch64, ARM, x86, x86_64}; KindArch kindArch() const { return (KindArch)_kindArch; } void setKindArch(KindArch a) { _kindArch = (uint8_t)a; } @@ -76,8 +72,6 @@ public: // kindLayoutAfter is treated as a bidirected edge by the dead-stripping // pass. kindLayoutAfter = 1, - // kindGroupChild is treated as a bidirected edge too. - kindGroupChild, kindAssociate, }; diff --git a/include/lld/Core/Resolver.h b/include/lld/Core/Resolver.h index 05af7d9573ea..fb62a779c0a5 100644 --- a/include/lld/Core/Resolver.h +++ b/include/lld/Core/Resolver.h @@ -17,6 +17,7 @@ #include "lld/Core/SymbolTable.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" +#include "llvm/Support/ErrorOr.h" #include <set> #include <unordered_map> #include <unordered_set> @@ -31,25 +32,23 @@ class LinkingContext; /// and producing a merged graph. class Resolver { public: - Resolver(LinkingContext &ctx) - : _ctx(ctx), _symbolTable(ctx), _result(new MergedFile()), - _fileIndex(0) {} + Resolver(LinkingContext &ctx) : _ctx(ctx), _result(new MergedFile()) {} // InputFiles::Handler methods - void doDefinedAtom(const DefinedAtom&); - bool doUndefinedAtom(const UndefinedAtom &); - void doSharedLibraryAtom(const SharedLibraryAtom &); - void doAbsoluteAtom(const AbsoluteAtom &); + void doDefinedAtom(OwningAtomPtr<DefinedAtom> atom); + bool doUndefinedAtom(OwningAtomPtr<UndefinedAtom> atom); + void doSharedLibraryAtom(OwningAtomPtr<SharedLibraryAtom> atom); + void doAbsoluteAtom(OwningAtomPtr<AbsoluteAtom> atom); // Handle files, this adds atoms from the current file thats // being processed by the resolver - bool handleFile(File &); + llvm::Expected<bool> handleFile(File &); // Handle an archive library file. - bool handleArchiveFile(File &); + llvm::Expected<bool> handleArchiveFile(File &); // Handle a shared library file. - void handleSharedLibrary(File &); + llvm::Error handleSharedLibrary(File &); /// @brief do work of merging and resolving and return list bool resolve(); @@ -57,37 +56,30 @@ public: std::unique_ptr<SimpleFile> resultFile() { return std::move(_result); } private: - typedef std::function<void(StringRef, bool)> UndefCallback; + typedef std::function<llvm::Expected<bool>(StringRef)> UndefCallback; bool undefinesAdded(int begin, int end); File *getFile(int &index); - /// \brief Add section group/.gnu.linkonce if it does not exist previously. - void maybeAddSectionGroupOrGnuLinkOnce(const DefinedAtom &atom); - /// \brief The main function that iterates over the files to resolve - void updatePreloadArchiveMap(); bool resolveUndefines(); void updateReferences(); void deadStripOptimize(); bool checkUndefines(); void removeCoalescedAwayAtoms(); - void checkDylibSymbolCollisions(); - void forEachUndefines(File &file, bool searchForOverrides, UndefCallback callback); + llvm::Expected<bool> forEachUndefines(File &file, UndefCallback callback); void markLive(const Atom *atom); - void addAtoms(const std::vector<const DefinedAtom *>&); - void maybePreloadArchiveMember(StringRef sym); class MergedFile : public SimpleFile { public: - MergedFile() : SimpleFile("<linker-internal>") {} - void addAtoms(std::vector<const Atom*>& atoms); + MergedFile() : SimpleFile("<linker-internal>", kindResolverMergedObject) {} + void addAtoms(llvm::MutableArrayRef<OwningAtomPtr<Atom>> atoms); }; LinkingContext &_ctx; SymbolTable _symbolTable; - std::vector<const Atom *> _atoms; + std::vector<OwningAtomPtr<Atom>> _atoms; std::set<const Atom *> _deadStripRoots; llvm::DenseSet<const Atom *> _liveAtoms; llvm::DenseSet<const Atom *> _deadAtoms; @@ -97,11 +89,6 @@ private: // --start-group and --end-group std::vector<File *> _files; std::map<File *, bool> _newUndefinesAdded; - size_t _fileIndex; - - // Preloading - llvm::StringMap<ArchiveLibraryFile *> _archiveMap; - llvm::DenseSet<ArchiveLibraryFile *> _archiveSeen; // List of undefined symbols. std::vector<StringRef> _undefines; diff --git a/include/lld/Core/STDExtras.h b/include/lld/Core/STDExtras.h deleted file mode 100644 index 4a6183891844..000000000000 --- a/include/lld/Core/STDExtras.h +++ /dev/null @@ -1,29 +0,0 @@ -//===- lld/Core/STDExtra.h - Helpers for the stdlib -----------------------===// -// -// The LLVM Linker -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef LLD_CORE_STD_EXTRA_H -#define LLD_CORE_STD_EXTRA_H - -namespace lld { -/// \brief Deleter for smart pointers that only calls the destructor. Memory is -/// managed elsewhere. A common use of this is for things allocated with a -/// BumpPtrAllocator. -template <class T> -struct destruct_delete { - void operator ()(T *ptr) { - ptr->~T(); - } -}; - -template <class T> -using unique_bump_ptr = std::unique_ptr<T, destruct_delete<T>>; - -} // end namespace lld - -#endif diff --git a/include/lld/Core/SharedLibraryAtom.h b/include/lld/Core/SharedLibraryAtom.h index 1b0c37c41138..7fec7a3e3d29 100644 --- a/include/lld/Core/SharedLibraryAtom.h +++ b/include/lld/Core/SharedLibraryAtom.h @@ -25,9 +25,7 @@ public: }; /// Returns shared library name used to load it at runtime. - /// On linux that is the DT_NEEDED name. /// On Darwin it is the LC_DYLIB_LOAD dylib name. - /// On Windows it is the DLL name that to be referred from .idata section. virtual StringRef loadName() const = 0; /// Returns if shared library symbol can be missing at runtime and if @@ -46,6 +44,8 @@ public: protected: SharedLibraryAtom() : Atom(definitionSharedLibrary) {} + + ~SharedLibraryAtom() override = default; }; } // namespace lld diff --git a/include/lld/Core/SharedLibraryFile.h b/include/lld/Core/SharedLibraryFile.h index a2907287862d..53bf967b0236 100644 --- a/include/lld/Core/SharedLibraryFile.h +++ b/include/lld/Core/SharedLibraryFile.h @@ -27,29 +27,34 @@ public: /// Check if the shared library exports a symbol with the specified name. /// If so, return a SharedLibraryAtom which represents that exported /// symbol. Otherwise return nullptr. - virtual const SharedLibraryAtom *exports(StringRef name, - bool dataSymbolOnly) const = 0; + virtual OwningAtomPtr<SharedLibraryAtom> exports(StringRef name) const = 0; - // Returns DSO name. It's the soname (ELF), the install name (MachO) or - // the import name (Windows). + // Returns the install name. virtual StringRef getDSOName() const = 0; - const AtomVector<DefinedAtom> &defined() const override { + const AtomRange<DefinedAtom> defined() const override { return _definedAtoms; } - const AtomVector<UndefinedAtom> &undefined() const override { + const AtomRange<UndefinedAtom> undefined() const override { return _undefinedAtoms; } - const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { + const AtomRange<SharedLibraryAtom> sharedLibrary() const override { return _sharedLibraryAtoms; } - const AtomVector<AbsoluteAtom> &absolute() const override { + const AtomRange<AbsoluteAtom> absolute() const override { return _absoluteAtoms; } + void clearAtoms() override { + _definedAtoms.clear(); + _undefinedAtoms.clear(); + _sharedLibraryAtoms.clear(); + _absoluteAtoms.clear(); + } + protected: /// only subclasses of SharedLibraryFile can be instantiated explicit SharedLibraryFile(StringRef path) : File(path, kindSharedLibrary) {} diff --git a/include/lld/Core/Simple.h b/include/lld/Core/Simple.h index 3c204f8ba284..f75b40327db4 100644 --- a/include/lld/Core/Simple.h +++ b/include/lld/Core/Simple.h @@ -15,36 +15,60 @@ #ifndef LLD_CORE_SIMPLE_H #define LLD_CORE_SIMPLE_H +#include "lld/Core/AbsoluteAtom.h" +#include "lld/Core/Atom.h" #include "lld/Core/DefinedAtom.h" #include "lld/Core/File.h" -#include "lld/Core/ArchiveLibraryFile.h" -#include "lld/Core/LinkingContext.h" #include "lld/Core/Reference.h" +#include "lld/Core/SharedLibraryAtom.h" #include "lld/Core/UndefinedAtom.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" #include "llvm/ADT/ilist.h" -#include "llvm/ADT/ilist_node.h" -#include <atomic> +#include "llvm/Support/Allocator.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/ErrorHandling.h" +#include <algorithm> +#include <cassert> +#include <cstdint> +#include <functional> namespace lld { class SimpleFile : public File { public: - SimpleFile(StringRef path) : File(path, kindObject) {} + SimpleFile(StringRef path, File::Kind kind) + : File(path, kind) {} + + ~SimpleFile() override { + _defined.clear(); + _undefined.clear(); + _shared.clear(); + _absolute.clear(); + } - void addAtom(const DefinedAtom &a) { _defined.push_back(&a); } - void addAtom(const UndefinedAtom &a) { _undefined.push_back(&a); } - void addAtom(const SharedLibraryAtom &a) { _shared.push_back(&a); } - void addAtom(const AbsoluteAtom &a) { _absolute.push_back(&a); } + void addAtom(DefinedAtom &a) { + _defined.push_back(OwningAtomPtr<DefinedAtom>(&a)); + } + void addAtom(UndefinedAtom &a) { + _undefined.push_back(OwningAtomPtr<UndefinedAtom>(&a)); + } + void addAtom(SharedLibraryAtom &a) { + _shared.push_back(OwningAtomPtr<SharedLibraryAtom>(&a)); + } + void addAtom(AbsoluteAtom &a) { + _absolute.push_back(OwningAtomPtr<AbsoluteAtom>(&a)); + } void addAtom(const Atom &atom) { if (auto *p = dyn_cast<DefinedAtom>(&atom)) { - _defined.push_back(p); + addAtom(const_cast<DefinedAtom &>(*p)); } else if (auto *p = dyn_cast<UndefinedAtom>(&atom)) { - _undefined.push_back(p); + addAtom(const_cast<UndefinedAtom &>(*p)); } else if (auto *p = dyn_cast<SharedLibraryAtom>(&atom)) { - _shared.push_back(p); + addAtom(const_cast<SharedLibraryAtom &>(*p)); } else if (auto *p = dyn_cast<AbsoluteAtom>(&atom)) { - _absolute.push_back(p); + addAtom(const_cast<AbsoluteAtom &>(*p)); } else { llvm_unreachable("atom has unknown definition kind"); } @@ -52,26 +76,33 @@ public: void removeDefinedAtomsIf(std::function<bool(const DefinedAtom *)> pred) { auto &atoms = _defined; - auto newEnd = std::remove_if(atoms.begin(), atoms.end(), pred); + auto newEnd = std::remove_if(atoms.begin(), atoms.end(), + [&pred](OwningAtomPtr<DefinedAtom> &p) { + return pred(p.get()); + }); atoms.erase(newEnd, atoms.end()); } - const AtomVector<DefinedAtom> &defined() const override { return _defined; } + const AtomRange<DefinedAtom> defined() const override { return _defined; } - const AtomVector<UndefinedAtom> &undefined() const override { + const AtomRange<UndefinedAtom> undefined() const override { return _undefined; } - const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { + const AtomRange<SharedLibraryAtom> sharedLibrary() const override { return _shared; } - const AtomVector<AbsoluteAtom> &absolute() const override { + const AtomRange<AbsoluteAtom> absolute() const override { return _absolute; } - typedef range<std::vector<const DefinedAtom *>::iterator> DefinedAtomRange; - DefinedAtomRange definedAtoms() { return make_range(_defined); } + void clearAtoms() override { + _defined.clear(); + _undefined.clear(); + _shared.clear(); + _absolute.clear(); + } private: AtomVector<DefinedAtom> _defined; @@ -80,48 +111,6 @@ private: AtomVector<AbsoluteAtom> _absolute; }; -/// \brief Archive library file that may be used as a virtual container -/// for symbols that should be added dynamically in response to -/// call to find() method. -class SimpleArchiveLibraryFile : public ArchiveLibraryFile { -public: - SimpleArchiveLibraryFile(StringRef filename) - : ArchiveLibraryFile(filename) {} - - const AtomVector<DefinedAtom> &defined() const override { - return _definedAtoms; - } - - const AtomVector<UndefinedAtom> &undefined() const override { - return _undefinedAtoms; - } - - const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { - return _sharedLibraryAtoms; - } - - const AtomVector<AbsoluteAtom> &absolute() const override { - return _absoluteAtoms; - } - - File *find(StringRef sym, bool dataSymbolOnly) override { - // For descendants: - // do some checks here and return dynamically generated files with atoms. - return nullptr; - } - - std::error_code - parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { - return std::error_code(); - } - -private: - AtomVector<DefinedAtom> _definedAtoms; - AtomVector<UndefinedAtom> _undefinedAtoms; - AtomVector<SharedLibraryAtom> _sharedLibraryAtoms; - AtomVector<AbsoluteAtom> _absoluteAtoms; -}; - class SimpleReference : public Reference { public: SimpleReference(Reference::KindNamespace ns, Reference::KindArch arch, @@ -159,12 +148,13 @@ private: SimpleReference *_prev; }; -} +} // end namespace lld // ilist will lazily create a sentinal (so end() can return a node past the // end of the list). We need this trait so that the sentinal is allocated // via the BumpPtrAllocator. namespace llvm { + template<> struct ilist_sentinel_traits<lld::SimpleReference> { @@ -200,7 +190,8 @@ struct ilist_sentinel_traits<lld::SimpleReference> { private: mutable llvm::BumpPtrAllocator *_allocator; }; -} + +} // end namespace llvm namespace lld { @@ -211,6 +202,10 @@ public: _references.setAllocator(&f.allocator()); } + ~SimpleDefinedAtom() override { + _references.clearAndLeakNodesUnsafely(); + } + const File &file() const override { return _file; } StringRef name() const override { return StringRef(); } @@ -256,9 +251,10 @@ public: it = reinterpret_cast<const void*>(next); } - void addReference(Reference::KindNamespace ns, Reference::KindArch arch, + void addReference(Reference::KindNamespace ns, + Reference::KindArch arch, Reference::KindValue kindValue, uint64_t off, - const Atom *target, Reference::Addend a) { + const Atom *target, Reference::Addend a) override { assert(target && "trying to create reference to nothing"); auto node = new (_file.allocator()) SimpleReference(ns, arch, kindValue, off, target, a); @@ -290,6 +286,7 @@ public: _references.push_back(node); } } + void setOrdinal(uint64_t ord) { _ordinal = ord; } private: @@ -306,6 +303,8 @@ public: assert(!name.empty() && "UndefinedAtoms must have a name"); } + ~SimpleUndefinedAtom() override = default; + /// file - returns the File that produced/owns this Atom const File &file() const override { return _file; } @@ -320,23 +319,6 @@ private: StringRef _name; }; -class SimpleAbsoluteAtom : public AbsoluteAtom { -public: - SimpleAbsoluteAtom(const File &f, StringRef name, Scope s, uint64_t value) - : _file(f), _name(name), _scope(s), _value(value) {} - - const File &file() const override { return _file; } - StringRef name() const override { return _name; } - uint64_t value() const override { return _value; } - Scope scope() const override { return _scope; } - -private: - const File &_file; - StringRef _name; - Scope _scope; - uint64_t _value; -}; - } // end namespace lld -#endif +#endif // LLD_CORE_SIMPLE_H diff --git a/include/lld/Core/SymbolTable.h b/include/lld/Core/SymbolTable.h index 2e4459236d18..db610ad14066 100644 --- a/include/lld/Core/SymbolTable.h +++ b/include/lld/Core/SymbolTable.h @@ -34,8 +34,6 @@ class UndefinedAtom; /// if an atom has been coalesced away. class SymbolTable { public: - explicit SymbolTable(LinkingContext &); - /// @brief add atom to symbol table bool add(const DefinedAtom &); @@ -70,13 +68,6 @@ public: /// @brief if atom has been coalesced away, return true bool isCoalescedAway(const Atom *); - /// @brief Find a group atom. - const Atom *findGroup(StringRef name); - - /// @brief Add a group atom and returns true/false depending on whether the - /// previously existed. - bool addGroup(const DefinedAtom &da); - private: typedef llvm::DenseMap<const Atom *, const Atom *> AtomToAtom; @@ -105,10 +96,8 @@ private: bool addByName(const Atom &); bool addByContent(const DefinedAtom &); - LinkingContext &_ctx; AtomToAtom _replacedAtoms; NameToAtom _nameTable; - NameToAtom _groupTable; AtomContentSet _contentTable; }; diff --git a/include/lld/Core/UndefinedAtom.h b/include/lld/Core/UndefinedAtom.h index 7a835a4ebaa8..f45d6ecda6b0 100644 --- a/include/lld/Core/UndefinedAtom.h +++ b/include/lld/Core/UndefinedAtom.h @@ -57,16 +57,10 @@ public: static bool classof(const UndefinedAtom *) { return true; } - /// Returns an undefined atom if this undefined symbol has a synonym. This is - /// mainly used in COFF. In COFF, an unresolved external symbol can have up to - /// one optional name (sym2) in addition to its regular name (sym1). If a - /// definition of sym1 exists, sym1 is resolved normally. Otherwise, all - /// references to sym1 refer to sym2 instead. In that case sym2 must be - /// resolved, or link will fail. - virtual const UndefinedAtom *fallback() const { return nullptr; } - protected: UndefinedAtom() : Atom(definitionUndefined) {} + + ~UndefinedAtom() override = default; }; } // namespace lld diff --git a/include/lld/Core/Writer.h b/include/lld/Core/Writer.h index 8214ed6203f2..216f934916bc 100644 --- a/include/lld/Core/Writer.h +++ b/include/lld/Core/Writer.h @@ -11,25 +11,24 @@ #define LLD_CORE_WRITER_H #include "lld/Core/LLVM.h" +#include "llvm/Support/Error.h" #include <memory> #include <vector> namespace lld { -class ELFLinkingContext; class File; class LinkingContext; class MachOLinkingContext; -class PECOFFLinkingContext; /// \brief The Writer is an abstract class for writing object files, shared -/// library files, and executable files. Each file format (e.g. ELF, mach-o, -/// PECOFF, etc) have a concrete subclass of Writer. +/// library files, and executable files. Each file format (e.g. mach-o, etc) +/// has a concrete subclass of Writer. class Writer { public: virtual ~Writer(); /// \brief Write a file from the supplied File object - virtual std::error_code writeFile(const File &linkedFile, StringRef path) = 0; + virtual llvm::Error writeFile(const File &linkedFile, StringRef path) = 0; /// \brief This method is called by Core Linking to give the Writer a chance /// to add file format specific "files" to set of files to be linked. This is @@ -41,9 +40,7 @@ protected: Writer(); }; -std::unique_ptr<Writer> createWriterELF(const ELFLinkingContext &); std::unique_ptr<Writer> createWriterMachO(const MachOLinkingContext &); -std::unique_ptr<Writer> createWriterPECOFF(const PECOFFLinkingContext &); std::unique_ptr<Writer> createWriterYAML(const LinkingContext &); } // end namespace lld diff --git a/include/lld/Core/range.h b/include/lld/Core/range.h deleted file mode 100644 index 614c9672955c..000000000000 --- a/include/lld/Core/range.h +++ /dev/null @@ -1,738 +0,0 @@ -//===-- lld/Core/range.h - Iterator ranges ----------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file -/// \brief Iterator range type based on c++1y range proposal. -/// -/// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3350.html -/// -//===----------------------------------------------------------------------===// - -#ifndef LLD_CORE_RANGE_H -#define LLD_CORE_RANGE_H - -#include "llvm/Support/Compiler.h" -#include <array> -#include <cassert> -#include <iterator> -#include <string> -#include <type_traits> -#include <utility> -#include <vector> - -namespace lld { -// Nothing in this namespace is part of the exported interface. -namespace detail { -using std::begin; -using std::end; -/// Used as the result type of undefined functions. -struct undefined {}; - -template <typename R> class begin_result { - template <typename T> static auto check(T &&t) -> decltype(begin(t)); - static undefined check(...); -public: - typedef decltype(check(std::declval<R>())) type; -}; - -template <typename R> class end_result { - template <typename T> static auto check(T &&t) -> decltype(end(t)); - static undefined check(...); -public: - typedef decltype(check(std::declval<R>())) type; -}; - -// Things that begin and end work on, in compatible ways, are -// ranges. [stmt.ranged] -template <typename R> -struct is_range : std::is_same<typename detail::begin_result<R>::type, - typename detail::end_result<R>::type> {}; - -// This currently requires specialization and doesn't work for -// detecting \c range<>s or iterators. We should add -// \c contiguous_iterator_tag to fix that. -template <typename R> struct is_contiguous_range : std::false_type {}; -template <typename R> -struct is_contiguous_range<R &> : is_contiguous_range<R> {}; -template <typename R> -struct is_contiguous_range <R &&> : is_contiguous_range<R> {}; -template <typename R> -struct is_contiguous_range<const R> : is_contiguous_range<R> {}; - -template <typename T, size_t N> -struct is_contiguous_range<T[N]> : std::true_type {}; -template <typename T, size_t N> -struct is_contiguous_range<const T[N]> : std::true_type {}; -template <typename T, size_t N> -struct is_contiguous_range<std::array<T, N> > : std::true_type {}; -template <typename charT, typename traits, typename Allocator> -struct is_contiguous_range< - std::basic_string<charT, traits, Allocator> > : std::true_type {}; -template <typename T, typename Allocator> -struct is_contiguous_range<std::vector<T, Allocator> > : std::true_type {}; - -// Removes cv qualifiers from all levels of a multi-level pointer -// type, not just the type level. -template <typename T> struct remove_all_cv_ptr { - typedef T type; -}; -template <typename T> struct remove_all_cv_ptr<T *> { - typedef typename remove_all_cv_ptr<T>::type *type; -}; -template <typename T> struct remove_all_cv_ptr<const T> { - typedef typename remove_all_cv_ptr<T>::type type; -}; -template <typename T> struct remove_all_cv_ptr<volatile T> { - typedef typename remove_all_cv_ptr<T>::type type; -}; -template <typename T> struct remove_all_cv_ptr<const volatile T> { - typedef typename remove_all_cv_ptr<T>::type type; -}; - -template <typename From, typename To> -struct conversion_preserves_array_indexing : std::false_type {}; - -template <typename FromVal, typename ToVal> -struct conversion_preserves_array_indexing<FromVal *, - ToVal *> : std::integral_constant< - bool, std::is_convertible<FromVal *, ToVal *>::value && - std::is_same<typename remove_all_cv_ptr<FromVal>::type, - typename remove_all_cv_ptr<ToVal>::type>::value> {}; - -template <typename T> -LLVM_CONSTEXPR auto adl_begin(T &&t) -> decltype(begin(t)) { - return begin(std::forward<T>(t)); -} - -template <typename T> LLVM_CONSTEXPR auto adl_end(T &&t) -> decltype(end(t)) { - return end(std::forward<T>(t)); -} -} // end namespace detail - -/// A \c std::range<Iterator> represents a half-open iterator range -/// built from two iterators, \c 'begin', and \c 'end'. If \c end is -/// not reachable from \c begin, the behavior is undefined. -/// -/// The mutability of elements of the range is controlled by the -/// Iterator argument. Instantiate -/// <code>range<<var>Foo</var>::iterator></code> or -/// <code>range<<var>T</var>*></code>, or call -/// <code>make_range(<var>non_const_container</var>)</code>, and you -/// get a mutable range. Instantiate -/// <code>range<<var>Foo</var>::const_iterator></code> or -/// <code>range<const <var>T</var>*></code>, or call -/// <code>make_range(<var>const_container</var>)</code>, and you get a -/// constant range. -/// -/// \todo Inherit from std::pair<Iterator, Iterator>? -/// -/// \todo This interface contains some functions that could be -/// provided as free algorithms rather than member functions, and all -/// of the <code>pop_*()</code> functions could be replaced by \c -/// slice() at the cost of some extra iterator copies. This makes -/// them more awkward to use, but makes it easier for users to write -/// their own types that follow the same interface. On the other hand, -/// a \c range_facade could be provided to help users write new -/// ranges, and it could provide the members. Such functions are -/// marked with a note in their documentation. (Of course, all of -/// these member functions could be provided as free functions using -/// the iterator access methods, but one goal here is to allow people -/// to program without touching iterators at all.) -template <typename Iterator> class range { - Iterator begin_, end_; -public: - /// \name types - /// @{ - - /// The iterator category of \c Iterator. - /// \todo Consider defining range categories. If they don't add - /// anything over the corresponding iterator categories, then - /// they're probably not worth defining. - typedef typename std::iterator_traits< - Iterator>::iterator_category iterator_category; - /// The type of elements of the range. Not cv-qualified. - typedef typename std::iterator_traits<Iterator>::value_type value_type; - /// The type of the size of the range and offsets within the range. - typedef typename std::iterator_traits< - Iterator>::difference_type difference_type; - /// The return type of element access methods: \c front(), \c back(), etc. - typedef typename std::iterator_traits<Iterator>::reference reference; - typedef typename std::iterator_traits<Iterator>::pointer pointer; - /// @} - - /// \name constructors - /// @{ - - /// Creates a range of default-constructed (<em>not</em> - /// value-initialized) iterators. For most \c Iterator types, this - /// will be an invalid range. - range() : begin_(), end_() {} - - /// \pre \c end is reachable from \c begin. - /// \post <code>this->begin() == begin && this->end() == end</code> - LLVM_CONSTEXPR range(Iterator begin, Iterator end) - : begin_(begin), end_(end) {} - - /// \par Participates in overload resolution if: - /// - \c Iterator is not a pointer type, - /// - \c begin(r) and \c end(r) return the same type, and - /// - that type is convertible to \c Iterator. - /// - /// \todo std::begin and std::end are overloaded between T& and - /// const T&, which means that if a container has only a non-const - /// begin or end method, then it's ill-formed to pass an rvalue to - /// the free function. To avoid that problem, we don't use - /// std::forward<> here, so begin() and end() are always called with - /// an lvalue. Another option would be to insist that rvalue - /// arguments to range() must have const begin() and end() methods. - template <typename R> LLVM_CONSTEXPR range( - R &&r, - typename std::enable_if< - !std::is_pointer<Iterator>::value && - detail::is_range<R>::value && - std::is_convertible<typename detail::begin_result<R>::type, - Iterator>::value>::type* = 0) - : begin_(detail::adl_begin(r)), end_(detail::adl_end(r)) {} - - /// This constructor creates a \c range<T*> from any range with - /// contiguous iterators. Because dereferencing a past-the-end - /// iterator can be undefined behavior, empty ranges get initialized - /// with \c nullptr rather than \c &*begin(). - /// - /// \par Participates in overload resolution if: - /// - \c Iterator is a pointer type \c T*, - /// - \c begin(r) and \c end(r) return the same type, - /// - elements \c i of that type satisfy the invariant - /// <code>&*(i + N) == (&*i) + N</code>, and - /// - The result of <code>&*begin()</code> is convertible to \c T* - /// using only qualification conversions [conv.qual] (since - /// pointer conversions stop the pointer from pointing to an - /// array element). - /// - /// \todo The <code>&*(i + N) == (&*i) + N</code> invariant is - /// currently impossible to check for user-defined types. We need a - /// \c contiguous_iterator_tag to let users assert it. - template <typename R> LLVM_CONSTEXPR range( - R &&r, - typename std::enable_if< - std::is_pointer<Iterator>::value && - detail::is_contiguous_range<R>::value - // MSVC returns false for this in this context, but not if we lift it out of the - // constructor. -#ifndef _MSC_VER - && detail::conversion_preserves_array_indexing< - decltype(&*detail::adl_begin(r)), Iterator>::value -#endif - >::type* = 0) - : begin_((detail::adl_begin(r) == detail::adl_end(r) && - !std::is_pointer<decltype(detail::adl_begin(r))>::value) - // For non-pointers, &*begin(r) is only defined behavior - // if there's an element there. Otherwise, use nullptr - // since the user can't dereference it anyway. This _is_ - // detectable. - ? nullptr : &*detail::adl_begin(r)), - end_(begin_ + (detail::adl_end(r) - detail::adl_begin(r))) {} - - /// @} - - /// \name iterator access - /// @{ - LLVM_CONSTEXPR Iterator begin() const { return begin_; } - LLVM_CONSTEXPR Iterator end() const { return end_; } - /// @} - - /// \name element access - /// @{ - - /// \par Complexity: - /// O(1) - /// \pre \c !empty() - /// \returns a reference to the element at the front of the range. - LLVM_CONSTEXPR reference front() const { return *begin(); } - - /// \par Ill-formed unless: - /// \c iterator_category is convertible to \c - /// std::bidirectional_iterator_tag. - /// - /// \par Complexity: - /// O(2) (Involves copying and decrementing an iterator, so not - /// quite as cheap as \c front()) - /// - /// \pre \c !empty() - /// \returns a reference to the element at the front of the range. - LLVM_CONSTEXPR reference back() const { - static_assert( - std::is_convertible<iterator_category, - std::bidirectional_iterator_tag>::value, - "Can only retrieve the last element of a bidirectional range."); - using std::prev; - return *prev(end()); - } - - /// This method is drawn from scripting language indexing. It - /// indexes std::forward from the beginning of the range if the argument - /// is positive, or backwards from the end of the array if the - /// argument is negative. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to \c - /// std::random_access_iterator_tag. - /// - /// \par Complexity: - /// O(1) - /// - /// \pre <code>abs(index) < size() || index == -size()</code> - /// - /// \returns if <code>index >= 0</code>, a reference to the - /// <code>index</code>'th element in the range. Otherwise, a - /// reference to the <code>size()+index</code>'th element. - LLVM_CONSTEXPR reference operator[](difference_type index) const { - static_assert(std::is_convertible<iterator_category, - std::random_access_iterator_tag>::value, - "Can only index into a random-access range."); - // Less readable construction for constexpr support. - return index < 0 ? end()[index] - : begin()[index]; - } - /// @} - - /// \name size - /// @{ - - /// \par Complexity: - /// O(1) - /// \returns \c true if the range contains no elements. - LLVM_CONSTEXPR bool empty() const { return begin() == end(); } - - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::forward_iterator_tag. - /// - /// \par Complexity: - /// O(1) if \c iterator_category is convertible to \c - /// std::random_access_iterator_tag. O(<code>size()</code>) - /// otherwise. - /// - /// \returns the number of times \c pop_front() can be called before - /// \c empty() becomes true. - LLVM_CONSTEXPR difference_type size() const { - static_assert(std::is_convertible<iterator_category, - std::forward_iterator_tag>::value, - "Calling size on an input range would destroy the range."); - return dispatch_size(iterator_category()); - } - /// @} - - /// \name traversal from the beginning of the range - /// @{ - - /// Advances the beginning of the range by one element. - /// \pre \c !empty() - void pop_front() { ++begin_; } - - /// Advances the beginning of the range by \c n elements. - /// - /// \par Complexity: - /// O(1) if \c iterator_category is convertible to \c - /// std::random_access_iterator_tag, O(<code>n</code>) otherwise. - /// - /// \pre <code>n >= 0</code>, and there must be at least \c n - /// elements in the range. - void pop_front(difference_type n) { advance(begin_, n); } - - /// Advances the beginning of the range by at most \c n elements, - /// stopping if the range becomes empty. A negative argument causes - /// no change. - /// - /// \par Complexity: - /// O(1) if \c iterator_category is convertible to \c - /// std::random_access_iterator_tag, O(<code>min(n, - /// <var>#-elements-in-range</var>)</code>) otherwise. - /// - /// \note Could be provided as a free function with little-to-no - /// loss in efficiency. - void pop_front_upto(difference_type n) { - advance_upto(begin_, std::max<difference_type>(0, n), end_, - iterator_category()); - } - - /// @} - - /// \name traversal from the end of the range - /// @{ - - /// Moves the end of the range earlier by one element. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::bidirectional_iterator_tag. - /// - /// \par Complexity: - /// O(1) - /// - /// \pre \c !empty() - void pop_back() { - static_assert(std::is_convertible<iterator_category, - std::bidirectional_iterator_tag>::value, - "Can only access the end of a bidirectional range."); - --end_; - } - - /// Moves the end of the range earlier by \c n elements. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::bidirectional_iterator_tag. - /// - /// \par Complexity: - /// O(1) if \c iterator_category is convertible to \c - /// std::random_access_iterator_tag, O(<code>n</code>) otherwise. - /// - /// \pre <code>n >= 0</code>, and there must be at least \c n - /// elements in the range. - void pop_back(difference_type n) { - static_assert(std::is_convertible<iterator_category, - std::bidirectional_iterator_tag>::value, - "Can only access the end of a bidirectional range."); - advance(end_, -n); - } - - /// Moves the end of the range earlier by <code>min(n, - /// size())</code> elements. A negative argument causes no change. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::bidirectional_iterator_tag. - /// - /// \par Complexity: - /// O(1) if \c iterator_category is convertible to \c - /// std::random_access_iterator_tag, O(<code>min(n, - /// <var>#-elements-in-range</var>)</code>) otherwise. - /// - /// \note Could be provided as a free function with little-to-no - /// loss in efficiency. - void pop_back_upto(difference_type n) { - static_assert(std::is_convertible<iterator_category, - std::bidirectional_iterator_tag>::value, - "Can only access the end of a bidirectional range."); - advance_upto(end_, -std::max<difference_type>(0, n), begin_, - iterator_category()); - } - - /// @} - - /// \name creating derived ranges - /// @{ - - /// Divides the range into two pieces at \c index, where a positive - /// \c index represents an offset from the beginning of the range - /// and a negative \c index represents an offset from the end. - /// <code>range[index]</code> is the first element in the second - /// piece. If <code>index >= size()</code>, the second piece - /// will be empty. If <code>index < -size()</code>, the first - /// piece will be empty. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::forward_iterator_tag. - /// - /// \par Complexity: - /// - If \c iterator_category is convertible to \c - /// std::random_access_iterator_tag: O(1) - /// - Otherwise, if \c iterator_category is convertible to \c - /// std::bidirectional_iterator_tag, \c abs(index) iterator increments - /// or decrements - /// - Otherwise, if <code>index >= 0</code>, \c index iterator - /// increments - /// - Otherwise, <code>size() + (size() + index)</code> - /// iterator increments. - /// - /// \returns a pair of adjacent ranges. - /// - /// \post - /// - <code>result.first.size() == min(index, this->size())</code> - /// - <code>result.first.end() == result.second.begin()</code> - /// - <code>result.first.size() + result.second.size()</code> <code>== - /// this->size()</code> - /// - /// \todo split() could take an arbitrary number of indices and - /// return an <code>N+1</code>-element \c tuple<>. This is tricky to - /// implement with negative indices in the optimal number of - /// increments or decrements for a bidirectional iterator, but it - /// should be possible. Do we want it? - std::pair<range, range> split(difference_type index) const { - static_assert( - std::is_convertible<iterator_category, - std::forward_iterator_tag>::value, - "Calling split on a non-std::forward range would return a useless " - "first result."); - if (index >= 0) { - range second = *this; - second.pop_front_upto(index); - return make_pair(range(begin(), second.begin()), second); - } else { - return dispatch_split_neg(index, iterator_category()); - } - } - - /// \returns A sub-range from \c start to \c stop (not including \c - /// stop, as usual). \c start and \c stop are interpreted as for - /// <code>operator[]</code>, with negative values offsetting from - /// the end of the range. Omitting the \c stop argument makes the - /// sub-range continue to the end of the original range. Positive - /// arguments saturate to the end of the range, and negative - /// arguments saturate to the beginning. If \c stop is before \c - /// start, returns an empty range beginning and ending at \c start. - /// - /// \par Ill-formed unless: - /// \c iterator_category is convertible to - /// \c std::forward_iterator_tag. - /// - /// \par Complexity: - /// - If \c iterator_category is convertible to \c - /// std::random_access_iterator_tag: O(1) - /// - Otherwise, if \c iterator_category is convertible to \c - /// std::bidirectional_iterator_tag, at most <code>min(abs(start), - /// size()) + min(abs(stop), size())</code> iterator - /// increments or decrements - /// - Otherwise, if <code>start >= 0 && stop >= 0</code>, - /// <code>max(start, stop)</code> iterator increments - /// - Otherwise, <code>size() + max(start', stop')</code> - /// iterator increments, where \c start' and \c stop' are the - /// offsets of the elements \c start and \c stop refer to. - /// - /// \note \c slice(start) should be implemented with a different - /// overload, rather than defaulting \c stop to - /// <code>numeric_limits<difference_type>::max()</code>, because - /// using a default would force non-random-access ranges to use an - /// O(<code>size()</code>) algorithm to compute the end rather - /// than the O(1) they're capable of. - range slice(difference_type start, difference_type stop) const { - static_assert( - std::is_convertible<iterator_category, - std::forward_iterator_tag>::value, - "Calling slice on a non-std::forward range would destroy the original " - "range."); - return dispatch_slice(start, stop, iterator_category()); - } - - range slice(difference_type start) const { - static_assert( - std::is_convertible<iterator_category, - std::forward_iterator_tag>::value, - "Calling slice on a non-std::forward range would destroy the original " - "range."); - return split(start).second; - } - - /// @} - -private: - // advance_upto: should be added to <algorithm>, but I'll use it as - // a helper function here. - // - // These return the number of increments that weren't applied - // because we ran into 'limit' (or 0 if we didn't run into limit). - static difference_type advance_upto(Iterator &it, difference_type n, - Iterator limit, std::input_iterator_tag) { - if (n < 0) - return 0; - while (it != limit && n > 0) { - ++it; - --n; - } - return n; - } - - static difference_type advance_upto(Iterator &it, difference_type n, - Iterator limit, - std::bidirectional_iterator_tag) { - if (n < 0) { - while (it != limit && n < 0) { - --it; - ++n; - } - } else { - while (it != limit && n > 0) { - ++it; - --n; - } - } - return n; - } - - static difference_type advance_upto(Iterator &it, difference_type n, - Iterator limit, - std::random_access_iterator_tag) { - difference_type distance = limit - it; - if (distance < 0) - assert(n <= 0); - else if (distance > 0) - assert(n >= 0); - - if (abs(distance) > abs(n)) { - it += n; - return 0; - } else { - it = limit; - return n - distance; - } - } - - // Dispatch functions. - difference_type dispatch_size(std::forward_iterator_tag) const { - return std::distance(begin(), end()); - } - - LLVM_CONSTEXPR difference_type dispatch_size( - std::random_access_iterator_tag) const { - return end() - begin(); - } - - std::pair<range, range> dispatch_split_neg(difference_type index, - std::forward_iterator_tag) const { - assert(index < 0); - difference_type size = this->size(); - return split(std::max<difference_type>(0, size + index)); - } - - std::pair<range, range> dispatch_split_neg( - difference_type index, std::bidirectional_iterator_tag) const { - assert(index < 0); - range first = *this; - first.pop_back_upto(-index); - return make_pair(first, range(first.end(), end())); - } - - range dispatch_slice(difference_type start, difference_type stop, - std::forward_iterator_tag) const { - if (start < 0 || stop < 0) { - difference_type size = this->size(); - if (start < 0) - start = std::max<difference_type>(0, size + start); - if (stop < 0) - stop = size + stop; // Possibly negative; will be fixed in 2 lines. - } - stop = std::max<difference_type>(start, stop); - - Iterator first = begin(); - advance_upto(first, start, end(), iterator_category()); - Iterator last = first; - advance_upto(last, stop - start, end(), iterator_category()); - return range(first, last); - } - - range dispatch_slice(const difference_type start, const difference_type stop, - std::bidirectional_iterator_tag) const { - Iterator first; - if (start < 0) { - first = end(); - advance_upto(first, start, begin(), iterator_category()); - } else { - first = begin(); - advance_upto(first, start, end(), iterator_category()); - } - Iterator last; - if (stop < 0) { - last = end(); - advance_upto(last, stop, first, iterator_category()); - } else { - if (start >= 0) { - last = first; - if (stop > start) - advance_upto(last, stop - start, end(), iterator_category()); - } else { - // Complicated: 'start' walked from the end of the sequence, - // but 'stop' needs to walk from the beginning. - Iterator dummy = begin(); - // Walk up to 'stop' increments from begin(), stopping when we - // get to 'first', and capturing the remaining number of - // increments. - difference_type increments_past_start = - advance_upto(dummy, stop, first, iterator_category()); - if (increments_past_start == 0) { - // If this is 0, then stop was before start. - last = first; - } else { - // Otherwise, count that many spaces beyond first. - last = first; - advance_upto(last, increments_past_start, end(), iterator_category()); - } - } - } - return range(first, last); - } - - range dispatch_slice(difference_type start, difference_type stop, - std::random_access_iterator_tag) const { - const difference_type size = this->size(); - if (start < 0) - start = size + start; - if (start < 0) - start = 0; - if (start > size) - start = size; - - if (stop < 0) - stop = size + stop; - if (stop < start) - stop = start; - if (stop > size) - stop = size; - - return range(begin() + start, begin() + stop); - } -}; - -/// \name deducing constructor wrappers -/// \relates std::range -/// \xmlonly <nonmember/> \endxmlonly -/// -/// These functions do the same thing as the constructor with the same -/// signature. They just allow users to avoid writing the iterator -/// type. -/// @{ - -/// \todo I'd like to define a \c make_range taking a single iterator -/// argument representing the beginning of a range that ends with a -/// default-constructed \c Iterator. This would help with using -/// iterators like \c istream_iterator. However, using just \c -/// make_range() could be confusing and lead to people writing -/// incorrect ranges of more common iterators. Is there a better name? -template <typename Iterator> -LLVM_CONSTEXPR range<Iterator> make_range(Iterator begin, Iterator end) { - return range<Iterator>(begin, end); -} - -/// \par Participates in overload resolution if: -/// \c begin(r) and \c end(r) return the same type. -template <typename Range> LLVM_CONSTEXPR auto make_range( - Range &&r, - typename std::enable_if<detail::is_range<Range>::value>::type* = 0) - -> range<decltype(detail::adl_begin(r))> { - return range<decltype(detail::adl_begin(r))>(r); -} - -/// \par Participates in overload resolution if: -/// - \c begin(r) and \c end(r) return the same type, -/// - that type satisfies the invariant that <code>&*(i + N) == -/// (&*i) + N</code>, and -/// - \c &*begin(r) has a pointer type. -template <typename Range> LLVM_CONSTEXPR auto make_ptr_range( - Range &&r, - typename std::enable_if< - detail::is_contiguous_range<Range>::value && - std::is_pointer<decltype(&*detail::adl_begin(r))>::value>::type* = 0) - -> range<decltype(&*detail::adl_begin(r))> { - return range<decltype(&*detail::adl_begin(r))>(r); -} -/// @} -} // end namespace lld - -#endif |