1
0
mirror of https://github.com/RPCS3/llvm-mirror.git synced 2024-10-19 02:52:53 +02:00
Commit Graph

2830 Commits

Author SHA1 Message Date
Jared Wyles
a93205f987 [jitlink] R_X86_64_PC32 support for the elf x86 jitlinker
Summary:

Adding in our first relocation type, and all the required plumbing to support the rest in following patches

Differential Revision: https://reviews.llvm.org/D80613

Reviewer: lhames
2020-05-30 10:53:18 +10:00
Lang Hames
9acf657a35 [ORC] Add debugging output for LLJIT construction.
This can be handy for checking whether the LLJIT instance you're constructing
matches your expectations.
2020-05-28 20:31:50 -07:00
Lang Hames
4f5e68aaf3 [JITLink] Improve llvm-jitlink regression testing support for ELF.
This patch adds a jitlink pass, 'registerELFGraphInfo', that records section
and symbol information about each LinkGraph in the llvm-jitlink session object.
This allows symbols and sections to be referred to by name in llvm-jitlink
regression tests. This will enable a testcase to be written for
https://reviews.llvm.org/D80613.
2020-05-28 20:31:50 -07:00
David Blaikie
30e53f607c Roll variables into an LLVM_DEBUG block to address -Wunused-but-set-variable 2020-05-26 12:05:08 -07:00
Simon Pilgrim
103e684408 Fix msvc "switch statement contains 'default' but no 'case' labels" warning. NFC.
Stripped out the switch statement, but kept case labels as comments for future reference.
2020-05-22 10:49:10 +01:00
Lang Hames
ee91e79e53 [JITLink] Initial implementation of ELF / x86-64 support for JITLink.
This initial implementation supports section and symbol parsing, but no
relocation support. It enables JITLink to link and execute ELF relocatable
objects that do not require relocations.

Patch by Jared Wyles. Thanks Jared!

Differential Revision: https://reviews.llvm.org/D79832
2020-05-21 21:44:00 -07:00
Lang Hames
a145c06983 [ORC] Share ownership of JITDylibs between ExecutionSession and
MaterializationResponsibility.

MaterializationResponsibility objects provide a connection between a
materialization process (compiler, jit linker, etc.) and the JIT state held in
the ExecutionSession and JITDylib objects. Switching to shared ownership
extends the lifetime of JITDylibs to ensure they remain accessible until all
materializers targeting them have completed. This will allow (in a follow-up
patch) JITDylibs to be removed from the ExecutionSession and placed in a
pending-destruction state while they are kept alive to communicate errors
to/from any still-runnning materialization processes. The intent is to enable
JITDylibs to be safely removed even if they have running compiles targeting
them.
2020-05-10 16:37:17 -07:00
Lang Hames
7864e622b1 [ORC] Rename SearchOrder operations on JITDylib to LinkOrder.
Refering to the link order of a dylib better matches the terminology used in
static compilation. As upcoming patches will increase the number of places where
link order matters (for example when closing JITDylibs) it's better to get this
name change out of the way early.
2020-05-04 16:47:52 -07:00
Lang Hames
1493399b9d [JITLink] Fix missing ADDITIONAL_HEADER_DIRS for the LLVMJITLink component.
Also adds target_link_libraries.

Thanks to @jcmac for spotting this.
2020-05-04 12:58:09 -07:00
Lang Hames
65ff3816c6 [JITLink] Fix a typo in a comment.
Thanks to @jcmac for pointing this out.
2020-05-04 12:58:09 -07:00
Sam McCall
9e1817bf4e std::isspace -> llvm::isSpace (where locale should be ignored)
I've left out some cases where I wasn't totally sure this was right or
whether the include was ok (compiler-rt) or idiomatic (flang).
2020-05-02 15:36:04 +02:00
Xing GUO
0cc48af0ab [Object] Change ObjectFile::getSymbolValue() return type to Expected<uint64_t>
Summary:
In D77860, we have changed `getSymbolFlags()` return type to `Expected<uint32_t>`.
This change helps bubble the error further up the stack.

Reviewers: jhenderson, grimar, JDevlieghere, MaskRay

Reviewed By: jhenderson

Subscribers: hiraditya, MaskRay, rupprecht, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D79075
2020-05-02 14:04:44 +08:00
Craig Topper
8757f48ecf [IR] Replace all uses of CallBase::getCalledValue() with getCalledOperand().
This method has been commented as deprecated for a while. Remove
it and replace all uses with the equivalent getCalledOperand().

I also made a few cleanups in here. For example, to removes use
of getElementType on a pointer when we could just use getFunctionType
from the call.

Differential Revision: https://reviews.llvm.org/D78882
2020-04-27 22:17:03 -07:00
Lang Hames
59e4d993a0 [JITLink] Fix endianness bug fedd32e2fa36.
The ByteSwap_NN functions return their result rather than modifying their
argument in-place, so we need to write the result back to CPUType here.
2020-04-27 10:40:11 -07:00
Simon Pilgrim
fe37a7c733 MCJIT.h - reduce unnecessary includes to forward declarations. NFC. 2020-04-25 12:58:25 +01:00
Simon Pilgrim
1ad8ea0571 RuntimeDyldELF.h - make the object namespace explicit for ELFObjectFileBase. NFC. 2020-04-23 13:52:49 +01:00
Lang Hames
4713d7a998 [JITLink] Fix edge removal iterator invalidation.
This patch changes Block::removeEdge to return a valid iterator to the new next
element, and uses this to update the edge removal algorithm in
LinkGraph::splitBlock.
2020-04-22 14:16:46 -07:00
Lang Hames
2ccfae6930 [JITLink] Read MachO Header CPU field only in jitLink_MachO.
It's the only field we need in this function.
2020-04-22 14:16:46 -07:00
Christopher Tetreault
7f0438624e [SVE] Add new VectorType subclasses
Summary:
Introduce new types for fixed width and scalable vectors.

Does not remove getNumElements yet so as to not break code during transition
period.

Reviewers: deadalnix, efriedma, sdesmalen, craig.topper, huntergr

Reviewed By: sdesmalen

Subscribers: jholewinski, arsenm, jvesely, nhaehnle, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, liufengdb, kerbowa, Joonsoo, grosul1, frgossen, lldb-commits, tschuett, hiraditya, rkruppe, psnobl, llvm-commits

Tags: #llvm, #lldb

Differential Revision: https://reviews.llvm.org/D77587
2020-04-22 08:59:01 -07:00
Simon Pilgrim
46fa565705 RuntimeDyldImpl.h - remove unused Twine forward declaration. NFC. 2020-04-22 15:07:17 +01:00
Craig Topper
bb554c7b77 [CallSite removal] Remove unneeded includes of CallSite.h. NFC 2020-04-22 00:07:13 -07:00
Craig Topper
a51a057b22 [CallSite removal][ExecutionEngine] Use CallBase in the Interpreter. NFC
Differential Revision: https://reviews.llvm.org/D78475
2020-04-20 10:37:03 -07:00
Lang Hames
c0b552bc67 [ORC] Replace LLJIT::defineAbsolute with an LLJIT::define convenience method.
LLJIT::defineAbsolute did not mangle its Name argument, which is inconsistent
with the behavior of other LLJIT methods (e.g. lookup). Since it is currently
unused anyway, this commit replaces it with a generic 'define' convenience
method for adding MaterializationUnits to the main JITDylib. This simplifies
use of the generic absoluteSymbols function (as well as the symbolAlias,
reexports and other functions that generate MaterializationUnits) with LLJIT.
2020-04-18 14:16:54 -07:00
vgxbj
bbdc25ab11 [Object] Change uint32_t getSymbolFlags() to Expected<uint32_t> getSymbolFlags().
This change enables getSymbolFlags() to return errors which benefit error reporting in clients.

Differential Revision: https://reviews.llvm.org/D77860
2020-04-18 21:27:57 +08:00
Lang Hames
ce4983f5c3 [Object] Remove conditional layout of bitfields in MachO::relocation_info.
This removes the conditional layout of relocation_info bitfields that was
introduced in 3ccd677bf (svn r358839). The platform relocation_info
struct (defined in usr/include/mach-o/reloc.h) does not define the layout of
this struct differently on big-endian platforms and we want to keep the LLVM
and platform definitions in sync.

To fix the bug that 3ccd677bf addressed this patch modifies JITLink to construct
its relocation_info structs from the raw relocation words using shift and mask
operations.
2020-04-16 16:17:36 -07:00
Sergej Jaskiewicz
430e5ccef4 Introduce llvm::sys::Process::getProcessId() and adopt it
Differential Revision: https://reviews.llvm.org/D78022
2020-04-16 15:05:37 +03:00
Lang Hames
deddb8bde9 [ORC] Add an OrcV2 C API function for configuring TargetMachines. 2020-04-10 15:51:29 -07:00
Lang Hames
4315ffca85 [ORC] Require JITDylib to be specified when adding IR and objects in the C API. 2020-04-09 17:59:26 -07:00
Lang Hames
a737d1b399 [ORC] Add C API support for adding object files to an LLJIT instance. 2020-04-09 16:18:46 -07:00
Lang Hames
e2925289c9 [ORC] Expand the OrcV2 C API bindings.
Adds basic support for LLJITBuilder and DynamicLibrarySearchGenerator. This
allows C API clients to configure LLJIT to expose process symbols to JIT'd
code. An example of this is added in
llvm/examples/OrcV2CBindingsReflectProcessSymbols.
2020-04-09 16:18:46 -07:00
Lang Hames
6cbaa73f51 [ORC] Make mangling convenience methods part of the public API of LLJIT.
This saves clients from having to manually construct a MangleAndInterner.
2020-04-08 20:20:13 -07:00
Benjamin Kramer
97d5ac4c23 [RuntimeDyld] Replace hand-rolled endian conversion with support::endian. NFCI. 2020-04-06 13:22:53 +02:00
Lang Hames
5c93ab4970 [ORC] Add MachO universal binary support to StaticLibraryDefinitionGenerator.
Add a new overload of StaticLibraryDefinitionGenerator::Load that takes a triple
argument and supports loading archives from MachO universal binaries in addition
to regular archives.

The LLI tool is updated to use this overload.
2020-04-05 20:21:05 -07:00
Lang Hames
da5bdc7302 Re-apply 0071eaaf089, "[ORC] Export __cxa_atexit ...", with fixes.
Forgot to include part of the testcase. Thank to Nico for spotting that and
reverting!
2020-04-02 16:03:35 -07:00
Nico Weber
f66efc2783 Revert "[ORC] Export __cxa_atexit from the main JITDylib in LLJIT."
This reverts commit 0071eaaf0892d7ef733578312abefdcf84311071.
Inputs/noop-main.ll wasn't checked in, so this breaks check-llvm
everywhere.
2020-04-01 22:49:38 -04:00
Lang Hames
b3739f14b9 [ORC] Export __cxa_atexit from the main JITDylib in LLJIT.
Failure to export __cxa_atexit can lead to an attempt to import a definition
from the process itself (if __cxa_atexit is referenced from another JITDylib),
but the process definition will clash with the existing non-exported definition
to produce an unexpected DuplicateDefinitionError.

This patch fixes the immediate issue by exporting __cxa_atexit. It also fixes a
bug where atexit functions in other JITDylibs were not being run by adding a
copy of run_atexits_helper to every JITDylib.

