[Orc] Add explicit move construction/assignment to RCMemoryManager.
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / OrcRemoteTargetClient.h
1 //===---- OrcRemoteTargetClient.h - Orc Remote-target Client ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the OrcRemoteTargetClient class and helpers. This class
11 // can be used to communicate over an RPCChannel with an OrcRemoteTargetServer
12 // instance to support remote-JITing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
17 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
18
19 #include "IndirectionUtils.h"
20 #include "OrcRemoteTargetRPCAPI.h"
21 #include <system_error>
22
23 #define DEBUG_TYPE "orc-remote"
24
25 namespace llvm {
26 namespace orc {
27 namespace remote {
28
29 /// This class provides utilities (including memory manager, indirect stubs
30 /// manager, and compile callback manager types) that support remote JITing
31 /// in ORC.
32 ///
33 /// Each of the utility classes talks to a JIT server (an instance of the
34 /// OrcRemoteTargetServer class) via an RPC system (see RPCUtils.h) to carry out
35 /// its actions.
36 template <typename ChannelT>
37 class OrcRemoteTargetClient : public OrcRemoteTargetRPCAPI {
38 public:
39   /// Remote memory manager.
40   class RCMemoryManager : public RuntimeDyld::MemoryManager {
41   public:
42     RCMemoryManager(OrcRemoteTargetClient &Client, ResourceIdMgr::ResourceId Id)
43         : Client(Client), Id(Id) {
44       DEBUG(dbgs() << "Created remote allocator " << Id << "\n");
45     }
46
47     RCMemoryManager(RCMemoryManager &&Other)
48         : Client(std::move(Other.Client)), Id(std::move(Other.Id)),
49           Unmapped(std::move(Other.Unmapped)),
50           Unfinalized(std::move(Other.Unfinalized)) {}
51
52     RCMemoryManager operator=(RCMemoryManager &&Other) {
53       Client = std::move(Other.Client);
54       Id = std::move(Other.Id);
55       Unmapped = std::move(Other.Unmapped);
56       Unfinalized = std::move(Other.Unfinalized);
57       return *this;
58     }
59
60     ~RCMemoryManager() {
61       Client.destroyRemoteAllocator(Id);
62       DEBUG(dbgs() << "Destroyed remote allocator " << Id << "\n");
63     }
64
65     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
66                                  unsigned SectionID,
67                                  StringRef SectionName) override {
68       Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
69       uint8_t *Alloc = reinterpret_cast<uint8_t *>(
70           Unmapped.back().CodeAllocs.back().getLocalAddress());
71       DEBUG(dbgs() << "Allocator " << Id << " allocated code for "
72                    << SectionName << ": " << Alloc << " (" << Size
73                    << " bytes, alignment " << Alignment << ")\n");
74       return Alloc;
75     }
76
77     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
78                                  unsigned SectionID, StringRef SectionName,
79                                  bool IsReadOnly) override {
80       if (IsReadOnly) {
81         Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
82         uint8_t *Alloc = reinterpret_cast<uint8_t *>(
83             Unmapped.back().RODataAllocs.back().getLocalAddress());
84         DEBUG(dbgs() << "Allocator " << Id << " allocated ro-data for "
85                      << SectionName << ": " << Alloc << " (" << Size
86                      << " bytes, alignment " << Alignment << ")\n");
87         return Alloc;
88       } // else...
89
90       Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
91       uint8_t *Alloc = reinterpret_cast<uint8_t *>(
92           Unmapped.back().RWDataAllocs.back().getLocalAddress());
93       DEBUG(dbgs() << "Allocator " << Id << " allocated rw-data for "
94                    << SectionName << ": " << Alloc << " (" << Size
95                    << " bytes, alignment " << Alignment << "\n");
96       return Alloc;
97     }
98
99     void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
100                                 uintptr_t RODataSize, uint32_t RODataAlign,
101                                 uintptr_t RWDataSize,
102                                 uint32_t RWDataAlign) override {
103       Unmapped.push_back(ObjectAllocs());
104
105       DEBUG(dbgs() << "Allocator " << Id << " reserved:\n");
106
107       if (CodeSize != 0) {
108         if (std::error_code EC = Client.reserveMem(
109                 Unmapped.back().RemoteCodeAddr, Id, CodeSize, CodeAlign)) {
110           (void)EC;
111           // FIXME; Add error to poll.
112           llvm_unreachable("Failed reserving remote memory.");
113         }
114         DEBUG(dbgs() << "  code: "
115                      << format("0x%016x", Unmapped.back().RemoteCodeAddr)
116                      << " (" << CodeSize << " bytes, alignment " << CodeAlign
117                      << ")\n");
118       }
119
120       if (RODataSize != 0) {
121         if (auto EC = Client.reserveMem(Unmapped.back().RemoteRODataAddr, Id,
122                                         RODataSize, RODataAlign)) {
123           // FIXME; Add error to poll.
124           llvm_unreachable("Failed reserving remote memory.");
125         }
126         DEBUG(dbgs() << "  ro-data: "
127                      << format("0x%016x", Unmapped.back().RemoteRODataAddr)
128                      << " (" << RODataSize << " bytes, alignment "
129                      << RODataAlign << ")\n");
130       }
131
132       if (RWDataSize != 0) {
133         if (auto EC = Client.reserveMem(Unmapped.back().RemoteRWDataAddr, Id,
134                                         RWDataSize, RWDataAlign)) {
135           // FIXME; Add error to poll.
136           llvm_unreachable("Failed reserving remote memory.");
137         }
138         DEBUG(dbgs() << "  rw-data: "
139                      << format("0x%016x", Unmapped.back().RemoteRWDataAddr)
140                      << " (" << RWDataSize << " bytes, alignment "
141                      << RWDataAlign << ")\n");
142       }
143     }
144
145     bool needsToReserveAllocationSpace() override { return true; }
146
147     void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
148                           size_t Size) override {}
149
150     void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr,
151                             size_t Size) override {}
152
153     void notifyObjectLoaded(RuntimeDyld &Dyld,
154                             const object::ObjectFile &Obj) override {
155       DEBUG(dbgs() << "Allocator " << Id << " applied mappings:\n");
156       for (auto &ObjAllocs : Unmapped) {
157         {
158           TargetAddress NextCodeAddr = ObjAllocs.RemoteCodeAddr;
159           for (auto &Alloc : ObjAllocs.CodeAllocs) {
160             NextCodeAddr = RoundUpToAlignment(NextCodeAddr, Alloc.getAlign());
161             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextCodeAddr);
162             DEBUG(dbgs() << "     code: "
163                          << static_cast<void *>(Alloc.getLocalAddress())
164                          << " -> " << format("0x%016x", NextCodeAddr) << "\n");
165             Alloc.setRemoteAddress(NextCodeAddr);
166             NextCodeAddr += Alloc.getSize();
167           }
168         }
169         {
170           TargetAddress NextRODataAddr = ObjAllocs.RemoteRODataAddr;
171           for (auto &Alloc : ObjAllocs.RODataAllocs) {
172             NextRODataAddr =
173                 RoundUpToAlignment(NextRODataAddr, Alloc.getAlign());
174             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRODataAddr);
175             DEBUG(dbgs() << "  ro-data: "
176                          << static_cast<void *>(Alloc.getLocalAddress())
177                          << " -> " << format("0x%016x", NextRODataAddr)
178                          << "\n");
179             Alloc.setRemoteAddress(NextRODataAddr);
180             NextRODataAddr += Alloc.getSize();
181           }
182         }
183         {
184           TargetAddress NextRWDataAddr = ObjAllocs.RemoteRWDataAddr;
185           for (auto &Alloc : ObjAllocs.RWDataAllocs) {
186             NextRWDataAddr =
187                 RoundUpToAlignment(NextRWDataAddr, Alloc.getAlign());
188             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRWDataAddr);
189             DEBUG(dbgs() << "  rw-data: "
190                          << static_cast<void *>(Alloc.getLocalAddress())
191                          << " -> " << format("0x%016x", NextRWDataAddr)
192                          << "\n");
193             Alloc.setRemoteAddress(NextRWDataAddr);
194             NextRWDataAddr += Alloc.getSize();
195           }
196         }
197         Unfinalized.push_back(std::move(ObjAllocs));
198       }
199       Unmapped.clear();
200     }
201
202     bool finalizeMemory(std::string *ErrMsg = nullptr) override {
203       DEBUG(dbgs() << "Allocator " << Id << " finalizing:\n");
204
205       for (auto &ObjAllocs : Unfinalized) {
206
207         for (auto &Alloc : ObjAllocs.CodeAllocs) {
208           DEBUG(dbgs() << "  copying code: "
209                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
210                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
211                        << Alloc.getSize() << " bytes)\n");
212           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
213                           Alloc.getSize());
214         }
215
216         if (ObjAllocs.RemoteCodeAddr) {
217           DEBUG(dbgs() << "  setting R-X permissions on code block: "
218                        << format("0x%016x", ObjAllocs.RemoteCodeAddr) << "\n");
219           Client.setProtections(Id, ObjAllocs.RemoteCodeAddr,
220                                 sys::Memory::MF_READ | sys::Memory::MF_EXEC);
221         }
222
223         for (auto &Alloc : ObjAllocs.RODataAllocs) {
224           DEBUG(dbgs() << "  copying ro-data: "
225                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
226                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
227                        << Alloc.getSize() << " bytes)\n");
228           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
229                           Alloc.getSize());
230         }
231
232         if (ObjAllocs.RemoteRODataAddr) {
233           DEBUG(dbgs() << "  setting R-- permissions on ro-data block: "
234                        << format("0x%016x", ObjAllocs.RemoteRODataAddr)
235                        << "\n");
236           Client.setProtections(Id, ObjAllocs.RemoteRODataAddr,
237                                 sys::Memory::MF_READ);
238         }
239
240         for (auto &Alloc : ObjAllocs.RWDataAllocs) {
241           DEBUG(dbgs() << "  copying rw-data: "
242                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
243                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
244                        << Alloc.getSize() << " bytes)\n");
245           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
246                           Alloc.getSize());
247         }
248
249         if (ObjAllocs.RemoteRWDataAddr) {
250           DEBUG(dbgs() << "  setting RW- permissions on rw-data block: "
251                        << format("0x%016x", ObjAllocs.RemoteRWDataAddr)
252                        << "\n");
253           Client.setProtections(Id, ObjAllocs.RemoteRWDataAddr,
254                                 sys::Memory::MF_READ | sys::Memory::MF_WRITE);
255         }
256       }
257       Unfinalized.clear();
258
259       return false;
260     }
261
262   private:
263     class Alloc {
264     public:
265       Alloc(uint64_t Size, unsigned Align)
266           : Size(Size), Align(Align), Contents(new char[Size + Align - 1]),
267             RemoteAddr(0) {}
268
269       Alloc(Alloc &&Other)
270           : Size(std::move(Other.Size)), Align(std::move(Other.Align)),
271             Contents(std::move(Other.Contents)),
272             RemoteAddr(std::move(Other.RemoteAddr)) {}
273
274       Alloc &operator=(Alloc &&Other) {
275         Size = std::move(Other.Size);
276         Align = std::move(Other.Align);
277         Contents = std::move(Other.Contents);
278         RemoteAddr = std::move(Other.RemoteAddr);
279         return *this;
280       }
281
282       uint64_t getSize() const { return Size; }
283
284       unsigned getAlign() const { return Align; }
285
286       char *getLocalAddress() const {
287         uintptr_t LocalAddr = reinterpret_cast<uintptr_t>(Contents.get());
288         LocalAddr = RoundUpToAlignment(LocalAddr, Align);
289         return reinterpret_cast<char *>(LocalAddr);
290       }
291
292       void setRemoteAddress(TargetAddress RemoteAddr) {
293         this->RemoteAddr = RemoteAddr;
294       }
295
296       TargetAddress getRemoteAddress() const { return RemoteAddr; }
297
298     private:
299       uint64_t Size;
300       unsigned Align;
301       std::unique_ptr<char[]> Contents;
302       TargetAddress RemoteAddr;
303     };
304
305     struct ObjectAllocs {
306       ObjectAllocs()
307           : RemoteCodeAddr(0), RemoteRODataAddr(0), RemoteRWDataAddr(0) {}
308       TargetAddress RemoteCodeAddr;
309       TargetAddress RemoteRODataAddr;
310       TargetAddress RemoteRWDataAddr;
311       std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
312     };
313
314     OrcRemoteTargetClient &Client;
315     ResourceIdMgr::ResourceId Id;
316     std::vector<ObjectAllocs> Unmapped;
317     std::vector<ObjectAllocs> Unfinalized;
318   };
319
320   /// Remote indirect stubs manager.
321   class RCIndirectStubsManager : public IndirectStubsManager {
322   public:
323     RCIndirectStubsManager(OrcRemoteTargetClient &Remote,
324                            ResourceIdMgr::ResourceId Id)
325         : Remote(Remote), Id(Id) {}
326
327     ~RCIndirectStubsManager() { Remote.destroyIndirectStubsManager(Id); }
328
329     std::error_code createStub(StringRef StubName, TargetAddress StubAddr,
330                                JITSymbolFlags StubFlags) override {
331       if (auto EC = reserveStubs(1))
332         return EC;
333
334       return createStubInternal(StubName, StubAddr, StubFlags);
335     }
336
337     std::error_code createStubs(const StubInitsMap &StubInits) override {
338       if (auto EC = reserveStubs(StubInits.size()))
339         return EC;
340
341       for (auto &Entry : StubInits)
342         if (auto EC = createStubInternal(Entry.first(), Entry.second.first,
343                                          Entry.second.second))
344           return EC;
345
346       return std::error_code();
347     }
348
349     JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
350       auto I = StubIndexes.find(Name);
351       if (I == StubIndexes.end())
352         return nullptr;
353       auto Key = I->second.first;
354       auto Flags = I->second.second;
355       auto StubSymbol = JITSymbol(getStubAddr(Key), Flags);
356       if (ExportedStubsOnly && !StubSymbol.isExported())
357         return nullptr;
358       return StubSymbol;
359     }
360
361     JITSymbol findPointer(StringRef Name) override {
362       auto I = StubIndexes.find(Name);
363       if (I == StubIndexes.end())
364         return nullptr;
365       auto Key = I->second.first;
366       auto Flags = I->second.second;
367       return JITSymbol(getPtrAddr(Key), Flags);
368     }
369
370     std::error_code updatePointer(StringRef Name,
371                                   TargetAddress NewAddr) override {
372       auto I = StubIndexes.find(Name);
373       assert(I != StubIndexes.end() && "No stub pointer for symbol");
374       auto Key = I->second.first;
375       return Remote.writePointer(getPtrAddr(Key), NewAddr);
376     }
377
378   private:
379     struct RemoteIndirectStubsInfo {
380       RemoteIndirectStubsInfo(TargetAddress StubBase, TargetAddress PtrBase,
381                               unsigned NumStubs)
382           : StubBase(StubBase), PtrBase(PtrBase), NumStubs(NumStubs) {}
383       TargetAddress StubBase;
384       TargetAddress PtrBase;
385       unsigned NumStubs;
386     };
387
388     OrcRemoteTargetClient &Remote;
389     ResourceIdMgr::ResourceId Id;
390     std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
391     typedef std::pair<uint16_t, uint16_t> StubKey;
392     std::vector<StubKey> FreeStubs;
393     StringMap<std::pair<StubKey, JITSymbolFlags>> StubIndexes;
394
395     std::error_code reserveStubs(unsigned NumStubs) {
396       if (NumStubs <= FreeStubs.size())
397         return std::error_code();
398
399       unsigned NewStubsRequired = NumStubs - FreeStubs.size();
400       TargetAddress StubBase;
401       TargetAddress PtrBase;
402       unsigned NumStubsEmitted;
403
404       Remote.emitIndirectStubs(StubBase, PtrBase, NumStubsEmitted, Id,
405                                NewStubsRequired);
406
407       unsigned NewBlockId = RemoteIndirectStubsInfos.size();
408       RemoteIndirectStubsInfos.push_back(
409           RemoteIndirectStubsInfo(StubBase, PtrBase, NumStubsEmitted));
410
411       for (unsigned I = 0; I < NumStubsEmitted; ++I)
412         FreeStubs.push_back(std::make_pair(NewBlockId, I));
413
414       return std::error_code();
415     }
416
417     std::error_code createStubInternal(StringRef StubName,
418                                        TargetAddress InitAddr,
419                                        JITSymbolFlags StubFlags) {
420       auto Key = FreeStubs.back();
421       FreeStubs.pop_back();
422       StubIndexes[StubName] = std::make_pair(Key, StubFlags);
423       return Remote.writePointer(getPtrAddr(Key), InitAddr);
424     }
425
426     TargetAddress getStubAddr(StubKey K) {
427       assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
428              "Missing stub address");
429       return RemoteIndirectStubsInfos[K.first].StubBase +
430              K.second * Remote.getIndirectStubSize();
431     }
432
433     TargetAddress getPtrAddr(StubKey K) {
434       assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
435              "Missing pointer address");
436       return RemoteIndirectStubsInfos[K.first].PtrBase +
437              K.second * Remote.getPointerSize();
438     }
439   };
440
441   /// Remote compile callback manager.
442   class RCCompileCallbackManager : public JITCompileCallbackManager {
443   public:
444     RCCompileCallbackManager(TargetAddress ErrorHandlerAddress,
445                              OrcRemoteTargetClient &Remote)
446         : JITCompileCallbackManager(ErrorHandlerAddress), Remote(Remote) {
447       assert(!Remote.CompileCallback && "Compile callback already set");
448       Remote.CompileCallback = [this](TargetAddress TrampolineAddr) {
449         return executeCompileCallback(TrampolineAddr);
450       };
451       Remote.emitResolverBlock();
452     }
453
454   private:
455     void grow() {
456       TargetAddress BlockAddr = 0;
457       uint32_t NumTrampolines = 0;
458       auto EC = Remote.emitTrampolineBlock(BlockAddr, NumTrampolines);
459       assert(!EC && "Failed to create trampolines");
460
461       uint32_t TrampolineSize = Remote.getTrampolineSize();
462       for (unsigned I = 0; I < NumTrampolines; ++I)
463         this->AvailableTrampolines.push_back(BlockAddr + (I * TrampolineSize));
464     }
465
466     OrcRemoteTargetClient &Remote;
467   };
468
469   /// Create an OrcRemoteTargetClient.
470   /// Channel is the ChannelT instance to communicate on. It is assumed that
471   /// the channel is ready to be read from and written to.
472   static ErrorOr<OrcRemoteTargetClient> Create(ChannelT &Channel) {
473     std::error_code EC;
474     OrcRemoteTargetClient H(Channel, EC);
475     if (EC)
476       return EC;
477     return H;
478   }
479
480   /// Call the int(void) function at the given address in the target and return
481   /// its result.
482   std::error_code callIntVoid(int &Result, TargetAddress Addr) {
483     DEBUG(dbgs() << "Calling int(*)(void) " << format("0x%016x", Addr) << "\n");
484
485     if (auto EC = call<CallIntVoid>(Channel, Addr))
486       return EC;
487
488     unsigned NextProcId;
489     if (auto EC = listenForCompileRequests(NextProcId))
490       return EC;
491
492     if (NextProcId != CallIntVoidResponseId)
493       return orcError(OrcErrorCode::UnexpectedRPCCall);
494
495     return handle<CallIntVoidResponse>(Channel, [&](int R) {
496       Result = R;
497       DEBUG(dbgs() << "Result: " << R << "\n");
498       return std::error_code();
499     });
500   }
501
502   /// Call the int(int, char*[]) function at the given address in the target and
503   /// return its result.
504   std::error_code callMain(int &Result, TargetAddress Addr,
505                            const std::vector<std::string> &Args) {
506     DEBUG(dbgs() << "Calling int(*)(int, char*[]) " << format("0x%016x", Addr)
507                  << "\n");
508
509     if (auto EC = call<CallMain>(Channel, Addr, Args))
510       return EC;
511
512     unsigned NextProcId;
513     if (auto EC = listenForCompileRequests(NextProcId))
514       return EC;
515
516     if (NextProcId != CallMainResponseId)
517       return orcError(OrcErrorCode::UnexpectedRPCCall);
518
519     return handle<CallMainResponse>(Channel, [&](int R) {
520       Result = R;
521       DEBUG(dbgs() << "Result: " << R << "\n");
522       return std::error_code();
523     });
524   }
525
526   /// Call the void() function at the given address in the target and wait for
527   /// it to finish.
528   std::error_code callVoidVoid(TargetAddress Addr) {
529     DEBUG(dbgs() << "Calling void(*)(void) " << format("0x%016x", Addr)
530                  << "\n");
531
532     if (auto EC = call<CallVoidVoid>(Channel, Addr))
533       return EC;
534
535     unsigned NextProcId;
536     if (auto EC = listenForCompileRequests(NextProcId))
537       return EC;
538
539     if (NextProcId != CallVoidVoidResponseId)
540       return orcError(OrcErrorCode::UnexpectedRPCCall);
541
542     return handle<CallVoidVoidResponse>(Channel, doNothing);
543   }
544
545   /// Create an RCMemoryManager which will allocate its memory on the remote
546   /// target.
547   std::error_code
548   createRemoteMemoryManager(std::unique_ptr<RCMemoryManager> &MM) {
549     assert(!MM && "MemoryManager should be null before creation.");
550
551     auto Id = AllocatorIds.getNext();
552     if (auto EC = call<CreateRemoteAllocator>(Channel, Id))
553       return EC;
554     MM = llvm::make_unique<RCMemoryManager>(*this, Id);
555     return std::error_code();
556   }
557
558   /// Create an RCIndirectStubsManager that will allocate stubs on the remote
559   /// target.
560   std::error_code
561   createIndirectStubsManager(std::unique_ptr<RCIndirectStubsManager> &I) {
562     assert(!I && "Indirect stubs manager should be null before creation.");
563     auto Id = IndirectStubOwnerIds.getNext();
564     if (auto EC = call<CreateIndirectStubsOwner>(Channel, Id))
565       return EC;
566     I = llvm::make_unique<RCIndirectStubsManager>(*this, Id);
567     return std::error_code();
568   }
569
570   /// Search for symbols in the remote process. Note: This should be used by
571   /// symbol resolvers *after* they've searched the local symbol table in the
572   /// JIT stack.
573   std::error_code getSymbolAddress(TargetAddress &Addr, StringRef Name) {
574     // Check for an 'out-of-band' error, e.g. from an MM destructor.
575     if (ExistingError)
576       return ExistingError;
577
578     // Request remote symbol address.
579     if (auto EC = call<GetSymbolAddress>(Channel, Name))
580       return EC;
581
582     return expect<GetSymbolAddressResponse>(Channel, [&](TargetAddress &A) {
583       Addr = A;
584       DEBUG(dbgs() << "Remote address lookup " << Name << " = "
585                    << format("0x%016x", Addr) << "\n");
586       return std::error_code();
587     });
588   }
589
590   /// Get the triple for the remote target.
591   const std::string &getTargetTriple() const { return RemoteTargetTriple; }
592
593   std::error_code terminateSession() { return call<TerminateSession>(Channel); }
594
595 private:
596   OrcRemoteTargetClient(ChannelT &Channel, std::error_code &EC)
597       : Channel(Channel), RemotePointerSize(0), RemotePageSize(0),
598         RemoteTrampolineSize(0), RemoteIndirectStubSize(0) {
599     if ((EC = call<GetRemoteInfo>(Channel)))
600       return;
601
602     EC = expect<GetRemoteInfoResponse>(
603         Channel, readArgs(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
604                           RemoteTrampolineSize, RemoteIndirectStubSize));
605   }
606
607   void destroyRemoteAllocator(ResourceIdMgr::ResourceId Id) {
608     if (auto EC = call<DestroyRemoteAllocator>(Channel, Id)) {
609       // FIXME: This will be triggered by a removeModuleSet call: Propagate
610       //        error return up through that.
611       llvm_unreachable("Failed to destroy remote allocator.");
612       AllocatorIds.release(Id);
613     }
614   }
615
616   std::error_code destroyIndirectStubsManager(ResourceIdMgr::ResourceId Id) {
617     IndirectStubOwnerIds.release(Id);
618     return call<DestroyIndirectStubsOwner>(Channel, Id);
619   }
620
621   std::error_code emitIndirectStubs(TargetAddress &StubBase,
622                                     TargetAddress &PtrBase,
623                                     uint32_t &NumStubsEmitted,
624                                     ResourceIdMgr::ResourceId Id,
625                                     uint32_t NumStubsRequired) {
626     if (auto EC = call<EmitIndirectStubs>(Channel, Id, NumStubsRequired))
627       return EC;
628
629     return expect<EmitIndirectStubsResponse>(
630         Channel, readArgs(StubBase, PtrBase, NumStubsEmitted));
631   }
632
633   std::error_code emitResolverBlock() {
634     // Check for an 'out-of-band' error, e.g. from an MM destructor.
635     if (ExistingError)
636       return ExistingError;
637
638     return call<EmitResolverBlock>(Channel);
639   }
640
641   std::error_code emitTrampolineBlock(TargetAddress &BlockAddr,
642                                       uint32_t &NumTrampolines) {
643     // Check for an 'out-of-band' error, e.g. from an MM destructor.
644     if (ExistingError)
645       return ExistingError;
646
647     if (auto EC = call<EmitTrampolineBlock>(Channel))
648       return EC;
649
650     return expect<EmitTrampolineBlockResponse>(
651         Channel, [&](TargetAddress BAddr, uint32_t NTrampolines) {
652           BlockAddr = BAddr;
653           NumTrampolines = NTrampolines;
654           return std::error_code();
655         });
656   }
657
658   uint32_t getIndirectStubSize() const { return RemoteIndirectStubSize; }
659   uint32_t getPageSize() const { return RemotePageSize; }
660   uint32_t getPointerSize() const { return RemotePointerSize; }
661
662   uint32_t getTrampolineSize() const { return RemoteTrampolineSize; }
663
664   std::error_code listenForCompileRequests(uint32_t &NextId) {
665     // Check for an 'out-of-band' error, e.g. from an MM destructor.
666     if (ExistingError)
667       return ExistingError;
668
669     if (auto EC = getNextProcId(Channel, NextId))
670       return EC;
671
672     while (NextId == RequestCompileId) {
673       TargetAddress TrampolineAddr = 0;
674       if (auto EC = handle<RequestCompile>(Channel, readArgs(TrampolineAddr)))
675         return EC;
676
677       TargetAddress ImplAddr = CompileCallback(TrampolineAddr);
678       if (auto EC = call<RequestCompileResponse>(Channel, ImplAddr))
679         return EC;
680
681       if (auto EC = getNextProcId(Channel, NextId))
682         return EC;
683     }
684
685     return std::error_code();
686   }
687
688   std::error_code readMem(char *Dst, TargetAddress Src, uint64_t Size) {
689     // Check for an 'out-of-band' error, e.g. from an MM destructor.
690     if (ExistingError)
691       return ExistingError;
692
693     if (auto EC = call<ReadMem>(Channel, Src, Size))
694       return EC;
695
696     if (auto EC = expect<ReadMemResponse>(
697             Channel, [&]() { return Channel.readBytes(Dst, Size); }))
698       return EC;
699
700     return std::error_code();
701   }
702
703   std::error_code reserveMem(TargetAddress &RemoteAddr,
704                              ResourceIdMgr::ResourceId Id, uint64_t Size,
705                              uint32_t Align) {
706
707     // Check for an 'out-of-band' error, e.g. from an MM destructor.
708     if (ExistingError)
709       return ExistingError;
710
711     if (auto EC = call<ReserveMem>(Channel, Id, Size, Align))
712       return EC;
713
714     if (std::error_code EC =
715             expect<ReserveMemResponse>(Channel, [&](TargetAddress Addr) {
716               RemoteAddr = Addr;
717               return std::error_code();
718             }))
719       return EC;
720
721     return std::error_code();
722   }
723
724   std::error_code setProtections(ResourceIdMgr::ResourceId Id,
725                                  TargetAddress RemoteSegAddr,
726                                  unsigned ProtFlags) {
727     return call<SetProtections>(Channel, Id, RemoteSegAddr, ProtFlags);
728   }
729
730   std::error_code writeMem(TargetAddress Addr, const char *Src, uint64_t Size) {
731     // Check for an 'out-of-band' error, e.g. from an MM destructor.
732     if (ExistingError)
733       return ExistingError;
734
735     // Make the send call.
736     if (auto EC = call<WriteMem>(Channel, Addr, Size))
737       return EC;
738
739     // Follow this up with the section contents.
740     if (auto EC = Channel.appendBytes(Src, Size))
741       return EC;
742
743     return Channel.send();
744   }
745
746   std::error_code writePointer(TargetAddress Addr, TargetAddress PtrVal) {
747     // Check for an 'out-of-band' error, e.g. from an MM destructor.
748     if (ExistingError)
749       return ExistingError;
750
751     return call<WritePtr>(Channel, Addr, PtrVal);
752   }
753
754   static std::error_code doNothing() { return std::error_code(); }
755
756   ChannelT &Channel;
757   std::error_code ExistingError;
758   std::string RemoteTargetTriple;
759   uint32_t RemotePointerSize;
760   uint32_t RemotePageSize;
761   uint32_t RemoteTrampolineSize;
762   uint32_t RemoteIndirectStubSize;
763   ResourceIdMgr AllocatorIds, IndirectStubOwnerIds;
764   std::function<TargetAddress(TargetAddress)> CompileCallback;
765 };
766
767 } // end namespace remote
768 } // end namespace orc
769 } // end namespace llvm
770
771 #undef DEBUG_TYPE
772
773 #endif