A follow up patch will deal with the bug where definition generators are called
despite a non-exported definition being present.
2020-04-01 19:12:08 -07:00
Lang Hames
df818b7034 [ORC] Don't require a null-terminator on MemoryBuffers for objects in archives.
The MemoryBuffer::getMemBuffer method's RequiresNullTerminator parameter
defaults to true, but object files are not null terminated so we need to
explicitly pass false here.
2020-04-01 12:16:38 -07:00
Eli Friedman
db20f1e2c5 Remove "mask" operand from shufflevector.
Instead, represent the mask as out-of-line data in the instruction. This
should be more efficient in the places that currently use
getShuffleVector(), and paves the way for further changes to add new
shuffles for scalable vectors.

This doesn't change the syntax in textual IR. And I don't currently plan
to change the bitcode encoding in this patch, although we'll probably
need to do something once we extend shufflevector for scalable types.

I expect that once this is finished, we can then replace the raw "mask"
with something more appropriate for scalable vectors.  Not sure exactly
what this looks like at the moment, but there are a few different ways
we could handle it.  Maybe we could try to describe specific shuffles.
Or maybe we could define it in terms of a function to convert a fixed-length
array into an appropriate scalable vector, using a "step", or something
like that.

Differential Revision: https://reviews.llvm.org/D72467
2020-03-31 13:08:59 -07:00
Lang Hames
c9245d5323 [ORC] Introduce JITSymbolFlags::HasMaterializeSideEffectsOnly flag.
This flag can be used to mark a symbol as existing only for the purpose of
enabling materialization. Such a symbol can be looked up to trigger
materialization with the lookup returning only once materialization is
complete. Symbols with this flag will never resolve however (to avoid
permanently polluting the symbol table), and should only be looked up using
the SymbolLookupFlags::WeaklyReferencedSymbol flag. The primary use case for
this flag is initialization symbols.
2020-03-27 11:02:54 -07:00
Lang Hames
c31e638b4f [ORC] Don't create MaterializingInfo entries unnecessarily. 2020-03-27 11:02:54 -07:00
Alina Sbirlea
a5d6fe1986 [CFG/BasicBlock] Rename succ_const to const_succ. [NFC]
Summary:
Rename `succ_const_iterator` to `const_succ_iterator` and
`succ_const_range` to `const_succ_range` for consistency with the
predecessor iterators, and the corresponding iterators in
MachineBasicBlock.

Reviewers: nicholas, dblaikie, nlewycky

Subscribers: hiraditya, bmahjour, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75952
2020-03-25 12:40:55 -07:00
Lang Hames
885fe25f2c [ORC] Move ostream operators for debugging output out of Core.h.
DebugUtils.h seems like a more appropriate home for these.
2020-03-21 18:27:28 -07:00
Lang Hames
f9245f3da0 [ORC] Re-apply 98f2bb44610, enable JITEventListeners in OrcV2, with fixes.
Updates the object buffer ownership scheme in jitLinkForOrc and related
functions: Ownership of both the object::ObjectFile and underlying
MemoryBuffer is passed into jitLinkForOrc and passed back to the onEmit
callback once linking is complete. This avoids the use-after-free errors
that were seen in 98f2bb44610.
2020-03-19 16:30:08 -07:00
Lang Hames
dac63bbcfc [ORC] Don't use a platform mutex for LLJIT's GenericLLVMIRPlatformSupport class.
Along the same lines as eb918d8daf1: This code also had to acquire the session
mutex, and this could cause a deadlock under the wrong circumstances. This
patch updates GenericLLVMIRPlatformSupport to just use the session lock for
everything.
2020-03-19 11:03:34 -07:00
Lang Hames
2945504341 [ORC] Fix indentation in debugging output. 2020-03-19 11:02:56 -07:00
Lang Hames
f62b9d12ef [ORC] Use finer-grained and session locking in MachOPlatform to avoid deadlock.
In MachOPlatform, obtaining the link-order for a JITDylib requires locking the
session, but also needs to be part of a larger atomic operation that collates
initializer symbols tracked by the platform. Trying to do this under a separate
platform mutex leads to potential locking order issues, e.g.

T1 locks session then tries to lock platform to register a new init symbol
meanwhile
T2 locks platform then tries to lock session to obtain link order.

Removing the platform lock and performing all these operations under the session
lock eliminates this possibility.

At the same time we also need to collate init pointers from the
MachOPlatform::InitScraperPlugin, and we don't need or want to lock the session
for that. The new InitSeqMutex has been added to guard these init pointers, and
the session mutex is never obtained while the InitSeqMutex is held.
2020-03-19 11:02:56 -07:00
Lang Hames
ea57541031 [ORC] Don't waste time building empty replacement MaterializationUnits. 2020-03-19 11:02:56 -07:00
Lang Hames
91189ff985 [ORC] Bail out early if a replacement MaterializationUnit is empty.
The MU may define no symbols, but still contain a non-trivial destructor (e.g.
an LLVM IR module that has been stripped of all externally visible
definitions, but which still needs to lock its context to be destroyed).
Bailing out early ensures that we destroy the unit outside the session lock,
rather than under it which may cause deadlocks.

Also adds some extra sanity-checking assertions.
2020-03-19 11:02:56 -07:00
Fangrui Song
bb43600d6c [Object] Change ELFObjectFile<ELFT>::getFileFormatName() to use BFD names
Follow-up for D74433

What the function returns are almost standard BFD names, except that "ELF" is
in uppercase instead of lowercase.

This patch changes "ELF" to "elf" and changes ARM/AArch64 to use their BFD names.
MIPS and PPC64 have endianness differences as well, but this patch does not intend to address them.

Advantages:

* llvm-objdump: the "file format " line matches GNU objdump on ARM/AArch64 objects
* "file format " line can be extracted and fed into llvm-objcopy -O literally.
  (https://github.com/ClangBuiltLinux/linux/issues/779 has such a use case)

Affected tools: llvm-readobj, llvm-objdump, llvm-dwarfdump, MCJIT (internal implementation detail, not exposed)

Reviewed By: jhenderson

Differential Revision: https://reviews.llvm.org/D76046
2020-03-16 07:42:04 -07:00
Lang Hames
82ffd8566c Revert "[ORC] Enable JITEventListeners in the RTDyldObjectLinkingLayer."
This reverts commit 98f2bb4461072347dcca7d2b1b9571b3a6525801.

Reverting while I investigate bot failures.
2020-03-15 15:35:08 -07:00
Lang Hames
64ff6abf1f [ORC] Enable JITEventListeners in the RTDyldObjectLinkingLayer.
Enable use of ExecutionEngine JITEventListeners in RTDyldObjectLinkingLayer.
This allows existing MCJIT clients to more easily migrate to LLJIT / ORCv2.

Example usage in llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener.

Differential Revision: https://reviews.llvm.org/D75838
2020-03-15 15:14:46 -07:00
Lang Hames
13786f8eaf [ORC] Print symbol flags and materializer name in ExecutionSession::dump.
The extra information can be helpful in diagnosing JIT bugs.
2020-03-14 18:52:10 -07:00
Lang Hames
42492d3889 [JITLink][MachO] Re-apply b64afadf306, MachO linker-private support, with fixes.
Global symbols with linker-private prefixes should be resolvable across object
boundaries, but internal symbols with linker-private prefixes should not.
2020-03-14 18:36:15 -07:00
Lang Hames
80d993d0f0 Revert "[JITLink][MachO] Treat linker private symbols as hidden rather than private."
This reverts commit b64afadf306f284a684ee656c6eefbd43c192c8d.

Reverting while I investigate bot failures.
2020-03-14 16:52:25 -07:00
Lang Hames
16ceeef4af [JITLink][MachO] Treat linker private symbols as hidden rather than private.
Linker-private symbols should be resolvable across object file boundaries.
2020-03-14 16:33:15 -07:00
Lang Hames
4ce58a4d70 [Orc] Add basic OrcV2 C bindings and example.
Renames the llvm/examples/LLJITExamples directory to llvm/examples/OrcV2Examples
since it is becoming a home for all OrcV2 examples, not just LLJIT.

See http://llvm.org/PR31103.
2020-03-14 14:41:22 -07:00
Jan Korous
0fd46fd26a [LLJIT] Add std::move() as a workaround for older compilers
Clang 3.8 isn't able to bind the variable to rvalue-ref which breaks the build.
2020-03-13 15:25:25 -07:00
Lang Hames
c3e7231c1f [MCJIT] Check for RuntimeDyld errors in MCJIT::finalizeLoadedModules.
Patch based on https://reviews.llvm.org/D75912 by Alexander Shishkin. Thanks
Alexander!

To minimize disruption to existing clients, who may be relying on the fact that
unused references to unresolved symbols do not generate an error, this patch
makes error checking opt-in: Clients can call ExecutionEngine::hasError or
LLVMExecutionEngineGetError to check whether and error has occurred.

Differential revision: https://reviews.llvm.org/D75912
2020-03-13 13:58:41 -07:00
Lang Hames
2e64fe9bf7 [ORC] Enable exception handling in JIT'd code when using LLJIT on Darwin.
This patch enables exception handling in code added to LLJIT on Darwin by
adding an orc::EHFrameRegistrationPlugin instance to the ObjectLinkingLayer
(which is currently used on Darwin only).
2020-03-12 15:33:56 -07:00
Lang Hames
a043ecbcf2 [ORC] Add a mutex to guard EHFrameRegistrationPlugin data structures.
These may be accessed from multiple threads if concurrent materialization is
enabled in ORC.

Testcase coming in a follow-up patch that enables eh-frame registration for
LLJIT.
2020-03-12 15:33:56 -07:00
Lang Hames
851489e81b [JITLink] Read symbol linkage from the correct field.
MachO symbol linkage is described by the desc field of the nlist entry, not the
type field.
2020-03-11 20:04:54 -07:00
Lang Hames
3bba4369ea [ORC] Fix an overly aggressive assert.
It is ok to add dependencies on symbols that are ready, they should just be
skipped.
2020-03-11 20:04:54 -07:00
Lang Hames
6f6fbeb0c0 [ORC] Add some extra debugging output. 2020-03-11 20:04:54 -07:00
Reid Kleckner
61b0badcbd Drop a StringMap.h include, NFC
$ diff -u <(sort thedeps-before.txt) <(sort thedeps-after.txt) \
    | grep '^[-+] ' | sort | uniq -c | sort -nr
    231 -    llvm/include/llvm/ADT/StringMap.h
    171 -    llvm/include/llvm/Support/AllocatorBase.h
    142 -    llvm/include/llvm/Support/PointerLikeTypeTraits.h
2020-03-11 15:45:34 -07:00
Lang Hames
bc59809461 [RuntimeDyld][COFF] Build stubs for COFF dllimport symbols.
Summary:
Enables JIT-linking by RuntimeDyld of COFF objects that contain references to
dllimport symbols. This is done by recognizing symbols that start with the
reserved "__imp_" prefix and building a pointer entry to the target symbol in
the stubs area of the section. References to the "__imp_" symbol are updated to
point to this pointer.

Work in progress: The generic code is in place, but only RuntimeDyldCOFFX86_64
and RuntimeDyldCOFFI386 have been updated to look for and update references to
dllimport symbols.

Reviewers: compnerd

Subscribers: hiraditya, ributzka, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75884
2020-03-10 16:08:40 -07:00
Lang Hames
9a8419c639 [RuntimeDyld] Allow multi-line rtdyld-check and jitlink-check expressions.
This patch allows rtdyld-check / jitlink-check expressions to be extended over
multiple lines by terminating each line with a '\'. E.g.

  # llvm-rtdyld: *{8}X = \
  # llvm-rtdyld:   Y
  X:
    .quad Y

This will be used to break up some long lines in upcoming test cases.
2020-03-10 16:08:40 -07:00
Benjamin Kramer
5193ea06e9 Give helpers internal linkage. NFC. 2020-03-10 18:27:42 +01:00
serge-sans-paille
2cab2132ef Avoid dangling reference on SectionList
Bug spotted by https://cookieplmonster.github.io/2020/02/01/emulator-bug-llvm-bug/

Basically, holding references to object inside a resized vector is a bad idea.

Differential Revision: https://reviews.llvm.org/D75110
2020-03-05 09:42:24 +01:00
Lang Hames
87a444bd04 [ORC] Remove hard dependency on libobjc when using MachOPlatform with LLJIT.
The LLJIT::MachOPlatformSupport class used to unconditionally attempt to
register __objc_selrefs and __objc_classlist sections. If libobjc had not
been loaded this resulted in an assertion, even if no objc sections were
actually present. This patch replaces this unconditional registration with
a check that no objce sections are present if libobjc has not been loaded.
This will allow clients to use MachOPlatform with LLJIT without requiring
libobjc for non-objc code.
2020-03-04 21:49:28 -08:00
Stefan Gränitz
81cfd93bf4 [ORC] Decompose LazyCallThroughManager::callThroughToSymbol()
Summary: Decompose callThroughToSymbol() into findReexport(), resolveSymbol(), notifyResolved() and reportCallThroughError(). This allows derived classes to reuse the functionality while adding their own code in between.

Reviewers: lhames

Reviewed By: lhames

Subscribers: hiraditya, steven_wu, dexonsmith, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75084
2020-03-05 00:24:23 +01:00
Lang Hames
0046e8e4e8 [ORC] Add some debugging output for initializers.
This output can be useful in tracking down initialization failures in the JIT.
2020-03-04 12:38:25 -08:00
Lang Hames
af3fbf0d88 [ORC] Skip ST_File symbols in MaterializationUnit interfaces / resolution.
ST_File symbols aren't relevant for linking purposes, but can end up shadowing
real symbols if they're not filtered.

No test case yet: The ideal testcase for this would be an ELF llvm-jitlink test,
but llvm-jitlink support for ELF is still under development. We should add a
testcase for this once support lands in tree.
2020-03-03 16:15:44 -08:00
Lang Hames
efa76b5281 [JITLink] Fix a pointer-to-integer cast in jitlink::InProcessMemoryManager.
reinterpret_cast'ing the block base address directly to a uint64_t leaves the
high bits in an implementation-defined state, but JITLink expects them to be
zero. Switching to pointerToJITTargetAddress for the cast should fix this.

This should fix the jitlink test failures that we have seen on some of the
32-bit testers.
2020-03-03 13:53:00 -08:00
Lang Hames
ab72e4c1c4 [ORC] Make sure we add initializers to the SymbolFlags map for objects. 2020-03-03 09:33:37 -08:00
Lang Hames
675f5945b9 [ORC] Remove an out-of-date FIXME 2020-03-03 09:33:37 -08:00
Reid Kleckner
80428fb35f Avoid including FileSystem.h from MemoryBuffer.h
Lots of headers pass around MemoryBuffer objects, but very few open
them. Let those that do include FileSystem.h.

Saves ~250 includes of Chrono.h & FileSystem.h:

$ diff -u thedeps-before.txt thedeps-after.txt | grep '^[-+] ' | sort | uniq -c | sort -nr
    254 -    ../llvm/include/llvm/Support/FileSystem.h
    253 -    ../llvm/include/llvm/Support/Chrono.h
    237 -    ../llvm/include/llvm/Support/NativeFormatting.h
    237 -    ../llvm/include/llvm/Support/FormatProviders.h
    192 -    ../llvm/include/llvm/ADT/StringSwitch.h
    190 -    ../llvm/include/llvm/Support/FormatVariadicDetails.h
...

This requires duplicating the file_t typedef, which is unfortunate. I
sunk the choice of mapping mode down into the cpp file using variable
template specializations instead of class members in headers.
2020-02-29 12:30:23 -08:00
Stefan Gränitz
0becb69ddb [ExecutionEngine] Add JITSymbolFlags::fromSummary(GlobalValueSummary*)
Summary: A function that creates JITSymbolFlags from a GlobalValueSummary. Similar functions exist: fromGlobalValue(), fromObjectSymbol()

Reviewers: lhames

Reviewed By: lhames

Subscribers: hiraditya, steven_wu, dexonsmith, arphaman, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75082
2020-02-29 11:54:03 +00:00
Lang Hames
e1f68ca3b5 [ORC] Remove the JITDylib::SymbolTableEntry::isInMaterializingState() method.
It was being used inconsistently. Uses have been replaced with direct checks
on the symbol state.
2020-02-25 16:44:12 -08:00
Benjamin Kramer
707b7beede [ORC] Remove spammy debug print 2020-02-24 12:10:13 +01:00
Lang Hames
7247401c11 [JITLink] Add a MachO x86-64 GOT and Stub bypass optimization.
This optimization bypasses GOT loads and calls/branches through stubs when the
ultimate target of the access/branch is found to be within range of the
reference.

Extra debugging output is also added to the generic JITLink algorithm and
basic GOT and Stubs builder utility to aid debugging.
2020-02-23 23:38:31 -08:00
Lang Hames
b6c9039962 [ORC] Update LLJIT to automatically run specially named initializer functions.
The GenericLLVMIRPlatformSupport class runs a transform on all LLVM IR added to
the LLJIT instance to replace instances of llvm.global_ctors with a specially
named function that runs the corresponing static initializers (See
(GlobalCtorDtorScraper from lib/ExecutionEngine/Orc/LLJIT.cpp). This patch
updates the GenericIRPlatform class to check for this specially named function
in other materialization units that are added to the JIT and, if found, add
the function to the initializer work queue. Doing this allows object files
that were compiled from IR and cached to be reloaded in subsequent JIT sessions
without their initializers being skipped.

To enable testing this patch also updates the lli tool's -jit-kind=orc-lazy mode
to respect the -enable-cache-manager and -object-cache-dir options, and modifies
the CompileOnDemandLayer to rename extracted submodules to include a hash of the
names of their symbol definitions. This allows a simple object caching scheme
based on module names (which was already implemented in lli) to work with the
lazy JIT.
2020-02-22 11:49:14 -08:00
Lang Hames
46f1687baa [ORC] Add errors for missing and extraneous symbol definitions.
This patch adds new errors and error checking to the ObjectLinkingLayer to
catch cases where a compiled or loaded object either:
(1) Contains definitions not covered by its responsibility set, or
(2) Is missing definitions that are covered by its responsibility set.

Proir to this patch providing the correct set of definitions was treated as
an API contract requirement, however this requires that the client be confident
in the correctness of the whole compiler / object-cache pipeline and results
in difficult-to-debug assertions upon failure. Treating this as a recoverable
error results in clearer diagnostics.

The performance overhead of this check is one comparison of densemap keys
(symbol string pointers) per linking object, which is minimal. If this overhead
ever becomes a problem we can add the check under a flag that can be turned off
if the client fully trusts the rest of the pipeline.
2020-02-22 11:49:14 -08:00
Hans Wennborg
e1296518ec Add #include <condition_variable> to fix build after 85fb997659b5
See https://reviews.llvm.org/D74300#1884614
2020-02-20 16:36:19 +01:00
Lang Hames
117fadbabd [ORC] Fix a missing move. 2020-02-19 14:27:31 -08:00
Lang Hames
900dc7edc7 [ORC] Add generic initializer/deinitializer support.
Initializers and deinitializers are used to implement C++ static constructors
and destructors, runtime registration for some languages (e.g. with the
Objective-C runtime for Objective-C/C++ code) and other tasks that would
typically be performed when a shared-object/dylib is loaded or unloaded by a
statically compiled program.

MCJIT and ORC have historically provided limited support for discovering and
running initializers/deinitializers by scanning the llvm.global_ctors and
llvm.global_dtors variables and recording the functions to be run. This approach
suffers from several drawbacks: (1) It only works for IR inputs, not for object
files (including cached JIT'd objects). (2) It only works for initializers
described by llvm.global_ctors and llvm.global_dtors, however not all
initializers are described in this way (Objective-C, for example, describes
initializers via specially named metadata sections). (3) To make the
initializer/deinitializer functions described by llvm.global_ctors and
llvm.global_dtors searchable they must be promoted to extern linkage, polluting
the JIT symbol table (extra care must be taken to ensure this promotion does
not result in symbol name clashes).

This patch introduces several interdependent changes to ORCv2 to support the
construction of new initialization schemes, and includes an implementation of a
backwards-compatible llvm.global_ctor/llvm.global_dtor scanning scheme, and a
MachO specific scheme that handles Objective-C runtime registration (if the
Objective-C runtime is available) enabling execution of LLVM IR compiled from
Objective-C and Swift.

The major changes included in this patch are:

(1) The MaterializationUnit and MaterializationResponsibility classes are
extended to describe an optional "initializer" symbol for the module (see the
getInitializerSymbol method on each class). The presence or absence of this
symbol indicates whether the module contains any initializers or
deinitializers. The initializer symbol otherwise behaves like any other:
searching for it triggers materialization.

(2) A new Platform interface is introduced in llvm/ExecutionEngine/Orc/Core.h
which provides the following callback interface:

  - Error setupJITDylib(JITDylib &JD): Can be used to install standard symbols
    in JITDylibs upon creation. E.g. __dso_handle.

  - Error notifyAdding(JITDylib &JD, const MaterializationUnit &MU): Generally
    used to record initializer symbols.

  - Error notifyRemoving(JITDylib &JD, VModuleKey K): Used to notify a platform
    that a module is being removed.

  Platform implementations can use these callbacks to track outstanding
initializers and implement a platform-specific approach for executing them. For
example, the MachOPlatform installs a plugin in the JIT linker to scan for both
__mod_inits sections (for C++ static constructors) and ObjC metadata sections.
If discovered, these are processed in the usual platform order: Objective-C
registration is carried out first, then static initializers are executed,
ensuring that calls to Objective-C from static initializers will be safe.

This patch updates LLJIT to use the new scheme for initialization. Two
LLJIT::PlatformSupport classes are implemented: A GenericIR platform and a MachO
platform. The GenericIR platform implements a modified version of the previous
llvm.global-ctor scraping scheme to provide support for Windows and
Linux. LLJIT's MachO platform uses the MachOPlatform class to provide MachO
specific initialization as described above.

Reviewers: sgraenitz, dblaikie

Subscribers: mgorny, hiraditya, mgrang, ributzka, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D74300
2020-02-19 13:59:32 -08:00
Alexandre Ganea
ae05eb086d [Support] On Windows, ensure hardware_concurrency() extends to all CPU sockets and all NUMA groups
The goal of this patch is to maximize CPU utilization on multi-socket or high core count systems, so that parallel computations such as LLD/ThinLTO can use all hardware threads in the system. Before this patch, on Windows, a maximum of 64 hardware threads could be used at most, in some cases dispatched only on one CPU socket.

== Background ==
Windows doesn't have a flat cpu_set_t like Linux. Instead, it projects hardware CPUs (or NUMA nodes) to applications through a concept of "processor groups". A "processor" is the smallest unit of execution on a CPU, that is, an hyper-thread if SMT is active; a core otherwise. There's a limit of 32-bit processors on older 32-bit versions of Windows, which later was raised to 64-processors with 64-bit versions of Windows. This limit comes from the affinity mask, which historically is represented by the sizeof(void*). Consequently, the concept of "processor groups" was introduced for dealing with systems with more than 64 hyper-threads.

By default, the Windows OS assigns only one "processor group" to each starting application, in a round-robin manner. If the application wants to use more processors, it needs to programmatically enable it, by assigning threads to other "processor groups". This also means that affinity cannot cross "processor group" boundaries; one can only specify a "preferred" group on start-up, but the application is free to allocate more groups if it wants to.

This creates a peculiar situation, where newer CPUs like the AMD EPYC 7702P (64-cores, 128-hyperthreads) are projected by the OS as two (2) "processor groups". This means that by default, an application can only use half of the cores. This situation could only get worse in the years to come, as dies with more cores will appear on the market.

== The problem ==
The heavyweight_hardware_concurrency() API was introduced so that only *one hardware thread per core* was used. Once that API returns, that original intention is lost, only the number of threads is retained. Consider a situation, on Windows, where the system has 2 CPU sockets, 18 cores each, each core having 2 hyper-threads, for a total of 72 hyper-threads. Both heavyweight_hardware_concurrency() and hardware_concurrency() currently return 36, because on Windows they are simply wrappers over std:🧵:hardware_concurrency() -- which can only return processors from the current "processor group".

== The changes in this patch ==
To solve this situation, we capture (and retain) the initial intention until the point of usage, through a new ThreadPoolStrategy class. The number of threads to use is deferred as late as possible, until the moment where the std::threads are created (ThreadPool in the case of ThinLTO).

When using hardware_concurrency(), setting ThreadCount to 0 now means to use all the possible hardware CPU (SMT) threads. Providing a ThreadCount above to the maximum number of threads will have no effect, the maximum will be used instead.
The heavyweight_hardware_concurrency() is similar to hardware_concurrency(), except that only one thread per hardware *core* will be used.

When LLVM_ENABLE_THREADS is OFF, the threading APIs will always return 1, to ensure any caller loops will be exercised at least once.

Differential Revision: https://reviews.llvm.org/D71775
2020-02-14 10:24:22 -05:00
Fangrui Song
e81ba0b0a3 [AsmPrinter] De-capitalize all AsmPrinter::Emit* but EmitInstruction
Similar to rL328848.
2020-02-13 17:06:24 -08:00
Lang Hames
b170349fb7 [ORC] Fix symbol dependence propagation algorithm in ObjectLinkingLayer.
ObjectLinkingLayer was not correctly propagating dependencies through local
symbols within an object. This could cause symbol lookup to return before a
searched-for symbol is ready if the following conditions are met:
(1) The definition of the symbol being searched for transitively depends on a
    local symbol within the same object, and that local symbol in turn
    transitively depends on an external symbol provided by some other module
    in the JIT.
(2) Concurrent compilation is enabled.
(3) Thread scheduling causes the lookup of the searched-for symbol to return
    before all transitive dependencies of the looked-up symbol are emitted.

This bug was found by inspection and has not been observed in practice.

A jitlink test case has been added to verify that symbol dependencies are
correctly propagated through local symbol definitions.
2020-02-11 12:56:41 -08:00
Lang Hames
1b4cebd3b1 [ORC] Add debug logging to JITDylib::addDependencies. 2020-02-11 12:56:40 -08:00
Bill Wendling
0816222e8f Revert "Remove redundant "std::move"s in return statements"
The build failed with

  error: call to deleted constructor of 'llvm::Error'

errors.

This reverts commit 1c2241a7936bf85aa68aef94bd40c3ba77d8ddf2.
2020-02-10 07:07:40 -08:00
Bill Wendling
e45b5f33f3 Remove redundant "std::move"s in return statements 2020-02-10 06:39:44 -08:00
Sylvestre Ledru
5c78d195eb Make StringRef's std::string conversion operator explicit
The build is currenly broken when perf or ffi are enabled for llvm

Just like in https://reviews.llvm.org/rG777180a32b61070a10dd330b4f038bf24e916af1
2020-02-01 15:43:45 +01:00
Benjamin Kramer
76555832b5 Another round of GCC5 fixes. 2020-01-29 02:09:24 +01:00
Benjamin Kramer
87d13166c7 Make llvm::StringRef to std::string conversions explicit.
This is how it should've been and brings it more in line with
std::string_view. There should be no functional change here.

This is mostly mechanical from a custom clang-tidy check, with a lot of
manual fixups. It uncovers a lot of minor inefficiencies.

This doesn't actually modify StringRef yet, I'll do that in a follow-up.
2020-01-28 23:25:25 +01:00
Guillaume Chatelet
af9e09671c [Alignment][NFC] Deprecate Align::None()
Summary:
This is a follow up on https://reviews.llvm.org/D71473#inline-647262.
There's a caveat here that `Align(1)` relies on the compiler understanding of `Log2_64` implementation to produce good code. One could use `Align()` as a replacement but I believe it is less clear that the alignment is one in that case.

Reviewers: xbolva00, courbet, bollu

Subscribers: arsenm, dylanmckay, sdardis, nemanjai, jvesely, nhaehnle, hiraditya, kbarton, jrtc27, atanasyan, jsji, Jim, kerbowa, cfe-commits, llvm-commits

Tags: #clang, #llvm

Differential Revision: https://reviews.llvm.org/D73099
2020-01-24 12:53:58 +01:00
Lang Hames
113c4918a7 [ORC] Fix a missing move in ce2207abaf9.
This should fix the build failure at
http://lab.llvm.org:8011/builders/clang-cmake-x86_64-sde-avx512-linux/builds/32524
and others.
2020-01-21 20:14:50 -08:00
Lang Hames
ac6d037b49 [ORC] Add support for emulated TLS to ORCv2.
This commit adds a ManglingOptions struct to IRMaterializationUnit, and replaces
IRCompileLayer::CompileFunction with a new IRCompileLayer::IRCompiler class. The
ManglingOptions struct defines the emulated-TLS state (via a bool member,
EmulatedTLS, which is true if emulated-TLS is enabled and false otherwise). The
IRCompileLayer::IRCompiler class wraps an IRCompiler (the same way that the
CompileFunction typedef used to), but adds a method to return the
IRCompileLayer::ManglingOptions that the compiler will use.

These changes allow us to correctly determine the symbols that will be produced
when a thread local global variable defined at the IR level is compiled with or
without emulated TLS. This is required for ORCv2, where MaterializationUnits
must declare their interface up-front.

Most ORCv2 clients should not require any changes. Clients writing custom IR
compilers will need to wrap their compiler in an IRCompileLayer::IRCompiler,
rather than an IRCompileLayer::CompileFunction, however this should be a
straightforward change (see modifications to CompileUtils.* in this patch for an
example).
2020-01-21 19:55:33 -08:00
Lang Hames
92390e491c [ORC] Add weak symbol support to defineMaterializing, fix for PR40074.
The MaterializationResponsibility::defineMaterializing method allows clients to
add new definitions that are in the process of being materialized to the JIT.
This patch adds support to defineMaterializing for symbols with weak linkage
where the new definitions may be rejected if another materializer concurrently
defines the same symbol. If a weak symbol is rejected it will not be added to
the MaterializationResponsibility's responsibility set. Clients can check for
membership in the responsibility set via the
MaterializationResponsibility::getSymbols() method before resolving any
such weak symbols.

This patch also adds code to RTDyldObjectLinkingLayer to tag COFF comdat symbols
introduced during codegen as weak, on the assumption that these are COFF comdat
constants. This fixes http://llvm.org/PR40074.
2020-01-19 10:46:07 -08:00
Lang Hames
afe0b073a6 [ORC] Set setCloneToNewContextOnEmit on LLJIT's transform layer when needed.
Based on Don Hinton's patch in https://reviews.llvm.org/D72406. This feature
was accidentally left out of e9e26c01cd865da678b1af6ba5f417c713956a66, and
would have pessimized concurrent compilation in the default case.

Thanks for spotting this Don!
2020-01-15 10:22:57 -08:00
Lang Hames
7f70888b46 [ORC] Simplify use of lazyReexports with LLJIT.
This patch makes the target triple available via the LLJIT interface, and moves
the IRTransformLayer from LLLazyJIT down into LLJIT. Together these changes make
it easier to use the lazyReexports utility with LLJIT, and to apply IR
transforms to code as it is compiled in LLJIT (rather than requiring transforms
to be applied manually before code is added). An code example is added in
llvm/examples/LLJITExamples/LLJITWithLazyReexports
2020-01-15 08:02:53 -08:00
Lang Hames
bbe6d35d70 [ORC] Update lazyReexports to support aliases with different symbol names.
A bug in the existing implementation meant that lazyReexports would not work if
the aliased name differed from the alias's name, i.e. all lazy reexports had to
be of the form (lib1, name) -> (lib2, name). This patch fixes the issue by
capturing the alias's name in the NotifyResolved callback. To simplify this
capture, and the LazyCallThroughManager code in general, the NotifyResolved
callback is updated to use llvm::unique_function rather than a custom class.

No test case yet: This can only be tested at runtime, and the only in-tree
client (lli) always uses aliases with matching names. I will add a new LLJIT
example shortly that will directly test the lazyReexports API and the
non-trivial alias use case.
2020-01-15 08:02:53 -08:00
Fangrui Song
3a9f350cbb [Disassembler] Delete the VStream parameter of MCDisassembler::getInstruction()
The argument is llvm::null() everywhere except llvm::errs() in
llvm-objdump in -DLLVM_ENABLE_ASSERTIONS=On builds. It is used by no
target but X86 in -DLLVM_ENABLE_ASSERTIONS=On builds.

If we ever have the needs to add verbose log to disassemblers, we can
record log with a member function, instead of passing it around as an
argument.
2020-01-11 13:34:52 -08:00
Lang Hames
6d930a5412 [ORC] Fix argv handling in runAsMain / lli.
This fixes an off-by-one error in the argc value computed by runAsMain, and
switches lli back to using the input bitcode (rather than the string "lli") as
the effective program name.

Thanks to Stefan Graenitz for spotting the bug.
2020-01-11 13:03:38 -08:00
Lang Hames
92479bab85 [ExecutionEngine] Re-enable FastISel for non-iOS arm targets.
Patch by Nicolas Capens. Thanks Nicolas!

https://reviews.llvm.org/D65015
2020-01-11 10:49:59 -08:00
Stefan Gränitz
746232dc0c [NFC][ORC] Fix typos and whitespaces in comments 2020-01-03 21:54:03 +01:00
Mark de Wever
be4b8874f7 [NFC] Fixes -Wrange-loop-analysis warnings
This avoids new warnings due to D68912 adds -Wrange-loop-analysis to -Wall.

Differential Revision: https://reviews.llvm.org/D71857
2020-01-01 20:01:37 +01:00
Fangrui Song
23ebb038ec [MCJIT] Migrate function attribute "no-frame-pointer-elim" to "frame-pointer" 2019-12-24 17:12:21 -08:00
Lang Hames
24ee3b266f [ORC] De-register eh-frames in the RTDyldObjectLinkingLayer destructor.
This matches the behavior of the legacy layer, which automatically deregistered
frames.
2019-12-20 21:10:49 -08:00
Lang Hames
80fb117833 [Orc][LLJIT] Re-apply 298e183e813 (use JITLink for LLJIT where supported).
Patch d9220b580b3 fixed the underlying issue that casued 298e183e813 to fail.
2019-12-19 20:42:26 -08:00
Lang Hames
f1bb810112 [JITLink][MachO] Fix common symbol size plumbing.
This fixes the underlying bug that was exposed by 298e183e813.
2019-12-19 20:41:59 -08:00
Lang Hames
cfdc44f541 Revert "[Orc][LLJIT] Use JITLink even if a custom JITTargetMachineBuilder is supplied."
This reverts commit 298e183e813c884dd22816383405bae3ef9ef278.

This commit caused some build failures -- reverting while I investigate.
2019-12-18 15:13:35 -08:00
Lang Hames
e72d1e9ed8 [Orc][LLJIT] Use JITLink even if a custom JITTargetMachineBuilder is supplied.
LLJITBuilder will now use JITLink on supported platforms even if a custom
JITTargetMachineBuilder is supplied, provided that neither the code model,
nor the relocation model, nor the ObjectLinkingLayerCreator is set.
2019-12-18 14:17:25 -08:00
Lang Hames
d8537b7cc4 [Orc][LLJIT] Automatically use JITLink for LLJIT on supported platforms.
JITLink (which underlies ObjectLinkingLayer) is a replacement for RuntimeDyld.
It supports the native code model, and linker plugins that enable a wider range
of features than RuntimeDyld.

Currently only enabled for MachO/x86-64 and MachO/arm64. New architectures will
be added as JITLink support for them is developed.
2019-12-15 21:57:10 -08:00
Lang Hames
9b94fee202 [ORC] Make ObjectLinkingLayer own its jitlink::MemoryManager.
This relieves ObjectLinkingLayer clients of the responsibility of holding the
memory manager. This makes it easier to select between RTDyldObjectLinkingLayer
(which already owned its memory manager factory) and ObjectLinkingLayer at
runtime as clients aren't required to hold a jitlink::MemoryManager field just
in case ObjectLinkingLayer is selected.
2019-12-15 17:35:52 -08:00
Lang Hames
8c3d4519e1 [ORC] Remove the automagic Main JITDylib fram ExecutionSession.
This patch removes the magic "main" JITDylib from ExecutionEngine. The main
JITDylib was created automatically at ExecutionSession construction time, and
all subsequently created JITDylibs were added to the main JITDylib's
links-against list by default. This saves a couple of lines of boilerplate for
simple JIT setups, but this isn't worth introducing magical behavior for.

ORCv2 clients should now construct their own main JITDylib using
ExecutionSession::createJITDylib and set up its linkages manually using
JITDylib::setSearchOrder (or related methods in JITDylib).
2019-12-05 01:36:49 -08:00
Lang Hames
2134d2b597 [ORC] Add a runAsMain utility function to ExecutionUtils.
The runAsMain function takes a pointer to a function with a standard C main
signature, int(*)(int, char*[]), and invokes it using the given arguments and
program name. The arguments are copied into writable temporary storage as
required by the C and C++ specifications, so runAsMain safe to use when calling
main functions that modify their arguments in-place.

This patch also uses the new runAsMain function to replace hand-rolled versions
in lli, llvm-jitlink, and the SpeculativeJIT example.
2019-12-02 01:52:52 -08:00
Lang Hames
436a4a17bb [Orc] Add setters for target options and features to JITTargetMachineBuilder.
Also remove redundant feature initialization steps from the detectHost method.
2019-12-02 01:52:51 -08:00
Lang Hames
ded5c52882 [ORC][JITLink] Add support for weak references, and improve handling of static
libraries.

This patch substantially updates ORCv2's lookup API in order to support weak
references, and to better support static archives. Key changes:

-- Each symbol being looked for is now associated with a SymbolLookupFlags
   value. If the associated value is SymbolLookupFlags::RequiredSymbol then
   the symbol must be defined in one of the JITDylibs being searched (or be
   able to be generated in one of these JITDylibs via an attached definition
   generator) or the lookup will fail with an error. If the associated value is
   SymbolLookupFlags::WeaklyReferencedSymbol then the symbol is permitted to be
   undefined, in which case it will simply not appear in the resulting
   SymbolMap if the rest of the lookup succeeds.

   Since lookup now requires these flags for each symbol, the lookup method now
   takes an instance of a new SymbolLookupSet type rather than a SymbolNameSet.
   SymbolLookupSet is a vector-backed set of (name, flags) pairs. Clients are
   responsible for ensuring that the set property (i.e. unique elements) holds,
   though this is usually simple and SymbolLookupSet provides convenience
   methods to support this.

-- Lookups now have an associated LookupKind value, which is either
   LookupKind::Static or LookupKind::DLSym. Definition generators can inspect
   the lookup kind when determining whether or not to generate new definitions.
   The StaticLibraryDefinitionGenerator is updated to only pull in new objects
   from the archive if the lookup kind is Static. This allows lookup to be
   re-used to emulate dlsym for JIT'd symbols without pulling in new objects
   from archives (which would not happen in a normal dlsym call).

-- JITLink is updated to allow externals to be assigned weak linkage, and
   weak externals now use the SymbolLookupFlags::WeaklyReferencedSymbol value
   for lookups. Unresolved weak references will be assigned the default value of
   zero.

Since this patch was modifying the lookup API anyway, it alo replaces all of the
"MatchNonExported" boolean arguments with a "JITDylibLookupFlags" enum for
readability. If a JITDylib's associated value is
JITDylibLookupFlags::MatchExportedSymbolsOnly then the lookup will only
match against exported (non-hidden) symbols in that JITDylib. If a JITDylib's
associated value is JITDylibLookupFlags::MatchAllSymbols then the lookup will
match against any symbol defined in the JITDylib.
2019-11-28 13:30:49 -08:00
Lang Hames
0a4ed7d874 [JITLink] Make sure MachO/x86-64 handles 32-bit signed addends correctly.
These need to be sign extended when loading into Edge addends.
2019-11-27 22:46:07 -08:00
Tom Stellard
28bf7f3536 [cmake] Explicitly mark libraries defined in lib/ as "Component Libraries"
Summary:
Most libraries are defined in the lib/ directory but there are also a
few libraries defined in tools/ e.g. libLLVM, libLTO.  I'm defining
"Component Libraries" as libraries defined in lib/ that may be included in
libLLVM.so.  Explicitly marking the libraries in lib/ as component
libraries allows us to remove some fragile checks that attempt to
differentiate between lib/ libraries and tools/ libraires:

1. In tools/llvm-shlib, because
llvm_map_components_to_libnames(LIB_NAMES "all") returned a list of
all libraries defined in the whole project, there was custom code
needed to filter out libraries defined in tools/, none of which should
be included in libLLVM.so.  This code assumed that any library
defined as static was from lib/ and everything else should be
excluded.

With this change, llvm_map_components_to_libnames(LIB_NAMES, "all")
only returns libraries that have been added to the LLVM_COMPONENT_LIBS
global cmake property, so this custom filtering logic can be removed.
Doing this also fixes the build with BUILD_SHARED_LIBS=ON
and LLVM_BUILD_LLVM_DYLIB=ON.

2. There was some code in llvm_add_library that assumed that
libraries defined in lib/ would not have LLVM_LINK_COMPONENTS or
ARG_LINK_COMPONENTS set.  This is only true because libraries
defined lib lib/ use LLVMBuild.txt and don't set these values.
This code has been fixed now to check if the library has been
explicitly marked as a component library, which should now make it
easier to remove LLVMBuild at some point in the future.

I have tested this patch on Windows, MacOS and Linux with release builds
and the following combinations of CMake options:

- "" (No options)
- -DLLVM_BUILD_LLVM_DYLIB=ON
- -DLLVM_LINK_LLVM_DYLIB=ON
- -DBUILD_SHARED_LIBS=ON
- -DBUILD_SHARED_LIBS=ON -DLLVM_BUILD_LLVM_DYLIB=ON
- -DBUILD_SHARED_LIBS=ON -DLLVM_LINK_LLVM_DYLIB=ON

Reviewers: beanz, smeenai, compnerd, phosek

Reviewed By: beanz

Subscribers: wuzish, jholewinski, arsenm, dschuff, jyknight, dylanmckay, sdardis, nemanjai, jvesely, nhaehnle, mgorny, mehdi_amini, sbc100, jgravelle-google, hiraditya, aheejin, fedor.sergeev, asb, rbar, johnrusso, simoncook, apazos, sabuasal, niosHD, jrtc27, MaskRay, zzheng, edward-jones, atanasyan, steven_wu, rogfer01, MartinMosbeck, brucehoult, the_o, dexonsmith, PkmX, jocewei, jsji, dang, Jim, lenary, s.egerton, pzheng, sameer.abuasal, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D70179
2019-11-21 10:48:08 -08:00
Lang Hames
d8fb36540a [Orc][Modules] Fix Modules build fallout from a34680a33eb.
In a34680a33eb OrcError.h and Orc/RPC/*.h were split out from the rest of
ExecutionEngine in order to eliminate false dependencies for remote JIT
targets (see https://reviews.llvm.org/D68732), however this broke modules
builds (see https://reviews.llvm.org/D69817).

This patch splits these headers out into a separate module, LLVM_OrcSupport,
in order to fix the modules build.

Fixes <rdar://56377508>.
2019-11-20 17:34:34 -08:00
Martin Storsjö
eb8f896e0e [ExecutionEngine] Add a missing break to avoid warnings
This fixes buildbot errors since dc3ee330891c2.
2019-11-20 12:20:05 +02:00
Adam Kallai
b8db2c32c1 ExecutionEngine: add preliminary support for COFF ARM64
Differential Revision: https://reviews.llvm.org/D69434
2019-11-20 10:59:42 +02:00
Sylvestre Ledru
1864c4422c Fix a build failure with perf: Add a missing include to llvm/Support/ManagedStatic.h
It was failing with
PerfJITEventListener.cpp:489:7: error: 'ManagedStatic' in namespace 'llvm' does not name a template type
 llvm::ManagedStatic<PerfJITEventListener> PerfListener;
2019-11-16 14:43:46 +01:00
Hans Wennborg
4beb961a84 Fix GCC -Wcast-qual warnings 2019-11-15 09:49:06 +01:00
Hans Wennborg
ac9f8ddb0e GCC 5.3 build fix
It was failing with

  llvm/lib/ExecutionEngine/Orc/DebugUtils.cpp:56:10:
  error: could not convert ‘Obj’ from ‘std::unique_ptr<llvm::MemoryBuffer>’
  to ‘llvm::Expected<std::unique_ptr<llvm::MemoryBuffer> >’
     return Obj;
            ^
2019-11-15 09:49:06 +01:00
Lang Hames
7336034e4d [ORC] Add a utility to support dumping JIT'd objects to disk for debugging.
Adds a DumpObjects utility that can be used to dump JIT'd objects to disk.
Instances of DebugObjects may be used by ObjectTransformLayer as no-op
transforms.

This patch also adds an ObjectTransformLayer to LLJIT and an example of how
to use this utility to dump JIT'd objects in LLJIT.
2019-11-14 21:27:19 -08:00
Lang Hames
023dd287ea [JITLink] Refactor EH-frame handling to support eh-frames with existing relocs.
Some targets (E.g. MachO/arm64) use relocations to fix some CFI record fields
in the eh-frame section. When relocations are used the initial (pre-relocation)
content of the eh-frame section can no longer be interpreted by following the
eh-frame specification. This causes errors in the existing eh-frame parser.

This patch moves eh-frame handling into two LinkGraph passes that are run after
relocations have been parsed (but before they are applied). The first] pass
breaks up blocks in the eh-frame section into per-CFI-record blocks, and the
second parses blocks of (potentially multiple) CFI records and adds the
appropriate edges to any CFI fields that do not have existing relocations.
These passes can be run independently of one another. By handling eh-frame
splitting/fixing with LinkGraph passes we can both re-use existing relocations
for CFI record fields and avoid applying eh-frame fixups before parsing the
section (which would complicate the linker and require extra temporary
allocations of working memory).
2019-11-06 14:30:26 -08:00
Alexandre Ganea
0fe15c92e6 [Orc] Fix iterator usage after remove
Differential Revision: https://reviews.llvm.org/D69805
2019-11-06 17:17:27 -05:00
Lang Hames
0998dbd50b [JITLink] Move block ownership from LinkGraph to Section.
This enables easy iteration over blocks in a specific section.
2019-10-30 17:57:03 -07:00
Lang Hames
b24faad0cf [JITLink] Add a utility for splitting blocks at a given index.
LinkGraph::splitBlock will split a block at a given index, returning a new
block covering the range [ 0, index ) and modifying the original block to
cover the range [ index, original-block-size ). Block addresses, content,
edges and symbols will be updated as necessary. This utility will be used
in upcoming improvements to JITLink's eh-frame support.
2019-10-30 12:35:49 -07:00
Chris Bieneman
9b89694766 Break out OrcError and RPC
Summary:
When createing an ORC remote JIT target the current library split forces the target process to link large portions of LLVM (Core, Execution Engine, JITLink, Object, MC, Passes, RuntimeDyld, Support, Target, and TransformUtils). This occurs because the ORC RPC interfaces rely on the static globals the ORC Error types require, which starts a cycle of pulling in more and more.

This patch breaks the ORC RPC Error implementations out into an "OrcError" library which only depends on LLVM Support. It also pulls the ORC RPC headers into their own subdirectory.

With this patch code can include the Orc/RPC/*.h headers and will only incur link dependencies on LLVMOrcError and LLVMSupport.

Reviewers: lhames

Reviewed By: lhames

Subscribers: mgorny, hiraditya, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D68732
2019-10-29 17:31:28 -07:00
Lang Hames
e6065669d0 [JITLink] Tighten section sorting criteria to fix a flaky test case.
Sections may have zero size and zero-sized sections may share a start address
with other zero-sized sections. For the section overlap test to function
correctly zero-sized sections must be ordered before any non-zero sized ones.

This should fix the intermittent failures in the
test/ExecutionEngine/JITLink/X86/MachO_zero_fill_alignment.s test case that
have been observed on some builders.
2019-10-28 22:56:13 -07:00
George Rimar
9459104c4d [llvm/Object] - Make ELFObjectFile::getRelocatedSection return Expected<section_iterator>
It returns just a section_iterator currently and have a report_fatal_error call inside.
This change adds a way to return errors and handle them on caller sides.

The patch also changes/improves current users and adds test cases.

Differential revision: https://reviews.llvm.org/D69167

llvm-svn: 375408
2019-10-21 11:06:38 +00:00
Reid Kleckner
bdc1c0106b Move endian constant from Host.h to SwapByteOrder.h, prune include
Works on this dependency chain:
  ArrayRef.h ->
  Hashing.h -> --CUT--
  Host.h ->
  StringMap.h / StringRef.h

ArrayRef is very popular, but Host.h is rarely needed. Move the
IsBigEndianHost constant to SwapByteOrder.h. Clients of that header are
more likely to need it.

llvm-svn: 375316
2019-10-19 00:48:11 +00:00
Lang Hames
7419cc0b85 [Orc] Add a method for ObjectLinkingLayer to return ownership of object buffers.
RTDyldObjectLinkingLayer allowed clients to register a NotifyEmitted function to
reclaim ownership of object buffers once they had been linked. This patch adds
similar functionality to ObjectLinkingLayer: Clients can now optionally call the
ObjectLinkingLayer::setReturnObjectBuffer method to register a function that
will be called when discarding object buffers. If set, this function will be
called to return ownership of the object regardless of whether the link
succeeded or failed.

Use cases for this function include debug dumping (it provides a way to dump
all objects linked into JIT'd code) and object re-use (e.g. storing an
object in a cache).

llvm-svn: 374951
2019-10-15 21:41:12 +00:00
Lang Hames
47191b1421 [JITLink] Switch to slab allocation for InProcessMemoryManager, re-enable test.
InProcessMemoryManager used to make separate memory allocation calls for each
permission level (RW, RX, RO), which could lead to target-out-of-range errors
if data and code were placed too far apart (this was the source of failures in
the JITLink/AArch64 testcase when it was first landed).

This patch updates InProcessMemoryManager to allocate a single slab which is
subdivided between text and data. This should guarantee that accesses remain
in-range provided that individual object files do not exceed 1Mb in size.
This patch also re-enables the JITLink/AArch64 testcase.

llvm-svn: 374948
2019-10-15 21:06:57 +00:00
Guillaume Chatelet
89f87ca322 [Alignment][NFC] Remove dependency on GlobalObject::setAlignment(unsigned)
Summary:
This is patch is part of a series to introduce an Alignment type.
See this thread for context: http://lists.llvm.org/pipermail/llvm-dev/2019-July/133851.html
See this patch for the introduction of the type: https://reviews.llvm.org/D64790

Reviewers: courbet

Subscribers: arsenm, mehdi_amini, jvesely, nhaehnle, hiraditya, steven_wu, dexonsmith, dang, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D68944

llvm-svn: 374880
2019-10-15 11:24:36 +00:00
Lang Hames
526df5edca [JITLink] Fix MachO/arm64 GOTPAGEOFF encoding.
The original implementation failed to shift the immediate down.

This should fix some of the bot failures due to r374476.

llvm-svn: 374499
2019-10-11 01:50:31 +00:00
Michael Liao
31229d098c Fix compilation warning due to typo.
llvm-svn: 374479
2019-10-10 23:48:56 +00:00
Lang Hames
3a95e22742 [JITLink] Add an initial implementation of JITLink for MachO/AArch64.
This implementation has support for all relocation types except TLV.

Compact unwind sections are not yet supported, so exceptions/unwinding will not
work.

llvm-svn: 374476
2019-10-10 23:37:51 +00:00
Jordan Rose
f093084da4 Second attempt to add iterator_range::empty()
Doing this makes MSVC complain that `empty(someRange)` could refer to
either C++17's std::empty or LLVM's llvm::empty, which previously we
avoided via SFINAE because std::empty is defined in terms of an empty
member rather than begin and end. So, switch callers over to the new
method as it is added.

https://reviews.llvm.org/D68439

llvm-svn: 373935
2019-10-07 18:14:24 +00:00
Martin Storsjo
6a46a29b8d [JITLink] Silence GCC warnings. NFC.
Use parentheses in an expression with mixed && and ||.

Differential Revision: https://reviews.llvm.org/D68447

llvm-svn: 373779
2019-10-04 19:47:42 +00:00
Simon Pilgrim
bae3718e6a Fix MSVC "not all control paths return a value" warning. NFCI.
llvm-svn: 373730
2019-10-04 11:24:51 +00:00
Simon Pilgrim
08c734c3f8 Fix MSVC "result of 32-bit shift implicitly converted to 64 bits" warning. NFCI.
llvm-svn: 373729
2019-10-04 11:24:35 +00:00
Lang Hames
2275aa86fb [JITLink] Explicitly destroy bumpptr-allocated blocks to avoid a memory leak.
llvm-svn: 373693
2019-10-04 05:24:40 +00:00
Lang Hames
cd8cf163ae [JITLink] Fix an unused variable warning.
llvm-svn: 373692
2019-10-04 05:24:39 +00:00
Lang Hames
595027e9c3 [JITLink] Switch from an atom-based model to a "blocks and symbols" model.
In the Atom model the symbols, content and relocations of a relocatable object
file are represented as a graph of atoms, where each Atom represents a
contiguous block of content with a single name (or no name at all if the
content is anonymous), and where edges between Atoms represent relocations.
If more than one symbol is associated with a contiguous block of content then
the content is broken into multiple atoms and layout constraints (represented by
edges) are introduced to ensure that the content remains effectively contiguous.
These layout constraints must be kept in mind when examining the content
associated with a symbol (it may be spread over multiple atoms) or when applying
certain relocation types (e.g. MachO subtractors).

This patch replaces the Atom model in JITLink with a blocks-and-symbols model.
The blocks-and-symbols model represents relocatable object files as bipartite
graphs, with one set of nodes representing contiguous content (Blocks) and
another representing named or anonymous locations (Symbols) within a Block.
Relocations are represented as edges from Blocks to Symbols. This scheme
removes layout constraints (simplifying handling of MachO alt-entry symbols,
and hopefully ELF sections at some point in the future) and simplifies some
relocation logic.

llvm-svn: 373689
2019-10-04 03:55:26 +00:00
Guillaume Chatelet
114e854bc6 [Alignment][NFC] Remove unneeded llvm:: scoping on Align types
llvm-svn: 373081
2019-09-27 12:54:21 +00:00
Simon Pilgrim
1e973c9493 [Orc] Silence static analyzer dyn_cast<ConstantInt> null dereference warning. NFCI.
llvm-svn: 372746
2019-09-24 12:43:55 +00:00
Simon Pilgrim
68869c364d [ExecutionEngine] Don't dereference a dyn_cast result. NFCI.
The static analyzer is warning about potential null dereferences of dyn_cast<> results - in these cases we can safely use cast<> directly as we know that these cases should all be the correct type, which is why its working atm and anyway cast<> will assert if they aren't.

llvm-svn: 371998
2019-09-16 15:19:11 +00:00
Sanjoy Das
0f3a1a9518 Add dependency from Orc to Passes
Summary: Orc uses registerFunctionAnalyses that's defined in Passes.

Reviewers: dblaikie

Subscribers: mcrosier, bixia, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D67477

llvm-svn: 371898
2019-09-13 21:07:56 +00:00
Benjamin Kramer
99cfb3923c [Orc] Roll back ThreadPool to std::function
MSVC doesn't allow move-only types in std::packaged_task. Boo.

llvm-svn: 371844
2019-09-13 11:59:51 +00:00
Benjamin Kramer
d97df4c6c8 [Orc] Address the remaining move-capture FIXMEs
This required spreading unique_function a bit more, which I think is a
good thing.

llvm-svn: 371843
2019-09-13 11:35:33 +00:00
Guillaume Chatelet
961213111f [Alignment] Move OffsetToAlignment to Alignment.h
Summary:
This is patch is part of a series to introduce an Alignment type.
See this thread for context: http://lists.llvm.org/pipermail/llvm-dev/2019-July/133851.html
See this patch for the introduction of the type: https://reviews.llvm.org/D64790

Reviewers: courbet, JDevlieghere, alexshap, rupprecht, jhenderson

Subscribers: sdardis, nemanjai, hiraditya, kbarton, jakehehrlich, jrtc27, MaskRay, atanasyan, jsji, seiya, cfe-commits, llvm-commits

Tags: #clang, #llvm

Differential Revision: https://reviews.llvm.org/D67499

llvm-svn: 371742
2019-09-12 15:20:36 +00:00
Tim Northover
1bb14916f2 AArch64: support arm64_32, an ILP32 slice for watchOS.
This is the main CodeGen patch to support the arm64_32 watchOS ABI in LLVM.
FastISel is mostly disabled for now since it would generate incorrect code for
ILP32.

llvm-svn: 371722
2019-09-12 10:22:23 +00:00
Praveen Velliengiri
33c62d6ddc [ORCv2] - New Speculate Query Implementation
Summary:
This patch introduces, SequenceBBQuery - new heuristic to find likely next callable functions it tries to find the blocks with calls in order of execution sequence of Blocks.

It still uses BlockFrequencyAnalysis to find high frequency blocks. For a handful of hottest blocks (plan to customize), the algorithm traverse and discovered the caller blocks along the way to Entry Basic Block and Exit Basic Block. It uses Block Hint, to stop traversing the already visited blocks in both direction. It implicitly assumes that once the block is visited during discovering entry or exit nodes, revisiting them again does not add much. It also branch probability info (cached result) to traverse only hot edges (planned to customize) from hot blocks. Without BPI, the algorithm mostly return's all the blocks in the CFG with calls.

It also changes the heuristic queries, so they don't maintain states. Hence it is safe to call from multiple threads.

It also implements, new instrumentation to avoid jumping into JIT on every call to the function with the help _orc_speculate.decision.block and _orc_speculate.block.

"Speculator Registration Mechanism is also changed" - kudos to @lhames

Open to review, mostly looking to change implementation of SequeceBBQuery heuristics with good data structure choices.

Reviewers: lhames, dblaikie

Reviewed By: lhames

Subscribers: mgorny, hiraditya, mgrang, llvm-commits, lhames

Tags: #speculative_compilation_in_orc, #llvm

Differential Revision: https://reviews.llvm.org/D66399

llvm-svn: 370092
2019-08-27 18:23:36 +00:00
Lang Hames
a74aa5a5a0 [JITLink][ORC] Track eh-frame section size for registration/deregistration.
On MachO, processing of the eh-frame section should stop if the end of the
__eh_frame section is reached, regardless of whether or not there is a null CFI
length field at the end of the section. This patch tracks the eh-frame section
size and threads it through the appropriate APIs so that processing can be
terminated correctly.

No testcase yet: This patch is all API plumbing (rather than modification of
linked memory) which the existing infrastructure does not provide a way of
testing. Committing without a testcase until I have an idea of how to write
one.

llvm-svn: 370074
2019-08-27 15:50:32 +00:00
Lang Hames
20a640eda8 [JITLink] Don't under-align zero-fill sections.
If content sections have lower alignment than zero-fill sections then bump the
overall segment alignment to avoid under-aligning the zero-fill sections.

llvm-svn: 370072
2019-08-27 15:22:23 +00:00
Lang Hames
3d87145b48 [ORC] Make sure that queries on emitted-but-not-ready symbols fail correctly.
In r369808 the failure scheme for ORC symbols was changed to make
MaterializationResponsibility objects responsible for failing the symbols
they represented. This simplifies error logic in the case where symbols are
still covered by a MaterializationResponsibility, but left a gap in error
handling: Symbols that have been emitted but are not yet ready (due to a
dependence on some unemitted symbol) are not covered by a
MaterializationResponsibility object. Under the scheme introduced in r369808
such symbols would be moved to the error state, but queries on those symbols
were never notified. This led to deadlocks when such symbols were failed.

This commit updates error logic to immediately fail queries on any symbol that
has already been emitted if one of its dependencies fails.

llvm-svn: 369976
2019-08-26 21:42:51 +00:00
Lang Hames
f2f188d997 [ORC] Fix an overly aggressive assert.
Symbols that have not been queried will not have MaterializingInfo entries,
so remove the assert that all failed symbols should have these entries.
Also updates the loop to only remove entries that were found earlier.

llvm-svn: 369975
2019-08-26 21:42:47 +00:00
Lang Hames
4a793e369c [ORC] Remove query dependencies when symbols are resolved.
If the dependencies are not removed then a late failure (one symbol covered by
the query failing after others have already been resolved) can result in an
attempt to detach the query from already finalized symbol, resulting in an
assert/crash. This patch fixes the issue by removing query dependencies in
JITDylib::resolve for symbols that meet the required state.

llvm-svn: 369809
2019-08-23 20:37:32 +00:00
Lang Hames
8902cdbc44 [ORC] Fix a FIXME: Propagate errors to dependencies.
When symbols are failed (via MaterializationResponsibility::failMaterialization)
any symbols depending on them will now be moved to an error state. Attempting
to resolve or emit a symbol in the error state (via the notifyResolved or
notifyEmitted methods on MaterializationResponsibility) will result in an error.
If notifyResolved or notifyEmitted return an error due to failure of a
dependence then the caller should log or discard the error and call
failMaterialization to propagate the failure to any queries waiting on the
symbols being resolved/emitted (plus their dependencies).

llvm-svn: 369808
2019-08-23 20:37:31 +00:00
Hubert Tong
f12628ef2a [cmake] Link in LLVMPasses due to dependency by LLVMOrcJIT; NFC
Summary:
rL367756 (f5c40cb) increases the dependency of LLVMOrcJIT on LLVMPasses.
In particular, symbols defined in LLVMPasses that are referenced by the
destructor of `PassBuilder` are now referenced by LLVMOrcJIT through
`Speculation.cpp.o`.

We believe that referencing symbols defined in LLVMPasses in the
destructor of `PassBuilder` is valid, and that adding to the set of such
symbols is legitimate. To support such cases, this patch adds LLVMPasses
to the set of libraries being linked when linking in LLVMOrcJIT causes
such symbols from LLVMPasses to be referenced.

Reviewers: Whitney, anhtuyen, pree-jackie

Reviewed By: pree-jackie

Subscribers: mgorny, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D66441

llvm-svn: 369310
2019-08-19 23:12:48 +00:00
Matthias Gehre
e16b3dbe3a [ORC] fix use-after-free detected by -Wreturn-stack-address
Summary:
llvm/lib/ExecutionEngine/Orc/Layer.cpp:53:12: warning: returning address of local temporary object [-Wreturn-stack-address]

In
```
StringRef IRMaterializationUnit::getName() const {
[...]
     return TSM.withModuleDo(
        [](const Module &M) { return M.getModuleIdentifier(); });
```
`getModuleIdentifier()` returns a `const std::string &`, but the implicit return type
of the lambda is `std::string` by value, and thus the returned `StringRef` refers
to a temporary `std::string`.

Detect by annotating `llvm::StringRef` with `[[gsl::Pointer]]`.

Reviewers: lhames, sgraenitz

Subscribers: hiraditya, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D66440

llvm-svn: 369306
2019-08-19 21:59:44 +00:00
Lang Hames
97a41256df [ORC] Remove some stray debugging output accidentally left in r368707
llvm-svn: 369141
2019-08-16 19:33:37 +00:00
Jonas Devlieghere
2c693415b7 [llvm] Migrate llvm::make_unique to std::make_unique
Now that we've moved to C++14, we no longer need the llvm::make_unique
implementation from STLExtras.h. This patch is a mechanical replacement
of (hopefully) all the llvm::make_unique instances across the monorepo.

llvm-svn: 369013
2019-08-15 15:54:37 +00:00
George Rimar
21610566c8 Recommit r368812 "[llvm/Object] - Convert SectionRef::getName() to return Expected<>"
Changes: no changes. A fix for the clang code will be landed right on top.

Original commit message:

SectionRef::getName() returns std::error_code now.
Returning Expected<> instead has multiple benefits.

For example, it forces user to check the error returned.
Also Expected<> may keep a valuable string error message,
what is more useful than having a error code.
(Object\invalid.test was updated to show the new messages printed.)

This patch makes a change for all users to switch to Expected<> version.

Note: in a few places the error returned was ignored before my changes.
In such places I left them ignored. My intention was to convert the interface
used, and not to improve and/or the existent users in this patch.
(Though I think this is good idea for a follow-ups to revisit such places
and either remove consumeError calls or comment each of them to clarify why
it is OK to have them).

Differential revision: https://reviews.llvm.org/D66089

llvm-svn: 368826
2019-08-14 11:10:11 +00:00
George Rimar
f64562dc67 Revert r368812 "[llvm/Object] - Convert SectionRef::getName() to return Expected<>"
It broke clang BB: http://lab.llvm.org:8011/builders/clang-x86_64-debian-fast/builds/16455

llvm-svn: 368813
2019-08-14 08:56:55 +00:00
George Rimar
3a9b0e354d [llvm/Object] - Convert SectionRef::getName() to return Expected<>
SectionRef::getName() returns std::error_code now.
Returning Expected<> instead has multiple benefits.

For example, it forces user to check the error returned.
Also Expected<> may keep a valuable string error message,
what is more useful than having a error code.
(Object\invalid.test was updated to show the new messages printed.)

This patch makes a change for all users to switch to Expected<> version.

Note: in a few places the error returned was ignored before my changes.
In such places I left them ignored. My intention was to convert the interface
used, and not to improve and/or the existent users in this patch.
(Though I think this is good idea for a follow-ups to revisit such places
and either remove consumeError calls or comment each of them to clarify why
it is OK to have them).

Differential revision: https://reviews.llvm.org/D66089

llvm-svn: 368812
2019-08-14 08:46:54 +00:00
Lang Hames
44eb111f3c [ORC] Refactor definition-generation, add a generator for static libraries.
This patch replaces the JITDylib::DefinitionGenerator typedef with a class of
the same name, and adds support for attaching a sequence of DefinitionGeneration
objects to a JITDylib.

This patch also adds a new definition generator,
StaticLibraryDefinitionGenerator, that can be used to add symbols fom a static
library to a JITDylib. An object from the static library will be added (via
a supplied ObjectLayer reference) whenever a symbol from that object is
referenced.

To enable testing, lli is updated to add support for the --extra-archive option
when running in -jit-kind=orc-lazy mode.

llvm-svn: 368707
2019-08-13 16:05:18 +00:00
Eric Christopher
540b42743d Move findBBwithCalls to the file it's used in to avoid unused function
warnings.

llvm-svn: 368636
2019-08-13 00:05:01 +00:00
Benjamin Kramer
b3f29d6f74 Replace llvm::MutexGuard/UniqueLock with their standard equivalents
All supported platforms have <mutex> now, so we don't need our own
copies any longer. No functionality change intended.

llvm-svn: 368149
2019-08-07 10:57:25 +00:00
Diego Caballero
cacc610125 Re-land D65760/r367944
Fixed most vexing parse ambiguation.

llvm-svn: 368055
2019-08-06 16:24:17 +00:00
Puyan Lotfi
d4f7bde729 Reverting D65760/r367944 due to buildbot failure.
http://lab.llvm.org:8011/builders/clang-x86_64-debian-fast/builds/15952/steps/build/logs/stdio

JITTargetMachineBuilder.cpp fails to build.

llvm-svn: 367954
2019-08-05 23:47:07 +00:00
Diego Caballero
19cf557cf1 [ORC] Add CPU name and sub-target features to detectHost
This commit adds host CPU name and sub-target features to the
`JITTargetMachineBuilder` created by `JITTargetMachineBuilder::detectHost()`.

Differential Revision: https://reviews.llvm.org/D65760

llvm-svn: 367944
2019-08-05 23:02:12 +00:00
Lang Hames
9e0a23cc50 [ORC] Work around broken GCC/libstdc++ by adding an explicit conversion.
This should fix the bots that have been failing due to r367712.

llvm-svn: 367921
2019-08-05 20:30:35 +00:00
Lang Hames
06b5e41b2a [JITLink] Add support for MachO/x86-64 UNSIGNED relocs with length=2.
MachO/x86-64 UNSIGNED relocs are almost always 64-bit (length=3), but UNSIGNED
relocs of length=2 are allowed if the target resides in the low 32-bits. This
patch adds support for such relocations in JITLink (previously they would have
triggered an unsupported relocation error).

llvm-svn: 367764
2019-08-03 20:17:10 +00:00
Lang Hames
67654ccd88 [JITLink] Fix error message formatting.
llvm-svn: 367763
2019-08-03 20:17:08 +00:00
Praveen Velliengiri
30dd62db8c Speculative Compilation
[ORC] Remove Speculator Variants for Different Program Representations

[ORC] Block Freq Analysis

Speculative Compilation with Naive Block Frequency

Add Applications to OrcSpeculation

ORC v2 with Block Freq Query & Example

Deleted BenchMark Programs

Signed-off-by: preejackie <praveenvelliengiri@gmail.com>

ORCv2 comments resolved

[ORCV2] NFC

ORCv2 NFC

[ORCv2] Speculative compilation - CFGWalkQuery

ORCv2 Adapting IRSpeculationLayer to new locking scheme

llvm-svn: 367756
2019-08-03 14:42:13 +00:00
Lang Hames
cba634369c [ORC] Remove a dead method.
llvm-svn: 367716
2019-08-02 20:09:30 +00:00
Lang Hames
c847808d77 [ORC] Turn on symbol-flags overrides for LLJIT on Windows by default.
libObject does not apply the Exported flag to symbols in COFF object files,
which can lead to assertions when the symbol flags initially derived from
IR added to the JIT clash with the flags seen by the JIT linker. Both
RTDyldObjectLinkingLayer and ObjectLinkingLayer have a workaround for this:
they can be told to override the flags seen by the linker with the flags
attached to the materialization responsibility object that was passed down
to the linker. This patch modifies LLJIT's setup code to enable this override
by default on platforms where COFF is the default object format.

llvm-svn: 367712
2019-08-02 19:43:20 +00:00
Lang Hames
a6587cc70d [ORC] Change the locking scheme for ThreadSafeModule.
ThreadSafeModule/ThreadSafeContext are used to manage lifetimes and locking
for LLVMContexts in ORCv2. Prior to this patch contexts were locked as soon
as an associated Module was emitted (to be compiled and linked), and were not
unlocked until the emit call returned. This could lead to deadlocks if
interdependent modules that shared contexts were compiled on different threads:
when, during emission of the first module, the dependence was discovered the
second module (which would provide the required symbol) could not be emitted as
the thread emitting the first module still held the lock.

This patch eliminates this possibility by moving to a finer-grained locking
scheme. Each client holds the module lock only while they are actively operating
on it. To make this finer grained locking simpler/safer to implement this patch
removes the explicit lock method, 'getContextLock', from ThreadSafeModule and
replaces it with a new method, 'withModuleDo', that implicitly locks the context,
calls a user-supplied function object to operate on the Module, then implicitly
unlocks the context before returning the result.

ThreadSafeModule TSM = getModule(...);
size_t NumFunctions = TSM.withModuleDo(
    [](Module &M) { // <- context locked before entry to lambda.
      return M.size();
    });

Existing ORCv2 layers that operate on ThreadSafeModules are updated to use the
new method.

This method is used to introduce Module locking into each of the existing
layers.

llvm-svn: 367686
2019-08-02 15:21:37 +00:00
Lang Hames
09e51c4e83 [ORC] Suppress an ORCv1 deprecation warning.
llvm-svn: 366485
2019-07-18 19:55:42 +00:00
Lang Hames
92fa8af24d [ORC] Add deprecation warnings to ORCv1 layers and utilities.
Summary:
ORCv1 is deprecated. The current aim is to remove it before the LLVM 10.0
release. This patch adds deprecation attributes to the ORCv1 layers and
utilities to warn clients of the change.

Reviewers: dblaikie, sgraenitz, AlexDenisov

Subscribers: llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D64609

llvm-svn: 366344
2019-07-17 16:40:52 +00:00
Lang Hames
9e5d8e3243 [ORC] Add custom IR compiler configuration to LLJITBuilder to enable obj caches.
LLJITBuilder now has a setCompileFunctionCreator method which can be used to
construct a CompileFunction for the LLJIT instance being created. The motivating
use-case for this is supporting ObjectCaches, which can now be set up at
compile-function construction time. To demonstrate this an example project,
LLJITWithObjectCache, is included.

llvm-svn: 365671
2019-07-10 17:24:24 +00:00
Lang Hames
07ff51c0a6 [JITLink][ORC] Add EHFrameRegistrar interface, use in EHFrameRegistrationPlugin.
Replaces direct calls to eh-frame registration with calls to methods on an
EHFrameRegistrar instance. This allows clients to substitute a registrar that
registers frames in a remote process via IPC/RPC.

llvm-svn: 365098
2019-07-04 00:05:12 +00:00
Erik Pilkington
29c3a3c9ec [C++2a] Add __builtin_bit_cast, used to implement std::bit_cast
This commit adds a new builtin, __builtin_bit_cast(T, v), which performs a
bit_cast from a value v to a type T. This expression can be evaluated at
compile time under specific circumstances.

The compile time evaluation currently doesn't support bit-fields, but I'm
planning on fixing this in a follow up (some of the logic for figuring this out
is in CodeGen). I'm also planning follow-ups for supporting some more esoteric
types that the constexpr evaluator supports, as well as extending
__builtin_memcpy constexpr evaluation to use the same infrastructure.

rdar://44987528

Differential revision: https://reviews.llvm.org/D62825

llvm-svn: 364954
2019-07-02 18:28:13 +00:00
Lang Hames
1644fea7a8 [JITLink] Move JITLinkMemoryManager into its own header.
llvm-svn: 363444
2019-06-14 19:41:21 +00:00
Lang Hames
f88499a668 [ORC] Rename MaterializationResponsibility resolve and emit methods to
notifyResolved/notifyEmitted.

The 'notify' prefix better describes what these methods do: they update the JIT
symbol states and notify any pending queries that the 'resolved' and 'emitted'
states have been reached (rather than actually performing the resolution or
emission themselves). Since new states are going to be introduced in the near
future (to track symbol registration/initialization) it's worth changing the
convention pre-emptively to avoid further confusion.

llvm-svn: 363322
2019-06-13 20:11:23 +00:00
Cameron McInally
f23300211d [ExecutionEngine] Fix rL362941: Add UnaryOperator visitor to the interpreter
Missed break statements. This was D62881.

llvm-svn: 362958
2019-06-10 16:05:25 +00:00
Cameron McInally
e5821b0815 [ExecutionEngine] Add UnaryOperator visitor to the interpreter
This is to support the unary FNeg instruction.

Differential Revision: https://reviews.llvm.org/D62881

llvm-svn: 362941
2019-06-10 14:38:48 +00:00
Lang Hames
6c25d206a9 [ORC] Update symbol lookup to use a single callback with a required symbol state
rather than two callbacks.

The asynchronous lookup API (which the synchronous lookup API wraps for
convenience) used to take two callbacks: OnResolved (called once all requested
symbols had an address assigned) and OnReady to be called once all requested
symbols were safe to access). This patch updates the asynchronous lookup API to
take a single 'OnComplete' callback and a required state (SymbolState) to
determine when the callback should be made. This simplifies the common use case
(where the client is interested in a specific state) and will generalize neatly
as new states are introduced to track runtime initialization of symbols.

Clients who were making use of both callbacks in a single query will now need to
issue two queries (one for SymbolState::Resolved and another for
SymbolState::Ready). Synchronous lookup API clients who were explicitly passing
the WaitOnReady argument will now need neeed to pass a SymbolState instead (for
'WaitOnReady == true' use SymbolState::Ready, for 'WaitOnReady == false' use
SymbolState::Resolved). Synchronous lookup API clients who were using default
arugment values should see no change.

llvm-svn: 362832
2019-06-07 19:33:51 +00:00
Nick Desaulniers
729fdacf8b [RuntimeDyld] fix too-small-bitmask error
Summary:
This was flagged in https://www.viva64.com/en/b/0629/ under "Snippet No.
33".

It seems that this statement is doing the standard bitwise trick for
adjusting a value to have a specific alignment.

The issue is that getStubAlignment() returns an unsigned, while DataSize
is declared a uint64_t. The right hand side of the expression is not
extended to 64b before bitwise negation, resulting in the top half of
the mask being 0s, which is not correct for realignment.

Reviewers: lhames, MaskRay

Reviewed By: MaskRay

Subscribers: RKSimon, MaskRay, hiraditya, llvm-commits, srhines

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D62227

llvm-svn: 362286
2019-06-01 04:51:26 +00:00
Lang Hames
2501b5002b [RuntimeDyld] Update reserveAllocationSpace to account for stub padding.
This should fix the buildbot failures caused by r362139.

llvm-svn: 362151
2019-05-30 20:58:28 +00:00
Lang Hames
b37b37b6f7 [RuntimeDyld] Apply padding and alignment bumps to all sections with stubs, and
increase the MachO/x86-64 stub alignment to 8.

Stub alignment should be guaranteed for any section containing RuntimeDyld
stubs/GOT-entries. To do this we should pad and align all sections containing
stubs, not just code sections.

This commit also bumps the MachO/x86-64 stub alignment to 8, so that GOT entries
will be aligned.

llvm-svn: 362139
2019-05-30 19:59:20 +00:00
Lang Hames
e86e9b45fa [ORC] Track JIT symbol states more explicitly.
Prior to this patch, JITDylibs inferred symbol states (whether a symbol was
newly added, materializing, resolved, or ready to run) via a combination of (1)
bits in the JITSymbolFlags member, and (2) the state of some internal JITDylib
data structures. This patch explicitly tracks symbol states by adding a new
SymbolState member to the symbol table entries, and removing the 'Lazy' and
'Materializing' bits from JITSymbolFlags. This is a first step towards adding
additional states representing initialization phases (e.g. eh-frame registration,
registration with the language runtime, and static initialization).

llvm-svn: 361899
2019-05-28 23:35:44 +00:00
Lang Hames
b21e21ec42 [RuntimeDyld][ARM] Fix an incorrect assertion condition.
Fixes https://llvm.org/PR42036

llvm-svn: 361782
2019-05-27 21:34:31 +00:00
Galina Kistanova
5c12234f3b Reverted r361134 because of a failing test left unattended for a long time.
http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win/builds/17792/steps/test-check-all/logs/stdio
Failing Tests (1):
    LLVM :: CodeGen/AMDGPU/regbank-reassign.mir

llvm-svn: 361430
2019-05-22 20:42:56 +00:00
Xing Xue
ec236adbbf Disable EHFrameSupport in JITLink/RuntimeDyld on AIX
Summary:
EH Frames aren't supported on AIX with the system compiler, but the definition of HAVE_EHTABLE_SUPPORT misses this which causes linking problems on AIX. This patch updates the definition of HAVE_EHTABLE_SUPPORT in both JITLink and RuntimeDyld.

Author: daltenty

Reviewers: sfertile, xingxue, hubert.reinterpretcase

Reviewed By: xingxue

Subscribers: hiraditya, jsji, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D62203

llvm-svn: 361410
2019-05-22 17:41:27 +00:00