xref: /llvm-project-15.0.7/llvm/lib/IR/Core.cpp (revision fc410138)
1 //===-- Core.cpp ----------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the common infrastructure (including the C bindings)
10 // for libLLVMCore.a, which implements the LLVM intermediate representation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm-c/Core.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/IR/Attributes.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/GlobalAlias.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Threading.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cassert>
39 #include <cstdlib>
40 #include <cstring>
41 #include <system_error>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "ir"
46 
47 void llvm::initializeCore(PassRegistry &Registry) {
48   initializeDominatorTreeWrapperPassPass(Registry);
49   initializePrintModulePassWrapperPass(Registry);
50   initializePrintFunctionPassWrapperPass(Registry);
51   initializeSafepointIRVerifierPass(Registry);
52   initializeVerifierLegacyPassPass(Registry);
53 }
54 
55 void LLVMInitializeCore(LLVMPassRegistryRef R) {
56   initializeCore(*unwrap(R));
57 }
58 
59 void LLVMShutdown() {
60   llvm_shutdown();
61 }
62 
63 /*===-- Error handling ----------------------------------------------------===*/
64 
65 char *LLVMCreateMessage(const char *Message) {
66   return strdup(Message);
67 }
68 
69 void LLVMDisposeMessage(char *Message) {
70   free(Message);
71 }
72 
73 
74 /*===-- Operations on contexts --------------------------------------------===*/
75 
76 static ManagedStatic<LLVMContext> GlobalContext;
77 
78 LLVMContextRef LLVMContextCreate() {
79   return wrap(new LLVMContext());
80 }
81 
82 LLVMContextRef LLVMGetGlobalContext() { return wrap(&*GlobalContext); }
83 
84 void LLVMContextSetDiagnosticHandler(LLVMContextRef C,
85                                      LLVMDiagnosticHandler Handler,
86                                      void *DiagnosticContext) {
87   unwrap(C)->setDiagnosticHandlerCallBack(
88       LLVM_EXTENSION reinterpret_cast<DiagnosticHandler::DiagnosticHandlerTy>(
89           Handler),
90       DiagnosticContext);
91 }
92 
93 LLVMDiagnosticHandler LLVMContextGetDiagnosticHandler(LLVMContextRef C) {
94   return LLVM_EXTENSION reinterpret_cast<LLVMDiagnosticHandler>(
95       unwrap(C)->getDiagnosticHandlerCallBack());
96 }
97 
98 void *LLVMContextGetDiagnosticContext(LLVMContextRef C) {
99   return unwrap(C)->getDiagnosticContext();
100 }
101 
102 void LLVMContextSetYieldCallback(LLVMContextRef C, LLVMYieldCallback Callback,
103                                  void *OpaqueHandle) {
104   auto YieldCallback =
105     LLVM_EXTENSION reinterpret_cast<LLVMContext::YieldCallbackTy>(Callback);
106   unwrap(C)->setYieldCallback(YieldCallback, OpaqueHandle);
107 }
108 
109 LLVMBool LLVMContextShouldDiscardValueNames(LLVMContextRef C) {
110   return unwrap(C)->shouldDiscardValueNames();
111 }
112 
113 void LLVMContextSetDiscardValueNames(LLVMContextRef C, LLVMBool Discard) {
114   unwrap(C)->setDiscardValueNames(Discard);
115 }
116 
117 void LLVMContextDispose(LLVMContextRef C) {
118   delete unwrap(C);
119 }
120 
121 unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char *Name,
122                                   unsigned SLen) {
123   return unwrap(C)->getMDKindID(StringRef(Name, SLen));
124 }
125 
126 unsigned LLVMGetMDKindID(const char *Name, unsigned SLen) {
127   return LLVMGetMDKindIDInContext(LLVMGetGlobalContext(), Name, SLen);
128 }
129 
130 unsigned LLVMGetEnumAttributeKindForName(const char *Name, size_t SLen) {
131   return Attribute::getAttrKindFromName(StringRef(Name, SLen));
132 }
133 
134 unsigned LLVMGetLastEnumAttributeKind(void) {
135   return Attribute::AttrKind::EndAttrKinds;
136 }
137 
138 LLVMAttributeRef LLVMCreateEnumAttribute(LLVMContextRef C, unsigned KindID,
139                                          uint64_t Val) {
140   auto &Ctx = *unwrap(C);
141   auto AttrKind = (Attribute::AttrKind)KindID;
142 
143   if (AttrKind == Attribute::AttrKind::ByVal) {
144     // After r362128, byval attributes need to have a type attribute. Provide a
145     // NULL one until a proper API is added for this.
146     return wrap(Attribute::getWithByValType(Ctx, NULL));
147   }
148 
149   return wrap(Attribute::get(Ctx, AttrKind, Val));
150 }
151 
152 unsigned LLVMGetEnumAttributeKind(LLVMAttributeRef A) {
153   return unwrap(A).getKindAsEnum();
154 }
155 
156 uint64_t LLVMGetEnumAttributeValue(LLVMAttributeRef A) {
157   auto Attr = unwrap(A);
158   if (Attr.isEnumAttribute())
159     return 0;
160   return Attr.getValueAsInt();
161 }
162 
163 LLVMAttributeRef LLVMCreateStringAttribute(LLVMContextRef C,
164                                            const char *K, unsigned KLength,
165                                            const char *V, unsigned VLength) {
166   return wrap(Attribute::get(*unwrap(C), StringRef(K, KLength),
167                              StringRef(V, VLength)));
168 }
169 
170 const char *LLVMGetStringAttributeKind(LLVMAttributeRef A,
171                                        unsigned *Length) {
172   auto S = unwrap(A).getKindAsString();
173   *Length = S.size();
174   return S.data();
175 }
176 
177 const char *LLVMGetStringAttributeValue(LLVMAttributeRef A,
178                                         unsigned *Length) {
179   auto S = unwrap(A).getValueAsString();
180   *Length = S.size();
181   return S.data();
182 }
183 
184 LLVMBool LLVMIsEnumAttribute(LLVMAttributeRef A) {
185   auto Attr = unwrap(A);
186   return Attr.isEnumAttribute() || Attr.isIntAttribute();
187 }
188 
189 LLVMBool LLVMIsStringAttribute(LLVMAttributeRef A) {
190   return unwrap(A).isStringAttribute();
191 }
192 
193 char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {
194   std::string MsgStorage;
195   raw_string_ostream Stream(MsgStorage);
196   DiagnosticPrinterRawOStream DP(Stream);
197 
198   unwrap(DI)->print(DP);
199   Stream.flush();
200 
201   return LLVMCreateMessage(MsgStorage.c_str());
202 }
203 
204 LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI) {
205     LLVMDiagnosticSeverity severity;
206 
207     switch(unwrap(DI)->getSeverity()) {
208     default:
209       severity = LLVMDSError;
210       break;
211     case DS_Warning:
212       severity = LLVMDSWarning;
213       break;
214     case DS_Remark:
215       severity = LLVMDSRemark;
216       break;
217     case DS_Note:
218       severity = LLVMDSNote;
219       break;
220     }
221 
222     return severity;
223 }
224 
225 /*===-- Operations on modules ---------------------------------------------===*/
226 
227 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {
228   return wrap(new Module(ModuleID, *GlobalContext));
229 }
230 
231 LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,
232                                                 LLVMContextRef C) {
233   return wrap(new Module(ModuleID, *unwrap(C)));
234 }
235 
236 void LLVMDisposeModule(LLVMModuleRef M) {
237   delete unwrap(M);
238 }
239 
240 const char *LLVMGetModuleIdentifier(LLVMModuleRef M, size_t *Len) {
241   auto &Str = unwrap(M)->getModuleIdentifier();
242   *Len = Str.length();
243   return Str.c_str();
244 }
245 
246 void LLVMSetModuleIdentifier(LLVMModuleRef M, const char *Ident, size_t Len) {
247   unwrap(M)->setModuleIdentifier(StringRef(Ident, Len));
248 }
249 
250 const char *LLVMGetSourceFileName(LLVMModuleRef M, size_t *Len) {
251   auto &Str = unwrap(M)->getSourceFileName();
252   *Len = Str.length();
253   return Str.c_str();
254 }
255 
256 void LLVMSetSourceFileName(LLVMModuleRef M, const char *Name, size_t Len) {
257   unwrap(M)->setSourceFileName(StringRef(Name, Len));
258 }
259 
260 /*--.. Data layout .........................................................--*/
261 const char *LLVMGetDataLayoutStr(LLVMModuleRef M) {
262   return unwrap(M)->getDataLayoutStr().c_str();
263 }
264 
265 const char *LLVMGetDataLayout(LLVMModuleRef M) {
266   return LLVMGetDataLayoutStr(M);
267 }
268 
269 void LLVMSetDataLayout(LLVMModuleRef M, const char *DataLayoutStr) {
270   unwrap(M)->setDataLayout(DataLayoutStr);
271 }
272 
273 /*--.. Target triple .......................................................--*/
274 const char * LLVMGetTarget(LLVMModuleRef M) {
275   return unwrap(M)->getTargetTriple().c_str();
276 }
277 
278 void LLVMSetTarget(LLVMModuleRef M, const char *Triple) {
279   unwrap(M)->setTargetTriple(Triple);
280 }
281 
282 /*--.. Module flags ........................................................--*/
283 struct LLVMOpaqueModuleFlagEntry {
284   LLVMModuleFlagBehavior Behavior;
285   const char *Key;
286   size_t KeyLen;
287   LLVMMetadataRef Metadata;
288 };
289 
290 static Module::ModFlagBehavior
291 map_to_llvmModFlagBehavior(LLVMModuleFlagBehavior Behavior) {
292   switch (Behavior) {
293   case LLVMModuleFlagBehaviorError:
294     return Module::ModFlagBehavior::Error;
295   case LLVMModuleFlagBehaviorWarning:
296     return Module::ModFlagBehavior::Warning;
297   case LLVMModuleFlagBehaviorRequire:
298     return Module::ModFlagBehavior::Require;
299   case LLVMModuleFlagBehaviorOverride:
300     return Module::ModFlagBehavior::Override;
301   case LLVMModuleFlagBehaviorAppend:
302     return Module::ModFlagBehavior::Append;
303   case LLVMModuleFlagBehaviorAppendUnique:
304     return Module::ModFlagBehavior::AppendUnique;
305   }
306   llvm_unreachable("Unknown LLVMModuleFlagBehavior");
307 }
308 
309 static LLVMModuleFlagBehavior
310 map_from_llvmModFlagBehavior(Module::ModFlagBehavior Behavior) {
311   switch (Behavior) {
312   case Module::ModFlagBehavior::Error:
313     return LLVMModuleFlagBehaviorError;
314   case Module::ModFlagBehavior::Warning:
315     return LLVMModuleFlagBehaviorWarning;
316   case Module::ModFlagBehavior::Require:
317     return LLVMModuleFlagBehaviorRequire;
318   case Module::ModFlagBehavior::Override:
319     return LLVMModuleFlagBehaviorOverride;
320   case Module::ModFlagBehavior::Append:
321     return LLVMModuleFlagBehaviorAppend;
322   case Module::ModFlagBehavior::AppendUnique:
323     return LLVMModuleFlagBehaviorAppendUnique;
324   default:
325     llvm_unreachable("Unhandled Flag Behavior");
326   }
327 }
328 
329 LLVMModuleFlagEntry *LLVMCopyModuleFlagsMetadata(LLVMModuleRef M, size_t *Len) {
330   SmallVector<Module::ModuleFlagEntry, 8> MFEs;
331   unwrap(M)->getModuleFlagsMetadata(MFEs);
332 
333   LLVMOpaqueModuleFlagEntry *Result = static_cast<LLVMOpaqueModuleFlagEntry *>(
334       safe_malloc(MFEs.size() * sizeof(LLVMOpaqueModuleFlagEntry)));
335   for (unsigned i = 0; i < MFEs.size(); ++i) {
336     const auto &ModuleFlag = MFEs[i];
337     Result[i].Behavior = map_from_llvmModFlagBehavior(ModuleFlag.Behavior);
338     Result[i].Key = ModuleFlag.Key->getString().data();
339     Result[i].KeyLen = ModuleFlag.Key->getString().size();
340     Result[i].Metadata = wrap(ModuleFlag.Val);
341   }
342   *Len = MFEs.size();
343   return Result;
344 }
345 
346 void LLVMDisposeModuleFlagsMetadata(LLVMModuleFlagEntry *Entries) {
347   free(Entries);
348 }
349 
350 LLVMModuleFlagBehavior
351 LLVMModuleFlagEntriesGetFlagBehavior(LLVMModuleFlagEntry *Entries,
352                                      unsigned Index) {
353   LLVMOpaqueModuleFlagEntry MFE =
354       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
355   return MFE.Behavior;
356 }
357 
358 const char *LLVMModuleFlagEntriesGetKey(LLVMModuleFlagEntry *Entries,
359                                         unsigned Index, size_t *Len) {
360   LLVMOpaqueModuleFlagEntry MFE =
361       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
362   *Len = MFE.KeyLen;
363   return MFE.Key;
364 }
365 
366 LLVMMetadataRef LLVMModuleFlagEntriesGetMetadata(LLVMModuleFlagEntry *Entries,
367                                                  unsigned Index) {
368   LLVMOpaqueModuleFlagEntry MFE =
369       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
370   return MFE.Metadata;
371 }
372 
373 LLVMMetadataRef LLVMGetModuleFlag(LLVMModuleRef M,
374                                   const char *Key, size_t KeyLen) {
375   return wrap(unwrap(M)->getModuleFlag({Key, KeyLen}));
376 }
377 
378 void LLVMAddModuleFlag(LLVMModuleRef M, LLVMModuleFlagBehavior Behavior,
379                        const char *Key, size_t KeyLen,
380                        LLVMMetadataRef Val) {
381   unwrap(M)->addModuleFlag(map_to_llvmModFlagBehavior(Behavior),
382                            {Key, KeyLen}, unwrap(Val));
383 }
384 
385 /*--.. Printing modules ....................................................--*/
386 
387 void LLVMDumpModule(LLVMModuleRef M) {
388   unwrap(M)->print(errs(), nullptr,
389                    /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
390 }
391 
392 LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename,
393                                char **ErrorMessage) {
394   std::error_code EC;
395   raw_fd_ostream dest(Filename, EC, sys::fs::OF_Text);
396   if (EC) {
397     *ErrorMessage = strdup(EC.message().c_str());
398     return true;
399   }
400 
401   unwrap(M)->print(dest, nullptr);
402 
403   dest.close();
404 
405   if (dest.has_error()) {
406     std::string E = "Error printing to file: " + dest.error().message();
407     *ErrorMessage = strdup(E.c_str());
408     return true;
409   }
410 
411   return false;
412 }
413 
414 char *LLVMPrintModuleToString(LLVMModuleRef M) {
415   std::string buf;
416   raw_string_ostream os(buf);
417 
418   unwrap(M)->print(os, nullptr);
419   os.flush();
420 
421   return strdup(buf.c_str());
422 }
423 
424 /*--.. Operations on inline assembler ......................................--*/
425 void LLVMSetModuleInlineAsm2(LLVMModuleRef M, const char *Asm, size_t Len) {
426   unwrap(M)->setModuleInlineAsm(StringRef(Asm, Len));
427 }
428 
429 void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
430   unwrap(M)->setModuleInlineAsm(StringRef(Asm));
431 }
432 
433 void LLVMAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm, size_t Len) {
434   unwrap(M)->appendModuleInlineAsm(StringRef(Asm, Len));
435 }
436 
437 const char *LLVMGetModuleInlineAsm(LLVMModuleRef M, size_t *Len) {
438   auto &Str = unwrap(M)->getModuleInlineAsm();
439   *Len = Str.length();
440   return Str.c_str();
441 }
442 
443 LLVMValueRef LLVMGetInlineAsm(LLVMTypeRef Ty,
444                               char *AsmString, size_t AsmStringSize,
445                               char *Constraints, size_t ConstraintsSize,
446                               LLVMBool HasSideEffects, LLVMBool IsAlignStack,
447                               LLVMInlineAsmDialect Dialect) {
448   InlineAsm::AsmDialect AD;
449   switch (Dialect) {
450   case LLVMInlineAsmDialectATT:
451     AD = InlineAsm::AD_ATT;
452     break;
453   case LLVMInlineAsmDialectIntel:
454     AD = InlineAsm::AD_Intel;
455     break;
456   }
457   return wrap(InlineAsm::get(unwrap<FunctionType>(Ty),
458                              StringRef(AsmString, AsmStringSize),
459                              StringRef(Constraints, ConstraintsSize),
460                              HasSideEffects, IsAlignStack, AD));
461 }
462 
463 
464 /*--.. Operations on module contexts ......................................--*/
465 LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M) {
466   return wrap(&unwrap(M)->getContext());
467 }
468 
469 
470 /*===-- Operations on types -----------------------------------------------===*/
471 
472 /*--.. Operations on all types (mostly) ....................................--*/
473 
474 LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty) {
475   switch (unwrap(Ty)->getTypeID()) {
476   case Type::VoidTyID:
477     return LLVMVoidTypeKind;
478   case Type::HalfTyID:
479     return LLVMHalfTypeKind;
480   case Type::FloatTyID:
481     return LLVMFloatTypeKind;
482   case Type::DoubleTyID:
483     return LLVMDoubleTypeKind;
484   case Type::X86_FP80TyID:
485     return LLVMX86_FP80TypeKind;
486   case Type::FP128TyID:
487     return LLVMFP128TypeKind;
488   case Type::PPC_FP128TyID:
489     return LLVMPPC_FP128TypeKind;
490   case Type::LabelTyID:
491     return LLVMLabelTypeKind;
492   case Type::MetadataTyID:
493     return LLVMMetadataTypeKind;
494   case Type::IntegerTyID:
495     return LLVMIntegerTypeKind;
496   case Type::FunctionTyID:
497     return LLVMFunctionTypeKind;
498   case Type::StructTyID:
499     return LLVMStructTypeKind;
500   case Type::ArrayTyID:
501     return LLVMArrayTypeKind;
502   case Type::PointerTyID:
503     return LLVMPointerTypeKind;
504   case Type::VectorTyID:
505     return LLVMVectorTypeKind;
506   case Type::X86_MMXTyID:
507     return LLVMX86_MMXTypeKind;
508   case Type::TokenTyID:
509     return LLVMTokenTypeKind;
510   }
511   llvm_unreachable("Unhandled TypeID.");
512 }
513 
514 LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty)
515 {
516     return unwrap(Ty)->isSized();
517 }
518 
519 LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty) {
520   return wrap(&unwrap(Ty)->getContext());
521 }
522 
523 void LLVMDumpType(LLVMTypeRef Ty) {
524   return unwrap(Ty)->print(errs(), /*IsForDebug=*/true);
525 }
526 
527 char *LLVMPrintTypeToString(LLVMTypeRef Ty) {
528   std::string buf;
529   raw_string_ostream os(buf);
530 
531   if (unwrap(Ty))
532     unwrap(Ty)->print(os);
533   else
534     os << "Printing <null> Type";
535 
536   os.flush();
537 
538   return strdup(buf.c_str());
539 }
540 
541 /*--.. Operations on integer types .........................................--*/
542 
543 LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C)  {
544   return (LLVMTypeRef) Type::getInt1Ty(*unwrap(C));
545 }
546 LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C)  {
547   return (LLVMTypeRef) Type::getInt8Ty(*unwrap(C));
548 }
549 LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C) {
550   return (LLVMTypeRef) Type::getInt16Ty(*unwrap(C));
551 }
552 LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C) {
553   return (LLVMTypeRef) Type::getInt32Ty(*unwrap(C));
554 }
555 LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C) {
556   return (LLVMTypeRef) Type::getInt64Ty(*unwrap(C));
557 }
558 LLVMTypeRef LLVMInt128TypeInContext(LLVMContextRef C) {
559   return (LLVMTypeRef) Type::getInt128Ty(*unwrap(C));
560 }
561 LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits) {
562   return wrap(IntegerType::get(*unwrap(C), NumBits));
563 }
564 
565 LLVMTypeRef LLVMInt1Type(void)  {
566   return LLVMInt1TypeInContext(LLVMGetGlobalContext());
567 }
568 LLVMTypeRef LLVMInt8Type(void)  {
569   return LLVMInt8TypeInContext(LLVMGetGlobalContext());
570 }
571 LLVMTypeRef LLVMInt16Type(void) {
572   return LLVMInt16TypeInContext(LLVMGetGlobalContext());
573 }
574 LLVMTypeRef LLVMInt32Type(void) {
575   return LLVMInt32TypeInContext(LLVMGetGlobalContext());
576 }
577 LLVMTypeRef LLVMInt64Type(void) {
578   return LLVMInt64TypeInContext(LLVMGetGlobalContext());
579 }
580 LLVMTypeRef LLVMInt128Type(void) {
581   return LLVMInt128TypeInContext(LLVMGetGlobalContext());
582 }
583 LLVMTypeRef LLVMIntType(unsigned NumBits) {
584   return LLVMIntTypeInContext(LLVMGetGlobalContext(), NumBits);
585 }
586 
587 unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy) {
588   return unwrap<IntegerType>(IntegerTy)->getBitWidth();
589 }
590 
591 /*--.. Operations on real types ............................................--*/
592 
593 LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C) {
594   return (LLVMTypeRef) Type::getHalfTy(*unwrap(C));
595 }
596 LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C) {
597   return (LLVMTypeRef) Type::getFloatTy(*unwrap(C));
598 }
599 LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C) {
600   return (LLVMTypeRef) Type::getDoubleTy(*unwrap(C));
601 }
602 LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C) {
603   return (LLVMTypeRef) Type::getX86_FP80Ty(*unwrap(C));
604 }
605 LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C) {
606   return (LLVMTypeRef) Type::getFP128Ty(*unwrap(C));
607 }
608 LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C) {
609   return (LLVMTypeRef) Type::getPPC_FP128Ty(*unwrap(C));
610 }
611 LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C) {
612   return (LLVMTypeRef) Type::getX86_MMXTy(*unwrap(C));
613 }
614 
615 LLVMTypeRef LLVMHalfType(void) {
616   return LLVMHalfTypeInContext(LLVMGetGlobalContext());
617 }
618 LLVMTypeRef LLVMFloatType(void) {
619   return LLVMFloatTypeInContext(LLVMGetGlobalContext());
620 }
621 LLVMTypeRef LLVMDoubleType(void) {
622   return LLVMDoubleTypeInContext(LLVMGetGlobalContext());
623 }
624 LLVMTypeRef LLVMX86FP80Type(void) {
625   return LLVMX86FP80TypeInContext(LLVMGetGlobalContext());
626 }
627 LLVMTypeRef LLVMFP128Type(void) {
628   return LLVMFP128TypeInContext(LLVMGetGlobalContext());
629 }
630 LLVMTypeRef LLVMPPCFP128Type(void) {
631   return LLVMPPCFP128TypeInContext(LLVMGetGlobalContext());
632 }
633 LLVMTypeRef LLVMX86MMXType(void) {
634   return LLVMX86MMXTypeInContext(LLVMGetGlobalContext());
635 }
636 
637 /*--.. Operations on function types ........................................--*/
638 
639 LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType,
640                              LLVMTypeRef *ParamTypes, unsigned ParamCount,
641                              LLVMBool IsVarArg) {
642   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
643   return wrap(FunctionType::get(unwrap(ReturnType), Tys, IsVarArg != 0));
644 }
645 
646 LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy) {
647   return unwrap<FunctionType>(FunctionTy)->isVarArg();
648 }
649 
650 LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy) {
651   return wrap(unwrap<FunctionType>(FunctionTy)->getReturnType());
652 }
653 
654 unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy) {
655   return unwrap<FunctionType>(FunctionTy)->getNumParams();
656 }
657 
658 void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest) {
659   FunctionType *Ty = unwrap<FunctionType>(FunctionTy);
660   for (FunctionType::param_iterator I = Ty->param_begin(),
661                                     E = Ty->param_end(); I != E; ++I)
662     *Dest++ = wrap(*I);
663 }
664 
665 /*--.. Operations on struct types ..........................................--*/
666 
667 LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,
668                            unsigned ElementCount, LLVMBool Packed) {
669   ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);
670   return wrap(StructType::get(*unwrap(C), Tys, Packed != 0));
671 }
672 
673 LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes,
674                            unsigned ElementCount, LLVMBool Packed) {
675   return LLVMStructTypeInContext(LLVMGetGlobalContext(), ElementTypes,
676                                  ElementCount, Packed);
677 }
678 
679 LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name)
680 {
681   return wrap(StructType::create(*unwrap(C), Name));
682 }
683 
684 const char *LLVMGetStructName(LLVMTypeRef Ty)
685 {
686   StructType *Type = unwrap<StructType>(Ty);
687   if (!Type->hasName())
688     return nullptr;
689   return Type->getName().data();
690 }
691 
692 void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes,
693                        unsigned ElementCount, LLVMBool Packed) {
694   ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);
695   unwrap<StructType>(StructTy)->setBody(Tys, Packed != 0);
696 }
697 
698 unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy) {
699   return unwrap<StructType>(StructTy)->getNumElements();
700 }
701 
702 void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest) {
703   StructType *Ty = unwrap<StructType>(StructTy);
704   for (StructType::element_iterator I = Ty->element_begin(),
705                                     E = Ty->element_end(); I != E; ++I)
706     *Dest++ = wrap(*I);
707 }
708 
709 LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i) {
710   StructType *Ty = unwrap<StructType>(StructTy);
711   return wrap(Ty->getTypeAtIndex(i));
712 }
713 
714 LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy) {
715   return unwrap<StructType>(StructTy)->isPacked();
716 }
717 
718 LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy) {
719   return unwrap<StructType>(StructTy)->isOpaque();
720 }
721 
722 LLVMBool LLVMIsLiteralStruct(LLVMTypeRef StructTy) {
723   return unwrap<StructType>(StructTy)->isLiteral();
724 }
725 
726 LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) {
727   return wrap(unwrap(M)->getTypeByName(Name));
728 }
729 
730 /*--.. Operations on array, pointer, and vector types (sequence types) .....--*/
731 
732 void LLVMGetSubtypes(LLVMTypeRef Tp, LLVMTypeRef *Arr) {
733     int i = 0;
734     for (auto *T : unwrap(Tp)->subtypes()) {
735         Arr[i] = wrap(T);
736         i++;
737     }
738 }
739 
740 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount) {
741   return wrap(ArrayType::get(unwrap(ElementType), ElementCount));
742 }
743 
744 LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace) {
745   return wrap(PointerType::get(unwrap(ElementType), AddressSpace));
746 }
747 
748 LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount) {
749   return wrap(VectorType::get(unwrap(ElementType), ElementCount));
750 }
751 
752 LLVMTypeRef LLVMGetElementType(LLVMTypeRef WrappedTy) {
753   auto *Ty = unwrap<Type>(WrappedTy);
754   if (auto *PTy = dyn_cast<PointerType>(Ty))
755     return wrap(PTy->getElementType());
756   if (auto *ATy = dyn_cast<ArrayType>(Ty))
757     return wrap(ATy->getElementType());
758   return wrap(cast<VectorType>(Ty)->getElementType());
759 }
760 
761 unsigned LLVMGetNumContainedTypes(LLVMTypeRef Tp) {
762     return unwrap(Tp)->getNumContainedTypes();
763 }
764 
765 unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy) {
766   return unwrap<ArrayType>(ArrayTy)->getNumElements();
767 }
768 
769 unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy) {
770   return unwrap<PointerType>(PointerTy)->getAddressSpace();
771 }
772 
773 unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy) {
774   return unwrap<VectorType>(VectorTy)->getNumElements();
775 }
776 
777 /*--.. Operations on other types ...........................................--*/
778 
779 LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C)  {
780   return wrap(Type::getVoidTy(*unwrap(C)));
781 }
782 LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C) {
783   return wrap(Type::getLabelTy(*unwrap(C)));
784 }
785 LLVMTypeRef LLVMTokenTypeInContext(LLVMContextRef C) {
786   return wrap(Type::getTokenTy(*unwrap(C)));
787 }
788 LLVMTypeRef LLVMMetadataTypeInContext(LLVMContextRef C) {
789   return wrap(Type::getMetadataTy(*unwrap(C)));
790 }
791 
792 LLVMTypeRef LLVMVoidType(void)  {
793   return LLVMVoidTypeInContext(LLVMGetGlobalContext());
794 }
795 LLVMTypeRef LLVMLabelType(void) {
796   return LLVMLabelTypeInContext(LLVMGetGlobalContext());
797 }
798 
799 /*===-- Operations on values ----------------------------------------------===*/
800 
801 /*--.. Operations on all values ............................................--*/
802 
803 LLVMTypeRef LLVMTypeOf(LLVMValueRef Val) {
804   return wrap(unwrap(Val)->getType());
805 }
806 
807 LLVMValueKind LLVMGetValueKind(LLVMValueRef Val) {
808     switch(unwrap(Val)->getValueID()) {
809 #define HANDLE_VALUE(Name) \
810   case Value::Name##Val: \
811     return LLVM##Name##ValueKind;
812 #include "llvm/IR/Value.def"
813   default:
814     return LLVMInstructionValueKind;
815   }
816 }
817 
818 const char *LLVMGetValueName2(LLVMValueRef Val, size_t *Length) {
819   auto *V = unwrap(Val);
820   *Length = V->getName().size();
821   return V->getName().data();
822 }
823 
824 void LLVMSetValueName2(LLVMValueRef Val, const char *Name, size_t NameLen) {
825   unwrap(Val)->setName(StringRef(Name, NameLen));
826 }
827 
828 const char *LLVMGetValueName(LLVMValueRef Val) {
829   return unwrap(Val)->getName().data();
830 }
831 
832 void LLVMSetValueName(LLVMValueRef Val, const char *Name) {
833   unwrap(Val)->setName(Name);
834 }
835 
836 void LLVMDumpValue(LLVMValueRef Val) {
837   unwrap(Val)->print(errs(), /*IsForDebug=*/true);
838 }
839 
840 char* LLVMPrintValueToString(LLVMValueRef Val) {
841   std::string buf;
842   raw_string_ostream os(buf);
843 
844   if (unwrap(Val))
845     unwrap(Val)->print(os);
846   else
847     os << "Printing <null> Value";
848 
849   os.flush();
850 
851   return strdup(buf.c_str());
852 }
853 
854 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {
855   unwrap(OldVal)->replaceAllUsesWith(unwrap(NewVal));
856 }
857 
858 int LLVMHasMetadata(LLVMValueRef Inst) {
859   return unwrap<Instruction>(Inst)->hasMetadata();
860 }
861 
862 LLVMValueRef LLVMGetMetadata(LLVMValueRef Inst, unsigned KindID) {
863   auto *I = unwrap<Instruction>(Inst);
864   assert(I && "Expected instruction");
865   if (auto *MD = I->getMetadata(KindID))
866     return wrap(MetadataAsValue::get(I->getContext(), MD));
867   return nullptr;
868 }
869 
870 // MetadataAsValue uses a canonical format which strips the actual MDNode for
871 // MDNode with just a single constant value, storing just a ConstantAsMetadata
872 // This undoes this canonicalization, reconstructing the MDNode.
873 static MDNode *extractMDNode(MetadataAsValue *MAV) {
874   Metadata *MD = MAV->getMetadata();
875   assert((isa<MDNode>(MD) || isa<ConstantAsMetadata>(MD)) &&
876       "Expected a metadata node or a canonicalized constant");
877 
878   if (MDNode *N = dyn_cast<MDNode>(MD))
879     return N;
880 
881   return MDNode::get(MAV->getContext(), MD);
882 }
883 
884 void LLVMSetMetadata(LLVMValueRef Inst, unsigned KindID, LLVMValueRef Val) {
885   MDNode *N = Val ? extractMDNode(unwrap<MetadataAsValue>(Val)) : nullptr;
886 
887   unwrap<Instruction>(Inst)->setMetadata(KindID, N);
888 }
889 
890 struct LLVMOpaqueValueMetadataEntry {
891   unsigned Kind;
892   LLVMMetadataRef Metadata;
893 };
894 
895 using MetadataEntries = SmallVectorImpl<std::pair<unsigned, MDNode *>>;
896 static LLVMValueMetadataEntry *
897 llvm_getMetadata(size_t *NumEntries,
898                  llvm::function_ref<void(MetadataEntries &)> AccessMD) {
899   SmallVector<std::pair<unsigned, MDNode *>, 8> MVEs;
900   AccessMD(MVEs);
901 
902   LLVMOpaqueValueMetadataEntry *Result =
903   static_cast<LLVMOpaqueValueMetadataEntry *>(
904                                               safe_malloc(MVEs.size() * sizeof(LLVMOpaqueValueMetadataEntry)));
905   for (unsigned i = 0; i < MVEs.size(); ++i) {
906     const auto &ModuleFlag = MVEs[i];
907     Result[i].Kind = ModuleFlag.first;
908     Result[i].Metadata = wrap(ModuleFlag.second);
909   }
910   *NumEntries = MVEs.size();
911   return Result;
912 }
913 
914 LLVMValueMetadataEntry *
915 LLVMInstructionGetAllMetadataOtherThanDebugLoc(LLVMValueRef Value,
916                                                size_t *NumEntries) {
917   return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {
918     unwrap<Instruction>(Value)->getAllMetadata(Entries);
919   });
920 }
921 
922 /*--.. Conversion functions ................................................--*/
923 
924 #define LLVM_DEFINE_VALUE_CAST(name)                                       \
925   LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                           \
926     return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \
927   }
928 
929 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)
930 
931 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {
932   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
933     if (isa<MDNode>(MD->getMetadata()) ||
934         isa<ValueAsMetadata>(MD->getMetadata()))
935       return Val;
936   return nullptr;
937 }
938 
939 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) {
940   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
941     if (isa<MDString>(MD->getMetadata()))
942       return Val;
943   return nullptr;
944 }
945 
946 /*--.. Operations on Uses ..................................................--*/
947 LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val) {
948   Value *V = unwrap(Val);
949   Value::use_iterator I = V->use_begin();
950   if (I == V->use_end())
951     return nullptr;
952   return wrap(&*I);
953 }
954 
955 LLVMUseRef LLVMGetNextUse(LLVMUseRef U) {
956   Use *Next = unwrap(U)->getNext();
957   if (Next)
958     return wrap(Next);
959   return nullptr;
960 }
961 
962 LLVMValueRef LLVMGetUser(LLVMUseRef U) {
963   return wrap(unwrap(U)->getUser());
964 }
965 
966 LLVMValueRef LLVMGetUsedValue(LLVMUseRef U) {
967   return wrap(unwrap(U)->get());
968 }
969 
970 /*--.. Operations on Users .................................................--*/
971 
972 static LLVMValueRef getMDNodeOperandImpl(LLVMContext &Context, const MDNode *N,
973                                          unsigned Index) {
974   Metadata *Op = N->getOperand(Index);
975   if (!Op)
976     return nullptr;
977   if (auto *C = dyn_cast<ConstantAsMetadata>(Op))
978     return wrap(C->getValue());
979   return wrap(MetadataAsValue::get(Context, Op));
980 }
981 
982 LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index) {
983   Value *V = unwrap(Val);
984   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
985     if (auto *L = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
986       assert(Index == 0 && "Function-local metadata can only have one operand");
987       return wrap(L->getValue());
988     }
989     return getMDNodeOperandImpl(V->getContext(),
990                                 cast<MDNode>(MD->getMetadata()), Index);
991   }
992 
993   return wrap(cast<User>(V)->getOperand(Index));
994 }
995 
996 LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index) {
997   Value *V = unwrap(Val);
998   return wrap(&cast<User>(V)->getOperandUse(Index));
999 }
1000 
1001 void LLVMSetOperand(LLVMValueRef Val, unsigned Index, LLVMValueRef Op) {
1002   unwrap<User>(Val)->setOperand(Index, unwrap(Op));
1003 }
1004 
1005 int LLVMGetNumOperands(LLVMValueRef Val) {
1006   Value *V = unwrap(Val);
1007   if (isa<MetadataAsValue>(V))
1008     return LLVMGetMDNodeNumOperands(Val);
1009 
1010   return cast<User>(V)->getNumOperands();
1011 }
1012 
1013 /*--.. Operations on constants of any type .................................--*/
1014 
1015 LLVMValueRef LLVMConstNull(LLVMTypeRef Ty) {
1016   return wrap(Constant::getNullValue(unwrap(Ty)));
1017 }
1018 
1019 LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty) {
1020   return wrap(Constant::getAllOnesValue(unwrap(Ty)));
1021 }
1022 
1023 LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty) {
1024   return wrap(UndefValue::get(unwrap(Ty)));
1025 }
1026 
1027 LLVMBool LLVMIsConstant(LLVMValueRef Ty) {
1028   return isa<Constant>(unwrap(Ty));
1029 }
1030 
1031 LLVMBool LLVMIsNull(LLVMValueRef Val) {
1032   if (Constant *C = dyn_cast<Constant>(unwrap(Val)))
1033     return C->isNullValue();
1034   return false;
1035 }
1036 
1037 LLVMBool LLVMIsUndef(LLVMValueRef Val) {
1038   return isa<UndefValue>(unwrap(Val));
1039 }
1040 
1041 LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty) {
1042   return wrap(ConstantPointerNull::get(unwrap<PointerType>(Ty)));
1043 }
1044 
1045 /*--.. Operations on metadata nodes ........................................--*/
1046 
1047 LLVMMetadataRef LLVMMDStringInContext2(LLVMContextRef C, const char *Str,
1048                                        size_t SLen) {
1049   return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen)));
1050 }
1051 
1052 LLVMMetadataRef LLVMMDNodeInContext2(LLVMContextRef C, LLVMMetadataRef *MDs,
1053                                      size_t Count) {
1054   return wrap(MDNode::get(*unwrap(C), ArrayRef<Metadata*>(unwrap(MDs), Count)));
1055 }
1056 
1057 LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
1058                                    unsigned SLen) {
1059   LLVMContext &Context = *unwrap(C);
1060   return wrap(MetadataAsValue::get(
1061       Context, MDString::get(Context, StringRef(Str, SLen))));
1062 }
1063 
1064 LLVMValueRef LLVMMDString(const char *Str, unsigned SLen) {
1065   return LLVMMDStringInContext(LLVMGetGlobalContext(), Str, SLen);
1066 }
1067 
1068 LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
1069                                  unsigned Count) {
1070   LLVMContext &Context = *unwrap(C);
1071   SmallVector<Metadata *, 8> MDs;
1072   for (auto *OV : makeArrayRef(Vals, Count)) {
1073     Value *V = unwrap(OV);
1074     Metadata *MD;
1075     if (!V)
1076       MD = nullptr;
1077     else if (auto *C = dyn_cast<Constant>(V))
1078       MD = ConstantAsMetadata::get(C);
1079     else if (auto *MDV = dyn_cast<MetadataAsValue>(V)) {
1080       MD = MDV->getMetadata();
1081       assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata "
1082                                           "outside of direct argument to call");
1083     } else {
1084       // This is function-local metadata.  Pretend to make an MDNode.
1085       assert(Count == 1 &&
1086              "Expected only one operand to function-local metadata");
1087       return wrap(MetadataAsValue::get(Context, LocalAsMetadata::get(V)));
1088     }
1089 
1090     MDs.push_back(MD);
1091   }
1092   return wrap(MetadataAsValue::get(Context, MDNode::get(Context, MDs)));
1093 }
1094 
1095 LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count) {
1096   return LLVMMDNodeInContext(LLVMGetGlobalContext(), Vals, Count);
1097 }
1098 
1099 LLVMValueRef LLVMMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
1100   return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
1101 }
1102 
1103 LLVMMetadataRef LLVMValueAsMetadata(LLVMValueRef Val) {
1104   auto *V = unwrap(Val);
1105   if (auto *C = dyn_cast<Constant>(V))
1106     return wrap(ConstantAsMetadata::get(C));
1107   if (auto *MAV = dyn_cast<MetadataAsValue>(V))
1108     return wrap(MAV->getMetadata());
1109   return wrap(ValueAsMetadata::get(V));
1110 }
1111 
1112 const char *LLVMGetMDString(LLVMValueRef V, unsigned *Length) {
1113   if (const auto *MD = dyn_cast<MetadataAsValue>(unwrap(V)))
1114     if (const MDString *S = dyn_cast<MDString>(MD->getMetadata())) {
1115       *Length = S->getString().size();
1116       return S->getString().data();
1117     }
1118   *Length = 0;
1119   return nullptr;
1120 }
1121 
1122 unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V) {
1123   auto *MD = cast<MetadataAsValue>(unwrap(V));
1124   if (isa<ValueAsMetadata>(MD->getMetadata()))
1125     return 1;
1126   return cast<MDNode>(MD->getMetadata())->getNumOperands();
1127 }
1128 
1129 LLVMNamedMDNodeRef LLVMGetFirstNamedMetadata(LLVMModuleRef M) {
1130   Module *Mod = unwrap(M);
1131   Module::named_metadata_iterator I = Mod->named_metadata_begin();
1132   if (I == Mod->named_metadata_end())
1133     return nullptr;
1134   return wrap(&*I);
1135 }
1136 
1137 LLVMNamedMDNodeRef LLVMGetLastNamedMetadata(LLVMModuleRef M) {
1138   Module *Mod = unwrap(M);
1139   Module::named_metadata_iterator I = Mod->named_metadata_end();
1140   if (I == Mod->named_metadata_begin())
1141     return nullptr;
1142   return wrap(&*--I);
1143 }
1144 
1145 LLVMNamedMDNodeRef LLVMGetNextNamedMetadata(LLVMNamedMDNodeRef NMD) {
1146   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1147   Module::named_metadata_iterator I(NamedNode);
1148   if (++I == NamedNode->getParent()->named_metadata_end())
1149     return nullptr;
1150   return wrap(&*I);
1151 }
1152 
1153 LLVMNamedMDNodeRef LLVMGetPreviousNamedMetadata(LLVMNamedMDNodeRef NMD) {
1154   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1155   Module::named_metadata_iterator I(NamedNode);
1156   if (I == NamedNode->getParent()->named_metadata_begin())
1157     return nullptr;
1158   return wrap(&*--I);
1159 }
1160 
1161 LLVMNamedMDNodeRef LLVMGetNamedMetadata(LLVMModuleRef M,
1162                                         const char *Name, size_t NameLen) {
1163   return wrap(unwrap(M)->getNamedMetadata(StringRef(Name, NameLen)));
1164 }
1165 
1166 LLVMNamedMDNodeRef LLVMGetOrInsertNamedMetadata(LLVMModuleRef M,
1167                                                 const char *Name, size_t NameLen) {
1168   return wrap(unwrap(M)->getOrInsertNamedMetadata({Name, NameLen}));
1169 }
1170 
1171 const char *LLVMGetNamedMetadataName(LLVMNamedMDNodeRef NMD, size_t *NameLen) {
1172   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1173   *NameLen = NamedNode->getName().size();
1174   return NamedNode->getName().data();
1175 }
1176 
1177 void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest) {
1178   auto *MD = cast<MetadataAsValue>(unwrap(V));
1179   if (auto *MDV = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
1180     *Dest = wrap(MDV->getValue());
1181     return;
1182   }
1183   const auto *N = cast<MDNode>(MD->getMetadata());
1184   const unsigned numOperands = N->getNumOperands();
1185   LLVMContext &Context = unwrap(V)->getContext();
1186   for (unsigned i = 0; i < numOperands; i++)
1187     Dest[i] = getMDNodeOperandImpl(Context, N, i);
1188 }
1189 
1190 unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char *Name) {
1191   if (NamedMDNode *N = unwrap(M)->getNamedMetadata(Name)) {
1192     return N->getNumOperands();
1193   }
1194   return 0;
1195 }
1196 
1197 void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char *Name,
1198                                   LLVMValueRef *Dest) {
1199   NamedMDNode *N = unwrap(M)->getNamedMetadata(Name);
1200   if (!N)
1201     return;
1202   LLVMContext &Context = unwrap(M)->getContext();
1203   for (unsigned i=0;i<N->getNumOperands();i++)
1204     Dest[i] = wrap(MetadataAsValue::get(Context, N->getOperand(i)));
1205 }
1206 
1207 void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name,
1208                                  LLVMValueRef Val) {
1209   NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(Name);
1210   if (!N)
1211     return;
1212   if (!Val)
1213     return;
1214   N->addOperand(extractMDNode(unwrap<MetadataAsValue>(Val)));
1215 }
1216 
1217 const char *LLVMGetDebugLocDirectory(LLVMValueRef Val, unsigned *Length) {
1218   if (!Length) return nullptr;
1219   StringRef S;
1220   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1221     if (const auto &DL = I->getDebugLoc()) {
1222       S = DL->getDirectory();
1223     }
1224   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1225     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1226     GV->getDebugInfo(GVEs);
1227     if (GVEs.size())
1228       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1229         S = DGV->getDirectory();
1230   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1231     if (const DISubprogram *DSP = F->getSubprogram())
1232       S = DSP->getDirectory();
1233   } else {
1234     assert(0 && "Expected Instruction, GlobalVariable or Function");
1235     return nullptr;
1236   }
1237   *Length = S.size();
1238   return S.data();
1239 }
1240 
1241 const char *LLVMGetDebugLocFilename(LLVMValueRef Val, unsigned *Length) {
1242   if (!Length) return nullptr;
1243   StringRef S;
1244   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1245     if (const auto &DL = I->getDebugLoc()) {
1246       S = DL->getFilename();
1247     }
1248   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1249     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1250     GV->getDebugInfo(GVEs);
1251     if (GVEs.size())
1252       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1253         S = DGV->getFilename();
1254   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1255     if (const DISubprogram *DSP = F->getSubprogram())
1256       S = DSP->getFilename();
1257   } else {
1258     assert(0 && "Expected Instruction, GlobalVariable or Function");
1259     return nullptr;
1260   }
1261   *Length = S.size();
1262   return S.data();
1263 }
1264 
1265 unsigned LLVMGetDebugLocLine(LLVMValueRef Val) {
1266   unsigned L = 0;
1267   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1268     if (const auto &DL = I->getDebugLoc()) {
1269       L = DL->getLine();
1270     }
1271   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1272     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1273     GV->getDebugInfo(GVEs);
1274     if (GVEs.size())
1275       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1276         L = DGV->getLine();
1277   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1278     if (const DISubprogram *DSP = F->getSubprogram())
1279       L = DSP->getLine();
1280   } else {
1281     assert(0 && "Expected Instruction, GlobalVariable or Function");
1282     return -1;
1283   }
1284   return L;
1285 }
1286 
1287 unsigned LLVMGetDebugLocColumn(LLVMValueRef Val) {
1288   unsigned C = 0;
1289   if (const auto *I = dyn_cast<Instruction>(unwrap(Val)))
1290     if (const auto &DL = I->getDebugLoc())
1291       C = DL->getColumn();
1292   return C;
1293 }
1294 
1295 /*--.. Operations on scalar constants ......................................--*/
1296 
1297 LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
1298                           LLVMBool SignExtend) {
1299   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), N, SignExtend != 0));
1300 }
1301 
1302 LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,
1303                                               unsigned NumWords,
1304                                               const uint64_t Words[]) {
1305     IntegerType *Ty = unwrap<IntegerType>(IntTy);
1306     return wrap(ConstantInt::get(Ty->getContext(),
1307                                  APInt(Ty->getBitWidth(),
1308                                        makeArrayRef(Words, NumWords))));
1309 }
1310 
1311 LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char Str[],
1312                                   uint8_t Radix) {
1313   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str),
1314                                Radix));
1315 }
1316 
1317 LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char Str[],
1318                                          unsigned SLen, uint8_t Radix) {
1319   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str, SLen),
1320                                Radix));
1321 }
1322 
1323 LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N) {
1324   return wrap(ConstantFP::get(unwrap(RealTy), N));
1325 }
1326 
1327 LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text) {
1328   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Text)));
1329 }
1330 
1331 LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char Str[],
1332                                           unsigned SLen) {
1333   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Str, SLen)));
1334 }
1335 
1336 unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal) {
1337   return unwrap<ConstantInt>(ConstantVal)->getZExtValue();
1338 }
1339 
1340 long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal) {
1341   return unwrap<ConstantInt>(ConstantVal)->getSExtValue();
1342 }
1343 
1344 double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *LosesInfo) {
1345   ConstantFP *cFP = unwrap<ConstantFP>(ConstantVal) ;
1346   Type *Ty = cFP->getType();
1347 
1348   if (Ty->isFloatTy()) {
1349     *LosesInfo = false;
1350     return cFP->getValueAPF().convertToFloat();
1351   }
1352 
1353   if (Ty->isDoubleTy()) {
1354     *LosesInfo = false;
1355     return cFP->getValueAPF().convertToDouble();
1356   }
1357 
1358   bool APFLosesInfo;
1359   APFloat APF = cFP->getValueAPF();
1360   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &APFLosesInfo);
1361   *LosesInfo = APFLosesInfo;
1362   return APF.convertToDouble();
1363 }
1364 
1365 /*--.. Operations on composite constants ...................................--*/
1366 
1367 LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,
1368                                       unsigned Length,
1369                                       LLVMBool DontNullTerminate) {
1370   /* Inverted the sense of AddNull because ', 0)' is a
1371      better mnemonic for null termination than ', 1)'. */
1372   return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),
1373                                            DontNullTerminate == 0));
1374 }
1375 
1376 LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
1377                              LLVMBool DontNullTerminate) {
1378   return LLVMConstStringInContext(LLVMGetGlobalContext(), Str, Length,
1379                                   DontNullTerminate);
1380 }
1381 
1382 LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx) {
1383   return wrap(unwrap<ConstantDataSequential>(C)->getElementAsConstant(idx));
1384 }
1385 
1386 LLVMBool LLVMIsConstantString(LLVMValueRef C) {
1387   return unwrap<ConstantDataSequential>(C)->isString();
1388 }
1389 
1390 const char *LLVMGetAsString(LLVMValueRef C, size_t *Length) {
1391   StringRef Str = unwrap<ConstantDataSequential>(C)->getAsString();
1392   *Length = Str.size();
1393   return Str.data();
1394 }
1395 
1396 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
1397                             LLVMValueRef *ConstantVals, unsigned Length) {
1398   ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length);
1399   return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));
1400 }
1401 
1402 LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
1403                                       LLVMValueRef *ConstantVals,
1404                                       unsigned Count, LLVMBool Packed) {
1405   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1406   return wrap(ConstantStruct::getAnon(*unwrap(C), makeArrayRef(Elements, Count),
1407                                       Packed != 0));
1408 }
1409 
1410 LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
1411                              LLVMBool Packed) {
1412   return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count,
1413                                   Packed);
1414 }
1415 
1416 LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
1417                                   LLVMValueRef *ConstantVals,
1418                                   unsigned Count) {
1419   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1420   StructType *Ty = cast<StructType>(unwrap(StructTy));
1421 
1422   return wrap(ConstantStruct::get(Ty, makeArrayRef(Elements, Count)));
1423 }
1424 
1425 LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) {
1426   return wrap(ConstantVector::get(makeArrayRef(
1427                             unwrap<Constant>(ScalarConstantVals, Size), Size)));
1428 }
1429 
1430 /*-- Opcode mapping */
1431 
1432 static LLVMOpcode map_to_llvmopcode(int opcode)
1433 {
1434     switch (opcode) {
1435       default: llvm_unreachable("Unhandled Opcode.");
1436 #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;
1437 #include "llvm/IR/Instruction.def"
1438 #undef HANDLE_INST
1439     }
1440 }
1441 
1442 static int map_from_llvmopcode(LLVMOpcode code)
1443 {
1444     switch (code) {
1445 #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;
1446 #include "llvm/IR/Instruction.def"
1447 #undef HANDLE_INST
1448     }
1449     llvm_unreachable("Unhandled Opcode.");
1450 }
1451 
1452 /*--.. Constant expressions ................................................--*/
1453 
1454 LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) {
1455   return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode());
1456 }
1457 
1458 LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) {
1459   return wrap(ConstantExpr::getAlignOf(unwrap(Ty)));
1460 }
1461 
1462 LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) {
1463   return wrap(ConstantExpr::getSizeOf(unwrap(Ty)));
1464 }
1465 
1466 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) {
1467   return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));
1468 }
1469 
1470 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) {
1471   return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal)));
1472 }
1473 
1474 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) {
1475   return wrap(ConstantExpr::getNUWNeg(unwrap<Constant>(ConstantVal)));
1476 }
1477 
1478 
1479 LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal) {
1480   return wrap(ConstantExpr::getFNeg(unwrap<Constant>(ConstantVal)));
1481 }
1482 
1483 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) {
1484   return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal)));
1485 }
1486 
1487 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1488   return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant),
1489                                    unwrap<Constant>(RHSConstant)));
1490 }
1491 
1492 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant,
1493                              LLVMValueRef RHSConstant) {
1494   return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant),
1495                                       unwrap<Constant>(RHSConstant)));
1496 }
1497 
1498 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant,
1499                              LLVMValueRef RHSConstant) {
1500   return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant),
1501                                       unwrap<Constant>(RHSConstant)));
1502 }
1503 
1504 LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1505   return wrap(ConstantExpr::getFAdd(unwrap<Constant>(LHSConstant),
1506                                     unwrap<Constant>(RHSConstant)));
1507 }
1508 
1509 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1510   return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant),
1511                                    unwrap<Constant>(RHSConstant)));
1512 }
1513 
1514 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant,
1515                              LLVMValueRef RHSConstant) {
1516   return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant),
1517                                       unwrap<Constant>(RHSConstant)));
1518 }
1519 
1520 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant,
1521                              LLVMValueRef RHSConstant) {
1522   return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant),
1523                                       unwrap<Constant>(RHSConstant)));
1524 }
1525 
1526 LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1527   return wrap(ConstantExpr::getFSub(unwrap<Constant>(LHSConstant),
1528                                     unwrap<Constant>(RHSConstant)));
1529 }
1530 
1531 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1532   return wrap(ConstantExpr::getMul(unwrap<Constant>(LHSConstant),
1533                                    unwrap<Constant>(RHSConstant)));
1534 }
1535 
1536 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant,
1537                              LLVMValueRef RHSConstant) {
1538   return wrap(ConstantExpr::getNSWMul(unwrap<Constant>(LHSConstant),
1539                                       unwrap<Constant>(RHSConstant)));
1540 }
1541 
1542 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant,
1543                              LLVMValueRef RHSConstant) {
1544   return wrap(ConstantExpr::getNUWMul(unwrap<Constant>(LHSConstant),
1545                                       unwrap<Constant>(RHSConstant)));
1546 }
1547 
1548 LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1549   return wrap(ConstantExpr::getFMul(unwrap<Constant>(LHSConstant),
1550                                     unwrap<Constant>(RHSConstant)));
1551 }
1552 
1553 LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1554   return wrap(ConstantExpr::getUDiv(unwrap<Constant>(LHSConstant),
1555                                     unwrap<Constant>(RHSConstant)));
1556 }
1557 
1558 LLVMValueRef LLVMConstExactUDiv(LLVMValueRef LHSConstant,
1559                                 LLVMValueRef RHSConstant) {
1560   return wrap(ConstantExpr::getExactUDiv(unwrap<Constant>(LHSConstant),
1561                                          unwrap<Constant>(RHSConstant)));
1562 }
1563 
1564 LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1565   return wrap(ConstantExpr::getSDiv(unwrap<Constant>(LHSConstant),
1566                                     unwrap<Constant>(RHSConstant)));
1567 }
1568 
1569 LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant,
1570                                 LLVMValueRef RHSConstant) {
1571   return wrap(ConstantExpr::getExactSDiv(unwrap<Constant>(LHSConstant),
1572                                          unwrap<Constant>(RHSConstant)));
1573 }
1574 
1575 LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1576   return wrap(ConstantExpr::getFDiv(unwrap<Constant>(LHSConstant),
1577                                     unwrap<Constant>(RHSConstant)));
1578 }
1579 
1580 LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1581   return wrap(ConstantExpr::getURem(unwrap<Constant>(LHSConstant),
1582                                     unwrap<Constant>(RHSConstant)));
1583 }
1584 
1585 LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1586   return wrap(ConstantExpr::getSRem(unwrap<Constant>(LHSConstant),
1587                                     unwrap<Constant>(RHSConstant)));
1588 }
1589 
1590 LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1591   return wrap(ConstantExpr::getFRem(unwrap<Constant>(LHSConstant),
1592                                     unwrap<Constant>(RHSConstant)));
1593 }
1594 
1595 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1596   return wrap(ConstantExpr::getAnd(unwrap<Constant>(LHSConstant),
1597                                    unwrap<Constant>(RHSConstant)));
1598 }
1599 
1600 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1601   return wrap(ConstantExpr::getOr(unwrap<Constant>(LHSConstant),
1602                                   unwrap<Constant>(RHSConstant)));
1603 }
1604 
1605 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1606   return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant),
1607                                    unwrap<Constant>(RHSConstant)));
1608 }
1609 
1610 LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate,
1611                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1612   return wrap(ConstantExpr::getICmp(Predicate,
1613                                     unwrap<Constant>(LHSConstant),
1614                                     unwrap<Constant>(RHSConstant)));
1615 }
1616 
1617 LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
1618                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1619   return wrap(ConstantExpr::getFCmp(Predicate,
1620                                     unwrap<Constant>(LHSConstant),
1621                                     unwrap<Constant>(RHSConstant)));
1622 }
1623 
1624 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1625   return wrap(ConstantExpr::getShl(unwrap<Constant>(LHSConstant),
1626                                    unwrap<Constant>(RHSConstant)));
1627 }
1628 
1629 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1630   return wrap(ConstantExpr::getLShr(unwrap<Constant>(LHSConstant),
1631                                     unwrap<Constant>(RHSConstant)));
1632 }
1633 
1634 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1635   return wrap(ConstantExpr::getAShr(unwrap<Constant>(LHSConstant),
1636                                     unwrap<Constant>(RHSConstant)));
1637 }
1638 
1639 LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
1640                           LLVMValueRef *ConstantIndices, unsigned NumIndices) {
1641   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1642                                NumIndices);
1643   Constant *Val = unwrap<Constant>(ConstantVal);
1644   Type *Ty =
1645       cast<PointerType>(Val->getType()->getScalarType())->getElementType();
1646   return wrap(ConstantExpr::getGetElementPtr(Ty, Val, IdxList));
1647 }
1648 
1649 LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
1650                                   LLVMValueRef *ConstantIndices,
1651                                   unsigned NumIndices) {
1652   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1653                                NumIndices);
1654   Constant *Val = unwrap<Constant>(ConstantVal);
1655   Type *Ty =
1656       cast<PointerType>(Val->getType()->getScalarType())->getElementType();
1657   return wrap(ConstantExpr::getInBoundsGetElementPtr(Ty, Val, IdxList));
1658 }
1659 
1660 LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1661   return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal),
1662                                      unwrap(ToType)));
1663 }
1664 
1665 LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1666   return wrap(ConstantExpr::getSExt(unwrap<Constant>(ConstantVal),
1667                                     unwrap(ToType)));
1668 }
1669 
1670 LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1671   return wrap(ConstantExpr::getZExt(unwrap<Constant>(ConstantVal),
1672                                     unwrap(ToType)));
1673 }
1674 
1675 LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1676   return wrap(ConstantExpr::getFPTrunc(unwrap<Constant>(ConstantVal),
1677                                        unwrap(ToType)));
1678 }
1679 
1680 LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1681   return wrap(ConstantExpr::getFPExtend(unwrap<Constant>(ConstantVal),
1682                                         unwrap(ToType)));
1683 }
1684 
1685 LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1686   return wrap(ConstantExpr::getUIToFP(unwrap<Constant>(ConstantVal),
1687                                       unwrap(ToType)));
1688 }
1689 
1690 LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1691   return wrap(ConstantExpr::getSIToFP(unwrap<Constant>(ConstantVal),
1692                                       unwrap(ToType)));
1693 }
1694 
1695 LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1696   return wrap(ConstantExpr::getFPToUI(unwrap<Constant>(ConstantVal),
1697                                       unwrap(ToType)));
1698 }
1699 
1700 LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1701   return wrap(ConstantExpr::getFPToSI(unwrap<Constant>(ConstantVal),
1702                                       unwrap(ToType)));
1703 }
1704 
1705 LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1706   return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal),
1707                                         unwrap(ToType)));
1708 }
1709 
1710 LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1711   return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal),
1712                                         unwrap(ToType)));
1713 }
1714 
1715 LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1716   return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal),
1717                                        unwrap(ToType)));
1718 }
1719 
1720 LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal,
1721                                     LLVMTypeRef ToType) {
1722   return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal),
1723                                              unwrap(ToType)));
1724 }
1725 
1726 LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal,
1727                                     LLVMTypeRef ToType) {
1728   return wrap(ConstantExpr::getZExtOrBitCast(unwrap<Constant>(ConstantVal),
1729                                              unwrap(ToType)));
1730 }
1731 
1732 LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal,
1733                                     LLVMTypeRef ToType) {
1734   return wrap(ConstantExpr::getSExtOrBitCast(unwrap<Constant>(ConstantVal),
1735                                              unwrap(ToType)));
1736 }
1737 
1738 LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,
1739                                      LLVMTypeRef ToType) {
1740   return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal),
1741                                               unwrap(ToType)));
1742 }
1743 
1744 LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
1745                                   LLVMTypeRef ToType) {
1746   return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal),
1747                                            unwrap(ToType)));
1748 }
1749 
1750 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
1751                               LLVMBool isSigned) {
1752   return wrap(ConstantExpr::getIntegerCast(unwrap<Constant>(ConstantVal),
1753                                            unwrap(ToType), isSigned));
1754 }
1755 
1756 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1757   return wrap(ConstantExpr::getFPCast(unwrap<Constant>(ConstantVal),
1758                                       unwrap(ToType)));
1759 }
1760 
1761 LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
1762                              LLVMValueRef ConstantIfTrue,
1763                              LLVMValueRef ConstantIfFalse) {
1764   return wrap(ConstantExpr::getSelect(unwrap<Constant>(ConstantCondition),
1765                                       unwrap<Constant>(ConstantIfTrue),
1766                                       unwrap<Constant>(ConstantIfFalse)));
1767 }
1768 
1769 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
1770                                      LLVMValueRef IndexConstant) {
1771   return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant),
1772                                               unwrap<Constant>(IndexConstant)));
1773 }
1774 
1775 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
1776                                     LLVMValueRef ElementValueConstant,
1777                                     LLVMValueRef IndexConstant) {
1778   return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant),
1779                                          unwrap<Constant>(ElementValueConstant),
1780                                              unwrap<Constant>(IndexConstant)));
1781 }
1782 
1783 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
1784                                     LLVMValueRef VectorBConstant,
1785                                     LLVMValueRef MaskConstant) {
1786   SmallVector<int, 16> IntMask;
1787   ShuffleVectorInst::getShuffleMask(unwrap<Constant>(MaskConstant), IntMask);
1788   return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant),
1789                                              unwrap<Constant>(VectorBConstant),
1790                                              IntMask));
1791 }
1792 
1793 LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList,
1794                                    unsigned NumIdx) {
1795   return wrap(ConstantExpr::getExtractValue(unwrap<Constant>(AggConstant),
1796                                             makeArrayRef(IdxList, NumIdx)));
1797 }
1798 
1799 LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant,
1800                                   LLVMValueRef ElementValueConstant,
1801                                   unsigned *IdxList, unsigned NumIdx) {
1802   return wrap(ConstantExpr::getInsertValue(unwrap<Constant>(AggConstant),
1803                                          unwrap<Constant>(ElementValueConstant),
1804                                            makeArrayRef(IdxList, NumIdx)));
1805 }
1806 
1807 LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString,
1808                                 const char *Constraints,
1809                                 LLVMBool HasSideEffects,
1810                                 LLVMBool IsAlignStack) {
1811   return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString,
1812                              Constraints, HasSideEffects, IsAlignStack));
1813 }
1814 
1815 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) {
1816   return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB)));
1817 }
1818 
1819 /*--.. Operations on global variables, functions, and aliases (globals) ....--*/
1820 
1821 LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) {
1822   return wrap(unwrap<GlobalValue>(Global)->getParent());
1823 }
1824 
1825 LLVMBool LLVMIsDeclaration(LLVMValueRef Global) {
1826   return unwrap<GlobalValue>(Global)->isDeclaration();
1827 }
1828 
1829 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {
1830   switch (unwrap<GlobalValue>(Global)->getLinkage()) {
1831   case GlobalValue::ExternalLinkage:
1832     return LLVMExternalLinkage;
1833   case GlobalValue::AvailableExternallyLinkage:
1834     return LLVMAvailableExternallyLinkage;
1835   case GlobalValue::LinkOnceAnyLinkage:
1836     return LLVMLinkOnceAnyLinkage;
1837   case GlobalValue::LinkOnceODRLinkage:
1838     return LLVMLinkOnceODRLinkage;
1839   case GlobalValue::WeakAnyLinkage:
1840     return LLVMWeakAnyLinkage;
1841   case GlobalValue::WeakODRLinkage:
1842     return LLVMWeakODRLinkage;
1843   case GlobalValue::AppendingLinkage:
1844     return LLVMAppendingLinkage;
1845   case GlobalValue::InternalLinkage:
1846     return LLVMInternalLinkage;
1847   case GlobalValue::PrivateLinkage:
1848     return LLVMPrivateLinkage;
1849   case GlobalValue::ExternalWeakLinkage:
1850     return LLVMExternalWeakLinkage;
1851   case GlobalValue::CommonLinkage:
1852     return LLVMCommonLinkage;
1853   }
1854 
1855   llvm_unreachable("Invalid GlobalValue linkage!");
1856 }
1857 
1858 void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {
1859   GlobalValue *GV = unwrap<GlobalValue>(Global);
1860 
1861   switch (Linkage) {
1862   case LLVMExternalLinkage:
1863     GV->setLinkage(GlobalValue::ExternalLinkage);
1864     break;
1865   case LLVMAvailableExternallyLinkage:
1866     GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1867     break;
1868   case LLVMLinkOnceAnyLinkage:
1869     GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
1870     break;
1871   case LLVMLinkOnceODRLinkage:
1872     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
1873     break;
1874   case LLVMLinkOnceODRAutoHideLinkage:
1875     LLVM_DEBUG(
1876         errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no "
1877                   "longer supported.");
1878     break;
1879   case LLVMWeakAnyLinkage:
1880     GV->setLinkage(GlobalValue::WeakAnyLinkage);
1881     break;
1882   case LLVMWeakODRLinkage:
1883     GV->setLinkage(GlobalValue::WeakODRLinkage);
1884     break;
1885   case LLVMAppendingLinkage:
1886     GV->setLinkage(GlobalValue::AppendingLinkage);
1887     break;
1888   case LLVMInternalLinkage:
1889     GV->setLinkage(GlobalValue::InternalLinkage);
1890     break;
1891   case LLVMPrivateLinkage:
1892     GV->setLinkage(GlobalValue::PrivateLinkage);
1893     break;
1894   case LLVMLinkerPrivateLinkage:
1895     GV->setLinkage(GlobalValue::PrivateLinkage);
1896     break;
1897   case LLVMLinkerPrivateWeakLinkage:
1898     GV->setLinkage(GlobalValue::PrivateLinkage);
1899     break;
1900   case LLVMDLLImportLinkage:
1901     LLVM_DEBUG(
1902         errs()
1903         << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported.");
1904     break;
1905   case LLVMDLLExportLinkage:
1906     LLVM_DEBUG(
1907         errs()
1908         << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported.");
1909     break;
1910   case LLVMExternalWeakLinkage:
1911     GV->setLinkage(GlobalValue::ExternalWeakLinkage);
1912     break;
1913   case LLVMGhostLinkage:
1914     LLVM_DEBUG(
1915         errs() << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");
1916     break;
1917   case LLVMCommonLinkage:
1918     GV->setLinkage(GlobalValue::CommonLinkage);
1919     break;
1920   }
1921 }
1922 
1923 const char *LLVMGetSection(LLVMValueRef Global) {
1924   // Using .data() is safe because of how GlobalObject::setSection is
1925   // implemented.
1926   return unwrap<GlobalValue>(Global)->getSection().data();
1927 }
1928 
1929 void LLVMSetSection(LLVMValueRef Global, const char *Section) {
1930   unwrap<GlobalObject>(Global)->setSection(Section);
1931 }
1932 
1933 LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) {
1934   return static_cast<LLVMVisibility>(
1935     unwrap<GlobalValue>(Global)->getVisibility());
1936 }
1937 
1938 void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) {
1939   unwrap<GlobalValue>(Global)
1940     ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz));
1941 }
1942 
1943 LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) {
1944   return static_cast<LLVMDLLStorageClass>(
1945       unwrap<GlobalValue>(Global)->getDLLStorageClass());
1946 }
1947 
1948 void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) {
1949   unwrap<GlobalValue>(Global)->setDLLStorageClass(
1950       static_cast<GlobalValue::DLLStorageClassTypes>(Class));
1951 }
1952 
1953 LLVMUnnamedAddr LLVMGetUnnamedAddress(LLVMValueRef Global) {
1954   switch (unwrap<GlobalValue>(Global)->getUnnamedAddr()) {
1955   case GlobalVariable::UnnamedAddr::None:
1956     return LLVMNoUnnamedAddr;
1957   case GlobalVariable::UnnamedAddr::Local:
1958     return LLVMLocalUnnamedAddr;
1959   case GlobalVariable::UnnamedAddr::Global:
1960     return LLVMGlobalUnnamedAddr;
1961   }
1962   llvm_unreachable("Unknown UnnamedAddr kind!");
1963 }
1964 
1965 void LLVMSetUnnamedAddress(LLVMValueRef Global, LLVMUnnamedAddr UnnamedAddr) {
1966   GlobalValue *GV = unwrap<GlobalValue>(Global);
1967 
1968   switch (UnnamedAddr) {
1969   case LLVMNoUnnamedAddr:
1970     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::None);
1971   case LLVMLocalUnnamedAddr:
1972     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Local);
1973   case LLVMGlobalUnnamedAddr:
1974     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Global);
1975   }
1976 }
1977 
1978 LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) {
1979   return unwrap<GlobalValue>(Global)->hasGlobalUnnamedAddr();
1980 }
1981 
1982 void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) {
1983   unwrap<GlobalValue>(Global)->setUnnamedAddr(
1984       HasUnnamedAddr ? GlobalValue::UnnamedAddr::Global
1985                      : GlobalValue::UnnamedAddr::None);
1986 }
1987 
1988 LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef Global) {
1989   return wrap(unwrap<GlobalValue>(Global)->getValueType());
1990 }
1991 
1992 /*--.. Operations on global variables, load and store instructions .........--*/
1993 
1994 unsigned LLVMGetAlignment(LLVMValueRef V) {
1995   Value *P = unwrap<Value>(V);
1996   if (GlobalValue *GV = dyn_cast<GlobalValue>(P))
1997     return GV->getAlignment();
1998   if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
1999     return AI->getAlignment();
2000   if (LoadInst *LI = dyn_cast<LoadInst>(P))
2001     return LI->getAlignment();
2002   if (StoreInst *SI = dyn_cast<StoreInst>(P))
2003     return SI->getAlignment();
2004 
2005   llvm_unreachable(
2006       "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment");
2007 }
2008 
2009 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) {
2010   Value *P = unwrap<Value>(V);
2011   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
2012     GV->setAlignment(MaybeAlign(Bytes));
2013   else if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
2014     AI->setAlignment(MaybeAlign(Bytes));
2015   else if (LoadInst *LI = dyn_cast<LoadInst>(P))
2016     LI->setAlignment(MaybeAlign(Bytes));
2017   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
2018     SI->setAlignment(MaybeAlign(Bytes));
2019   else
2020     llvm_unreachable(
2021         "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment");
2022 }
2023 
2024 LLVMValueMetadataEntry *LLVMGlobalCopyAllMetadata(LLVMValueRef Value,
2025                                                   size_t *NumEntries) {
2026   return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {
2027     if (Instruction *Instr = dyn_cast<Instruction>(unwrap(Value))) {
2028       Instr->getAllMetadata(Entries);
2029     } else {
2030       unwrap<GlobalObject>(Value)->getAllMetadata(Entries);
2031     }
2032   });
2033 }
2034 
2035 unsigned LLVMValueMetadataEntriesGetKind(LLVMValueMetadataEntry *Entries,
2036                                          unsigned Index) {
2037   LLVMOpaqueValueMetadataEntry MVE =
2038       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2039   return MVE.Kind;
2040 }
2041 
2042 LLVMMetadataRef
2043 LLVMValueMetadataEntriesGetMetadata(LLVMValueMetadataEntry *Entries,
2044                                     unsigned Index) {
2045   LLVMOpaqueValueMetadataEntry MVE =
2046       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2047   return MVE.Metadata;
2048 }
2049 
2050 void LLVMDisposeValueMetadataEntries(LLVMValueMetadataEntry *Entries) {
2051   free(Entries);
2052 }
2053 
2054 void LLVMGlobalSetMetadata(LLVMValueRef Global, unsigned Kind,
2055                            LLVMMetadataRef MD) {
2056   unwrap<GlobalObject>(Global)->setMetadata(Kind, unwrap<MDNode>(MD));
2057 }
2058 
2059 void LLVMGlobalEraseMetadata(LLVMValueRef Global, unsigned Kind) {
2060   unwrap<GlobalObject>(Global)->eraseMetadata(Kind);
2061 }
2062 
2063 void LLVMGlobalClearMetadata(LLVMValueRef Global) {
2064   unwrap<GlobalObject>(Global)->clearMetadata();
2065 }
2066 
2067 /*--.. Operations on global variables ......................................--*/
2068 
2069 LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) {
2070   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2071                                  GlobalValue::ExternalLinkage, nullptr, Name));
2072 }
2073 
2074 LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
2075                                          const char *Name,
2076                                          unsigned AddressSpace) {
2077   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2078                                  GlobalValue::ExternalLinkage, nullptr, Name,
2079                                  nullptr, GlobalVariable::NotThreadLocal,
2080                                  AddressSpace));
2081 }
2082 
2083 LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) {
2084   return wrap(unwrap(M)->getNamedGlobal(Name));
2085 }
2086 
2087 LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) {
2088   Module *Mod = unwrap(M);
2089   Module::global_iterator I = Mod->global_begin();
2090   if (I == Mod->global_end())
2091     return nullptr;
2092   return wrap(&*I);
2093 }
2094 
2095 LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
2096   Module *Mod = unwrap(M);
2097   Module::global_iterator I = Mod->global_end();
2098   if (I == Mod->global_begin())
2099     return nullptr;
2100   return wrap(&*--I);
2101 }
2102 
2103 LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
2104   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2105   Module::global_iterator I(GV);
2106   if (++I == GV->getParent()->global_end())
2107     return nullptr;
2108   return wrap(&*I);
2109 }
2110 
2111 LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
2112   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2113   Module::global_iterator I(GV);
2114   if (I == GV->getParent()->global_begin())
2115     return nullptr;
2116   return wrap(&*--I);
2117 }
2118 
2119 void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
2120   unwrap<GlobalVariable>(GlobalVar)->eraseFromParent();
2121 }
2122 
2123 LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
2124   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
2125   if ( !GV->hasInitializer() )
2126     return nullptr;
2127   return wrap(GV->getInitializer());
2128 }
2129 
2130 void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) {
2131   unwrap<GlobalVariable>(GlobalVar)
2132     ->setInitializer(unwrap<Constant>(ConstantVal));
2133 }
2134 
2135 LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) {
2136   return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal();
2137 }
2138 
2139 void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) {
2140   unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0);
2141 }
2142 
2143 LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) {
2144   return unwrap<GlobalVariable>(GlobalVar)->isConstant();
2145 }
2146 
2147 void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) {
2148   unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0);
2149 }
2150 
2151 LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) {
2152   switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) {
2153   case GlobalVariable::NotThreadLocal:
2154     return LLVMNotThreadLocal;
2155   case GlobalVariable::GeneralDynamicTLSModel:
2156     return LLVMGeneralDynamicTLSModel;
2157   case GlobalVariable::LocalDynamicTLSModel:
2158     return LLVMLocalDynamicTLSModel;
2159   case GlobalVariable::InitialExecTLSModel:
2160     return LLVMInitialExecTLSModel;
2161   case GlobalVariable::LocalExecTLSModel:
2162     return LLVMLocalExecTLSModel;
2163   }
2164 
2165   llvm_unreachable("Invalid GlobalVariable thread local mode");
2166 }
2167 
2168 void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) {
2169   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2170 
2171   switch (Mode) {
2172   case LLVMNotThreadLocal:
2173     GV->setThreadLocalMode(GlobalVariable::NotThreadLocal);
2174     break;
2175   case LLVMGeneralDynamicTLSModel:
2176     GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel);
2177     break;
2178   case LLVMLocalDynamicTLSModel:
2179     GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel);
2180     break;
2181   case LLVMInitialExecTLSModel:
2182     GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
2183     break;
2184   case LLVMLocalExecTLSModel:
2185     GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel);
2186     break;
2187   }
2188 }
2189 
2190 LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) {
2191   return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized();
2192 }
2193 
2194 void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) {
2195   unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit);
2196 }
2197 
2198 /*--.. Operations on aliases ......................................--*/
2199 
2200 LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
2201                           const char *Name) {
2202   auto *PTy = cast<PointerType>(unwrap(Ty));
2203   return wrap(GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2204                                   GlobalValue::ExternalLinkage, Name,
2205                                   unwrap<Constant>(Aliasee), unwrap(M)));
2206 }
2207 
2208 LLVMValueRef LLVMGetNamedGlobalAlias(LLVMModuleRef M,
2209                                      const char *Name, size_t NameLen) {
2210   return wrap(unwrap(M)->getNamedAlias(Name));
2211 }
2212 
2213 LLVMValueRef LLVMGetFirstGlobalAlias(LLVMModuleRef M) {
2214   Module *Mod = unwrap(M);
2215   Module::alias_iterator I = Mod->alias_begin();
2216   if (I == Mod->alias_end())
2217     return nullptr;
2218   return wrap(&*I);
2219 }
2220 
2221 LLVMValueRef LLVMGetLastGlobalAlias(LLVMModuleRef M) {
2222   Module *Mod = unwrap(M);
2223   Module::alias_iterator I = Mod->alias_end();
2224   if (I == Mod->alias_begin())
2225     return nullptr;
2226   return wrap(&*--I);
2227 }
2228 
2229 LLVMValueRef LLVMGetNextGlobalAlias(LLVMValueRef GA) {
2230   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2231   Module::alias_iterator I(Alias);
2232   if (++I == Alias->getParent()->alias_end())
2233     return nullptr;
2234   return wrap(&*I);
2235 }
2236 
2237 LLVMValueRef LLVMGetPreviousGlobalAlias(LLVMValueRef GA) {
2238   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2239   Module::alias_iterator I(Alias);
2240   if (I == Alias->getParent()->alias_begin())
2241     return nullptr;
2242   return wrap(&*--I);
2243 }
2244 
2245 LLVMValueRef LLVMAliasGetAliasee(LLVMValueRef Alias) {
2246   return wrap(unwrap<GlobalAlias>(Alias)->getAliasee());
2247 }
2248 
2249 void LLVMAliasSetAliasee(LLVMValueRef Alias, LLVMValueRef Aliasee) {
2250   unwrap<GlobalAlias>(Alias)->setAliasee(unwrap<Constant>(Aliasee));
2251 }
2252 
2253 /*--.. Operations on functions .............................................--*/
2254 
2255 LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
2256                              LLVMTypeRef FunctionTy) {
2257   return wrap(Function::Create(unwrap<FunctionType>(FunctionTy),
2258                                GlobalValue::ExternalLinkage, Name, unwrap(M)));
2259 }
2260 
2261 LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) {
2262   return wrap(unwrap(M)->getFunction(Name));
2263 }
2264 
2265 LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) {
2266   Module *Mod = unwrap(M);
2267   Module::iterator I = Mod->begin();
2268   if (I == Mod->end())
2269     return nullptr;
2270   return wrap(&*I);
2271 }
2272 
2273 LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
2274   Module *Mod = unwrap(M);
2275   Module::iterator I = Mod->end();
2276   if (I == Mod->begin())
2277     return nullptr;
2278   return wrap(&*--I);
2279 }
2280 
2281 LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
2282   Function *Func = unwrap<Function>(Fn);
2283   Module::iterator I(Func);
2284   if (++I == Func->getParent()->end())
2285     return nullptr;
2286   return wrap(&*I);
2287 }
2288 
2289 LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
2290   Function *Func = unwrap<Function>(Fn);
2291   Module::iterator I(Func);
2292   if (I == Func->getParent()->begin())
2293     return nullptr;
2294   return wrap(&*--I);
2295 }
2296 
2297 void LLVMDeleteFunction(LLVMValueRef Fn) {
2298   unwrap<Function>(Fn)->eraseFromParent();
2299 }
2300 
2301 LLVMBool LLVMHasPersonalityFn(LLVMValueRef Fn) {
2302   return unwrap<Function>(Fn)->hasPersonalityFn();
2303 }
2304 
2305 LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn) {
2306   return wrap(unwrap<Function>(Fn)->getPersonalityFn());
2307 }
2308 
2309 void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn) {
2310   unwrap<Function>(Fn)->setPersonalityFn(unwrap<Constant>(PersonalityFn));
2311 }
2312 
2313 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
2314   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
2315     return F->getIntrinsicID();
2316   return 0;
2317 }
2318 
2319 static Intrinsic::ID llvm_map_to_intrinsic_id(unsigned ID) {
2320   assert(ID < llvm::Intrinsic::num_intrinsics && "Intrinsic ID out of range");
2321   return llvm::Intrinsic::ID(ID);
2322 }
2323 
2324 LLVMValueRef LLVMGetIntrinsicDeclaration(LLVMModuleRef Mod,
2325                                          unsigned ID,
2326                                          LLVMTypeRef *ParamTypes,
2327                                          size_t ParamCount) {
2328   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2329   auto IID = llvm_map_to_intrinsic_id(ID);
2330   return wrap(llvm::Intrinsic::getDeclaration(unwrap(Mod), IID, Tys));
2331 }
2332 
2333 const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength) {
2334   auto IID = llvm_map_to_intrinsic_id(ID);
2335   auto Str = llvm::Intrinsic::getName(IID);
2336   *NameLength = Str.size();
2337   return Str.data();
2338 }
2339 
2340 LLVMTypeRef LLVMIntrinsicGetType(LLVMContextRef Ctx, unsigned ID,
2341                                  LLVMTypeRef *ParamTypes, size_t ParamCount) {
2342   auto IID = llvm_map_to_intrinsic_id(ID);
2343   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2344   return wrap(llvm::Intrinsic::getType(*unwrap(Ctx), IID, Tys));
2345 }
2346 
2347 const char *LLVMIntrinsicCopyOverloadedName(unsigned ID,
2348                                             LLVMTypeRef *ParamTypes,
2349                                             size_t ParamCount,
2350                                             size_t *NameLength) {
2351   auto IID = llvm_map_to_intrinsic_id(ID);
2352   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2353   auto Str = llvm::Intrinsic::getName(IID, Tys);
2354   *NameLength = Str.length();
2355   return strdup(Str.c_str());
2356 }
2357 
2358 unsigned LLVMLookupIntrinsicID(const char *Name, size_t NameLen) {
2359   return Function::lookupIntrinsicID({Name, NameLen});
2360 }
2361 
2362 LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID) {
2363   auto IID = llvm_map_to_intrinsic_id(ID);
2364   return llvm::Intrinsic::isOverloaded(IID);
2365 }
2366 
2367 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {
2368   return unwrap<Function>(Fn)->getCallingConv();
2369 }
2370 
2371 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) {
2372   return unwrap<Function>(Fn)->setCallingConv(
2373     static_cast<CallingConv::ID>(CC));
2374 }
2375 
2376 const char *LLVMGetGC(LLVMValueRef Fn) {
2377   Function *F = unwrap<Function>(Fn);
2378   return F->hasGC()? F->getGC().c_str() : nullptr;
2379 }
2380 
2381 void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
2382   Function *F = unwrap<Function>(Fn);
2383   if (GC)
2384     F->setGC(GC);
2385   else
2386     F->clearGC();
2387 }
2388 
2389 void LLVMAddAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2390                              LLVMAttributeRef A) {
2391   unwrap<Function>(F)->addAttribute(Idx, unwrap(A));
2392 }
2393 
2394 unsigned LLVMGetAttributeCountAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx) {
2395   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2396   return AS.getNumAttributes();
2397 }
2398 
2399 void LLVMGetAttributesAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2400                               LLVMAttributeRef *Attrs) {
2401   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2402   for (auto A : AS)
2403     *Attrs++ = wrap(A);
2404 }
2405 
2406 LLVMAttributeRef LLVMGetEnumAttributeAtIndex(LLVMValueRef F,
2407                                              LLVMAttributeIndex Idx,
2408                                              unsigned KindID) {
2409   return wrap(unwrap<Function>(F)->getAttribute(Idx,
2410                                                 (Attribute::AttrKind)KindID));
2411 }
2412 
2413 LLVMAttributeRef LLVMGetStringAttributeAtIndex(LLVMValueRef F,
2414                                                LLVMAttributeIndex Idx,
2415                                                const char *K, unsigned KLen) {
2416   return wrap(unwrap<Function>(F)->getAttribute(Idx, StringRef(K, KLen)));
2417 }
2418 
2419 void LLVMRemoveEnumAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2420                                     unsigned KindID) {
2421   unwrap<Function>(F)->removeAttribute(Idx, (Attribute::AttrKind)KindID);
2422 }
2423 
2424 void LLVMRemoveStringAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2425                                       const char *K, unsigned KLen) {
2426   unwrap<Function>(F)->removeAttribute(Idx, StringRef(K, KLen));
2427 }
2428 
2429 void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A,
2430                                         const char *V) {
2431   Function *Func = unwrap<Function>(Fn);
2432   Attribute Attr = Attribute::get(Func->getContext(), A, V);
2433   Func->addAttribute(AttributeList::FunctionIndex, Attr);
2434 }
2435 
2436 /*--.. Operations on parameters ............................................--*/
2437 
2438 unsigned LLVMCountParams(LLVMValueRef FnRef) {
2439   // This function is strictly redundant to
2440   //   LLVMCountParamTypes(LLVMGetElementType(LLVMTypeOf(FnRef)))
2441   return unwrap<Function>(FnRef)->arg_size();
2442 }
2443 
2444 void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) {
2445   Function *Fn = unwrap<Function>(FnRef);
2446   for (Function::arg_iterator I = Fn->arg_begin(),
2447                               E = Fn->arg_end(); I != E; I++)
2448     *ParamRefs++ = wrap(&*I);
2449 }
2450 
2451 LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
2452   Function *Fn = unwrap<Function>(FnRef);
2453   return wrap(&Fn->arg_begin()[index]);
2454 }
2455 
2456 LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
2457   return wrap(unwrap<Argument>(V)->getParent());
2458 }
2459 
2460 LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) {
2461   Function *Func = unwrap<Function>(Fn);
2462   Function::arg_iterator I = Func->arg_begin();
2463   if (I == Func->arg_end())
2464     return nullptr;
2465   return wrap(&*I);
2466 }
2467 
2468 LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
2469   Function *Func = unwrap<Function>(Fn);
2470   Function::arg_iterator I = Func->arg_end();
2471   if (I == Func->arg_begin())
2472     return nullptr;
2473   return wrap(&*--I);
2474 }
2475 
2476 LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
2477   Argument *A = unwrap<Argument>(Arg);
2478   Function *Fn = A->getParent();
2479   if (A->getArgNo() + 1 >= Fn->arg_size())
2480     return nullptr;
2481   return wrap(&Fn->arg_begin()[A->getArgNo() + 1]);
2482 }
2483 
2484 LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
2485   Argument *A = unwrap<Argument>(Arg);
2486   if (A->getArgNo() == 0)
2487     return nullptr;
2488   return wrap(&A->getParent()->arg_begin()[A->getArgNo() - 1]);
2489 }
2490 
2491 void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) {
2492   Argument *A = unwrap<Argument>(Arg);
2493   A->addAttr(Attribute::getWithAlignment(A->getContext(), Align(align)));
2494 }
2495 
2496 /*--.. Operations on ifuncs ................................................--*/
2497 
2498 LLVMValueRef LLVMAddGlobalIFunc(LLVMModuleRef M,
2499                                 const char *Name, size_t NameLen,
2500                                 LLVMTypeRef Ty, unsigned AddrSpace,
2501                                 LLVMValueRef Resolver) {
2502   return wrap(GlobalIFunc::create(unwrap(Ty), AddrSpace,
2503                                   GlobalValue::ExternalLinkage,
2504                                   StringRef(Name, NameLen),
2505                                   unwrap<Constant>(Resolver), unwrap(M)));
2506 }
2507 
2508 LLVMValueRef LLVMGetNamedGlobalIFunc(LLVMModuleRef M,
2509                                      const char *Name, size_t NameLen) {
2510   return wrap(unwrap(M)->getNamedIFunc(StringRef(Name, NameLen)));
2511 }
2512 
2513 LLVMValueRef LLVMGetFirstGlobalIFunc(LLVMModuleRef M) {
2514   Module *Mod = unwrap(M);
2515   Module::ifunc_iterator I = Mod->ifunc_begin();
2516   if (I == Mod->ifunc_end())
2517     return nullptr;
2518   return wrap(&*I);
2519 }
2520 
2521 LLVMValueRef LLVMGetLastGlobalIFunc(LLVMModuleRef M) {
2522   Module *Mod = unwrap(M);
2523   Module::ifunc_iterator I = Mod->ifunc_end();
2524   if (I == Mod->ifunc_begin())
2525     return nullptr;
2526   return wrap(&*--I);
2527 }
2528 
2529 LLVMValueRef LLVMGetNextGlobalIFunc(LLVMValueRef IFunc) {
2530   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2531   Module::ifunc_iterator I(GIF);
2532   if (++I == GIF->getParent()->ifunc_end())
2533     return nullptr;
2534   return wrap(&*I);
2535 }
2536 
2537 LLVMValueRef LLVMGetPreviousGlobalIFunc(LLVMValueRef IFunc) {
2538   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2539   Module::ifunc_iterator I(GIF);
2540   if (I == GIF->getParent()->ifunc_begin())
2541     return nullptr;
2542   return wrap(&*--I);
2543 }
2544 
2545 LLVMValueRef LLVMGetGlobalIFuncResolver(LLVMValueRef IFunc) {
2546   return wrap(unwrap<GlobalIFunc>(IFunc)->getResolver());
2547 }
2548 
2549 void LLVMSetGlobalIFuncResolver(LLVMValueRef IFunc, LLVMValueRef Resolver) {
2550   unwrap<GlobalIFunc>(IFunc)->setResolver(unwrap<Constant>(Resolver));
2551 }
2552 
2553 void LLVMEraseGlobalIFunc(LLVMValueRef IFunc) {
2554   unwrap<GlobalIFunc>(IFunc)->eraseFromParent();
2555 }
2556 
2557 void LLVMRemoveGlobalIFunc(LLVMValueRef IFunc) {
2558   unwrap<GlobalIFunc>(IFunc)->removeFromParent();
2559 }
2560 
2561 /*--.. Operations on basic blocks ..........................................--*/
2562 
2563 LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) {
2564   return wrap(static_cast<Value*>(unwrap(BB)));
2565 }
2566 
2567 LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) {
2568   return isa<BasicBlock>(unwrap(Val));
2569 }
2570 
2571 LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) {
2572   return wrap(unwrap<BasicBlock>(Val));
2573 }
2574 
2575 const char *LLVMGetBasicBlockName(LLVMBasicBlockRef BB) {
2576   return unwrap(BB)->getName().data();
2577 }
2578 
2579 LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) {
2580   return wrap(unwrap(BB)->getParent());
2581 }
2582 
2583 LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) {
2584   return wrap(unwrap(BB)->getTerminator());
2585 }
2586 
2587 unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) {
2588   return unwrap<Function>(FnRef)->size();
2589 }
2590 
2591 void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
2592   Function *Fn = unwrap<Function>(FnRef);
2593   for (BasicBlock &BB : *Fn)
2594     *BasicBlocksRefs++ = wrap(&BB);
2595 }
2596 
2597 LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
2598   return wrap(&unwrap<Function>(Fn)->getEntryBlock());
2599 }
2600 
2601 LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) {
2602   Function *Func = unwrap<Function>(Fn);
2603   Function::iterator I = Func->begin();
2604   if (I == Func->end())
2605     return nullptr;
2606   return wrap(&*I);
2607 }
2608 
2609 LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
2610   Function *Func = unwrap<Function>(Fn);
2611   Function::iterator I = Func->end();
2612   if (I == Func->begin())
2613     return nullptr;
2614   return wrap(&*--I);
2615 }
2616 
2617 LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
2618   BasicBlock *Block = unwrap(BB);
2619   Function::iterator I(Block);
2620   if (++I == Block->getParent()->end())
2621     return nullptr;
2622   return wrap(&*I);
2623 }
2624 
2625 LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
2626   BasicBlock *Block = unwrap(BB);
2627   Function::iterator I(Block);
2628   if (I == Block->getParent()->begin())
2629     return nullptr;
2630   return wrap(&*--I);
2631 }
2632 
2633 LLVMBasicBlockRef LLVMCreateBasicBlockInContext(LLVMContextRef C,
2634                                                 const char *Name) {
2635   return wrap(llvm::BasicBlock::Create(*unwrap(C), Name));
2636 }
2637 
2638 void LLVMInsertExistingBasicBlockAfterInsertBlock(LLVMBuilderRef Builder,
2639                                                   LLVMBasicBlockRef BB) {
2640   BasicBlock *ToInsert = unwrap(BB);
2641   BasicBlock *CurBB = unwrap(Builder)->GetInsertBlock();
2642   assert(CurBB && "current insertion point is invalid!");
2643   CurBB->getParent()->getBasicBlockList().insertAfter(CurBB->getIterator(),
2644                                                       ToInsert);
2645 }
2646 
2647 void LLVMAppendExistingBasicBlock(LLVMValueRef Fn,
2648                                   LLVMBasicBlockRef BB) {
2649   unwrap<Function>(Fn)->getBasicBlockList().push_back(unwrap(BB));
2650 }
2651 
2652 LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
2653                                                 LLVMValueRef FnRef,
2654                                                 const char *Name) {
2655   return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef)));
2656 }
2657 
2658 LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) {
2659   return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name);
2660 }
2661 
2662 LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
2663                                                 LLVMBasicBlockRef BBRef,
2664                                                 const char *Name) {
2665   BasicBlock *BB = unwrap(BBRef);
2666   return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB));
2667 }
2668 
2669 LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef,
2670                                        const char *Name) {
2671   return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name);
2672 }
2673 
2674 void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) {
2675   unwrap(BBRef)->eraseFromParent();
2676 }
2677 
2678 void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) {
2679   unwrap(BBRef)->removeFromParent();
2680 }
2681 
2682 void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2683   unwrap(BB)->moveBefore(unwrap(MovePos));
2684 }
2685 
2686 void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2687   unwrap(BB)->moveAfter(unwrap(MovePos));
2688 }
2689 
2690 /*--.. Operations on instructions ..........................................--*/
2691 
2692 LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) {
2693   return wrap(unwrap<Instruction>(Inst)->getParent());
2694 }
2695 
2696 LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) {
2697   BasicBlock *Block = unwrap(BB);
2698   BasicBlock::iterator I = Block->begin();
2699   if (I == Block->end())
2700     return nullptr;
2701   return wrap(&*I);
2702 }
2703 
2704 LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
2705   BasicBlock *Block = unwrap(BB);
2706   BasicBlock::iterator I = Block->end();
2707   if (I == Block->begin())
2708     return nullptr;
2709   return wrap(&*--I);
2710 }
2711 
2712 LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
2713   Instruction *Instr = unwrap<Instruction>(Inst);
2714   BasicBlock::iterator I(Instr);
2715   if (++I == Instr->getParent()->end())
2716     return nullptr;
2717   return wrap(&*I);
2718 }
2719 
2720 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
2721   Instruction *Instr = unwrap<Instruction>(Inst);
2722   BasicBlock::iterator I(Instr);
2723   if (I == Instr->getParent()->begin())
2724     return nullptr;
2725   return wrap(&*--I);
2726 }
2727 
2728 void LLVMInstructionRemoveFromParent(LLVMValueRef Inst) {
2729   unwrap<Instruction>(Inst)->removeFromParent();
2730 }
2731 
2732 void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
2733   unwrap<Instruction>(Inst)->eraseFromParent();
2734 }
2735 
2736 LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) {
2737   if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst)))
2738     return (LLVMIntPredicate)I->getPredicate();
2739   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2740     if (CE->getOpcode() == Instruction::ICmp)
2741       return (LLVMIntPredicate)CE->getPredicate();
2742   return (LLVMIntPredicate)0;
2743 }
2744 
2745 LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) {
2746   if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst)))
2747     return (LLVMRealPredicate)I->getPredicate();
2748   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2749     if (CE->getOpcode() == Instruction::FCmp)
2750       return (LLVMRealPredicate)CE->getPredicate();
2751   return (LLVMRealPredicate)0;
2752 }
2753 
2754 LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) {
2755   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2756     return map_to_llvmopcode(C->getOpcode());
2757   return (LLVMOpcode)0;
2758 }
2759 
2760 LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) {
2761   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2762     return wrap(C->clone());
2763   return nullptr;
2764 }
2765 
2766 LLVMValueRef LLVMIsATerminatorInst(LLVMValueRef Inst) {
2767   Instruction *I = dyn_cast<Instruction>(unwrap(Inst));
2768   return (I && I->isTerminator()) ? wrap(I) : nullptr;
2769 }
2770 
2771 unsigned LLVMGetNumArgOperands(LLVMValueRef Instr) {
2772   if (FuncletPadInst *FPI = dyn_cast<FuncletPadInst>(unwrap(Instr))) {
2773     return FPI->getNumArgOperands();
2774   }
2775   return unwrap<CallBase>(Instr)->getNumArgOperands();
2776 }
2777 
2778 /*--.. Call and invoke instructions ........................................--*/
2779 
2780 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) {
2781   return unwrap<CallBase>(Instr)->getCallingConv();
2782 }
2783 
2784 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {
2785   return unwrap<CallBase>(Instr)->setCallingConv(
2786       static_cast<CallingConv::ID>(CC));
2787 }
2788 
2789 void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,
2790                                 unsigned align) {
2791   auto *Call = unwrap<CallBase>(Instr);
2792   Attribute AlignAttr =
2793       Attribute::getWithAlignment(Call->getContext(), Align(align));
2794   Call->addAttribute(index, AlignAttr);
2795 }
2796 
2797 void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2798                               LLVMAttributeRef A) {
2799   unwrap<CallBase>(C)->addAttribute(Idx, unwrap(A));
2800 }
2801 
2802 unsigned LLVMGetCallSiteAttributeCount(LLVMValueRef C,
2803                                        LLVMAttributeIndex Idx) {
2804   auto *Call = unwrap<CallBase>(C);
2805   auto AS = Call->getAttributes().getAttributes(Idx);
2806   return AS.getNumAttributes();
2807 }
2808 
2809 void LLVMGetCallSiteAttributes(LLVMValueRef C, LLVMAttributeIndex Idx,
2810                                LLVMAttributeRef *Attrs) {
2811   auto *Call = unwrap<CallBase>(C);
2812   auto AS = Call->getAttributes().getAttributes(Idx);
2813   for (auto A : AS)
2814     *Attrs++ = wrap(A);
2815 }
2816 
2817 LLVMAttributeRef LLVMGetCallSiteEnumAttribute(LLVMValueRef C,
2818                                               LLVMAttributeIndex Idx,
2819                                               unsigned KindID) {
2820   return wrap(
2821       unwrap<CallBase>(C)->getAttribute(Idx, (Attribute::AttrKind)KindID));
2822 }
2823 
2824 LLVMAttributeRef LLVMGetCallSiteStringAttribute(LLVMValueRef C,
2825                                                 LLVMAttributeIndex Idx,
2826                                                 const char *K, unsigned KLen) {
2827   return wrap(unwrap<CallBase>(C)->getAttribute(Idx, StringRef(K, KLen)));
2828 }
2829 
2830 void LLVMRemoveCallSiteEnumAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2831                                      unsigned KindID) {
2832   unwrap<CallBase>(C)->removeAttribute(Idx, (Attribute::AttrKind)KindID);
2833 }
2834 
2835 void LLVMRemoveCallSiteStringAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2836                                        const char *K, unsigned KLen) {
2837   unwrap<CallBase>(C)->removeAttribute(Idx, StringRef(K, KLen));
2838 }
2839 
2840 LLVMValueRef LLVMGetCalledValue(LLVMValueRef Instr) {
2841   return wrap(unwrap<CallBase>(Instr)->getCalledValue());
2842 }
2843 
2844 LLVMTypeRef LLVMGetCalledFunctionType(LLVMValueRef Instr) {
2845   return wrap(unwrap<CallBase>(Instr)->getFunctionType());
2846 }
2847 
2848 /*--.. Operations on call instructions (only) ..............................--*/
2849 
2850 LLVMBool LLVMIsTailCall(LLVMValueRef Call) {
2851   return unwrap<CallInst>(Call)->isTailCall();
2852 }
2853 
2854 void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) {
2855   unwrap<CallInst>(Call)->setTailCall(isTailCall);
2856 }
2857 
2858 /*--.. Operations on invoke instructions (only) ............................--*/
2859 
2860 LLVMBasicBlockRef LLVMGetNormalDest(LLVMValueRef Invoke) {
2861   return wrap(unwrap<InvokeInst>(Invoke)->getNormalDest());
2862 }
2863 
2864 LLVMBasicBlockRef LLVMGetUnwindDest(LLVMValueRef Invoke) {
2865   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2866     return wrap(CRI->getUnwindDest());
2867   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2868     return wrap(CSI->getUnwindDest());
2869   }
2870   return wrap(unwrap<InvokeInst>(Invoke)->getUnwindDest());
2871 }
2872 
2873 void LLVMSetNormalDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2874   unwrap<InvokeInst>(Invoke)->setNormalDest(unwrap(B));
2875 }
2876 
2877 void LLVMSetUnwindDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2878   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2879     return CRI->setUnwindDest(unwrap(B));
2880   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2881     return CSI->setUnwindDest(unwrap(B));
2882   }
2883   unwrap<InvokeInst>(Invoke)->setUnwindDest(unwrap(B));
2884 }
2885 
2886 /*--.. Operations on terminators ...........................................--*/
2887 
2888 unsigned LLVMGetNumSuccessors(LLVMValueRef Term) {
2889   return unwrap<Instruction>(Term)->getNumSuccessors();
2890 }
2891 
2892 LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) {
2893   return wrap(unwrap<Instruction>(Term)->getSuccessor(i));
2894 }
2895 
2896 void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) {
2897   return unwrap<Instruction>(Term)->setSuccessor(i, unwrap(block));
2898 }
2899 
2900 /*--.. Operations on branch instructions (only) ............................--*/
2901 
2902 LLVMBool LLVMIsConditional(LLVMValueRef Branch) {
2903   return unwrap<BranchInst>(Branch)->isConditional();
2904 }
2905 
2906 LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) {
2907   return wrap(unwrap<BranchInst>(Branch)->getCondition());
2908 }
2909 
2910 void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) {
2911   return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond));
2912 }
2913 
2914 /*--.. Operations on switch instructions (only) ............................--*/
2915 
2916 LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) {
2917   return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest());
2918 }
2919 
2920 /*--.. Operations on alloca instructions (only) ............................--*/
2921 
2922 LLVMTypeRef LLVMGetAllocatedType(LLVMValueRef Alloca) {
2923   return wrap(unwrap<AllocaInst>(Alloca)->getAllocatedType());
2924 }
2925 
2926 /*--.. Operations on gep instructions (only) ...............................--*/
2927 
2928 LLVMBool LLVMIsInBounds(LLVMValueRef GEP) {
2929   return unwrap<GetElementPtrInst>(GEP)->isInBounds();
2930 }
2931 
2932 void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds) {
2933   return unwrap<GetElementPtrInst>(GEP)->setIsInBounds(InBounds);
2934 }
2935 
2936 /*--.. Operations on phi nodes .............................................--*/
2937 
2938 void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
2939                      LLVMBasicBlockRef *IncomingBlocks, unsigned Count) {
2940   PHINode *PhiVal = unwrap<PHINode>(PhiNode);
2941   for (unsigned I = 0; I != Count; ++I)
2942     PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I]));
2943 }
2944 
2945 unsigned LLVMCountIncoming(LLVMValueRef PhiNode) {
2946   return unwrap<PHINode>(PhiNode)->getNumIncomingValues();
2947 }
2948 
2949 LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) {
2950   return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index));
2951 }
2952 
2953 LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) {
2954   return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index));
2955 }
2956 
2957 /*--.. Operations on extractvalue and insertvalue nodes ....................--*/
2958 
2959 unsigned LLVMGetNumIndices(LLVMValueRef Inst) {
2960   auto *I = unwrap(Inst);
2961   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
2962     return GEP->getNumIndices();
2963   if (auto *EV = dyn_cast<ExtractValueInst>(I))
2964     return EV->getNumIndices();
2965   if (auto *IV = dyn_cast<InsertValueInst>(I))
2966     return IV->getNumIndices();
2967   if (auto *CE = dyn_cast<ConstantExpr>(I))
2968     return CE->getIndices().size();
2969   llvm_unreachable(
2970     "LLVMGetNumIndices applies only to extractvalue and insertvalue!");
2971 }
2972 
2973 const unsigned *LLVMGetIndices(LLVMValueRef Inst) {
2974   auto *I = unwrap(Inst);
2975   if (auto *EV = dyn_cast<ExtractValueInst>(I))
2976     return EV->getIndices().data();
2977   if (auto *IV = dyn_cast<InsertValueInst>(I))
2978     return IV->getIndices().data();
2979   if (auto *CE = dyn_cast<ConstantExpr>(I))
2980     return CE->getIndices().data();
2981   llvm_unreachable(
2982     "LLVMGetIndices applies only to extractvalue and insertvalue!");
2983 }
2984 
2985 
2986 /*===-- Instruction builders ----------------------------------------------===*/
2987 
2988 LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C) {
2989   return wrap(new IRBuilder<>(*unwrap(C)));
2990 }
2991 
2992 LLVMBuilderRef LLVMCreateBuilder(void) {
2993   return LLVMCreateBuilderInContext(LLVMGetGlobalContext());
2994 }
2995 
2996 void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block,
2997                          LLVMValueRef Instr) {
2998   BasicBlock *BB = unwrap(Block);
2999   auto I = Instr ? unwrap<Instruction>(Instr)->getIterator() : BB->end();
3000   unwrap(Builder)->SetInsertPoint(BB, I);
3001 }
3002 
3003 void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
3004   Instruction *I = unwrap<Instruction>(Instr);
3005   unwrap(Builder)->SetInsertPoint(I->getParent(), I->getIterator());
3006 }
3007 
3008 void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
3009   BasicBlock *BB = unwrap(Block);
3010   unwrap(Builder)->SetInsertPoint(BB);
3011 }
3012 
3013 LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder) {
3014    return wrap(unwrap(Builder)->GetInsertBlock());
3015 }
3016 
3017 void LLVMClearInsertionPosition(LLVMBuilderRef Builder) {
3018   unwrap(Builder)->ClearInsertionPoint();
3019 }
3020 
3021 void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr) {
3022   unwrap(Builder)->Insert(unwrap<Instruction>(Instr));
3023 }
3024 
3025 void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr,
3026                                    const char *Name) {
3027   unwrap(Builder)->Insert(unwrap<Instruction>(Instr), Name);
3028 }
3029 
3030 void LLVMDisposeBuilder(LLVMBuilderRef Builder) {
3031   delete unwrap(Builder);
3032 }
3033 
3034 /*--.. Metadata builders ...................................................--*/
3035 
3036 LLVMMetadataRef LLVMGetCurrentDebugLocation2(LLVMBuilderRef Builder) {
3037   return wrap(unwrap(Builder)->getCurrentDebugLocation().getAsMDNode());
3038 }
3039 
3040 void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Builder, LLVMMetadataRef Loc) {
3041   if (Loc)
3042     unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(unwrap<MDNode>(Loc)));
3043   else
3044     unwrap(Builder)->SetCurrentDebugLocation(DebugLoc());
3045 }
3046 
3047 void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L) {
3048   MDNode *Loc =
3049       L ? cast<MDNode>(unwrap<MetadataAsValue>(L)->getMetadata()) : nullptr;
3050   unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(Loc));
3051 }
3052 
3053 LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder) {
3054   LLVMContext &Context = unwrap(Builder)->getContext();
3055   return wrap(MetadataAsValue::get(
3056       Context, unwrap(Builder)->getCurrentDebugLocation().getAsMDNode()));
3057 }
3058 
3059 void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) {
3060   unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst));
3061 }
3062 
3063 void LLVMBuilderSetDefaultFPMathTag(LLVMBuilderRef Builder,
3064                                     LLVMMetadataRef FPMathTag) {
3065 
3066   unwrap(Builder)->setDefaultFPMathTag(FPMathTag
3067                                        ? unwrap<MDNode>(FPMathTag)
3068                                        : nullptr);
3069 }
3070 
3071 LLVMMetadataRef LLVMBuilderGetDefaultFPMathTag(LLVMBuilderRef Builder) {
3072   return wrap(unwrap(Builder)->getDefaultFPMathTag());
3073 }
3074 
3075 /*--.. Instruction builders ................................................--*/
3076 
3077 LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef B) {
3078   return wrap(unwrap(B)->CreateRetVoid());
3079 }
3080 
3081 LLVMValueRef LLVMBuildRet(LLVMBuilderRef B, LLVMValueRef V) {
3082   return wrap(unwrap(B)->CreateRet(unwrap(V)));
3083 }
3084 
3085 LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef B, LLVMValueRef *RetVals,
3086                                    unsigned N) {
3087   return wrap(unwrap(B)->CreateAggregateRet(unwrap(RetVals), N));
3088 }
3089 
3090 LLVMValueRef LLVMBuildBr(LLVMBuilderRef B, LLVMBasicBlockRef Dest) {
3091   return wrap(unwrap(B)->CreateBr(unwrap(Dest)));
3092 }
3093 
3094 LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef B, LLVMValueRef If,
3095                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Else) {
3096   return wrap(unwrap(B)->CreateCondBr(unwrap(If), unwrap(Then), unwrap(Else)));
3097 }
3098 
3099 LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef B, LLVMValueRef V,
3100                              LLVMBasicBlockRef Else, unsigned NumCases) {
3101   return wrap(unwrap(B)->CreateSwitch(unwrap(V), unwrap(Else), NumCases));
3102 }
3103 
3104 LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
3105                                  unsigned NumDests) {
3106   return wrap(unwrap(B)->CreateIndirectBr(unwrap(Addr), NumDests));
3107 }
3108 
3109 LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn,
3110                              LLVMValueRef *Args, unsigned NumArgs,
3111                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
3112                              const char *Name) {
3113   Value *V = unwrap(Fn);
3114   FunctionType *FnT =
3115       cast<FunctionType>(cast<PointerType>(V->getType())->getElementType());
3116 
3117   return wrap(
3118       unwrap(B)->CreateInvoke(FnT, unwrap(Fn), unwrap(Then), unwrap(Catch),
3119                               makeArrayRef(unwrap(Args), NumArgs), Name));
3120 }
3121 
3122 LLVMValueRef LLVMBuildInvoke2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
3123                               LLVMValueRef *Args, unsigned NumArgs,
3124                               LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
3125                               const char *Name) {
3126   return wrap(unwrap(B)->CreateInvoke(
3127       unwrap<FunctionType>(Ty), unwrap(Fn), unwrap(Then), unwrap(Catch),
3128       makeArrayRef(unwrap(Args), NumArgs), Name));
3129 }
3130 
3131 LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
3132                                  LLVMValueRef PersFn, unsigned NumClauses,
3133                                  const char *Name) {
3134   // The personality used to live on the landingpad instruction, but now it
3135   // lives on the parent function. For compatibility, take the provided
3136   // personality and put it on the parent function.
3137   if (PersFn)
3138     unwrap(B)->GetInsertBlock()->getParent()->setPersonalityFn(
3139         cast<Function>(unwrap(PersFn)));
3140   return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty), NumClauses, Name));
3141 }
3142 
3143 LLVMValueRef LLVMBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
3144                                LLVMValueRef *Args, unsigned NumArgs,
3145                                const char *Name) {
3146   return wrap(unwrap(B)->CreateCatchPad(unwrap(ParentPad),
3147                                         makeArrayRef(unwrap(Args), NumArgs),
3148                                         Name));
3149 }
3150 
3151 LLVMValueRef LLVMBuildCleanupPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
3152                                  LLVMValueRef *Args, unsigned NumArgs,
3153                                  const char *Name) {
3154   if (ParentPad == nullptr) {
3155     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
3156     ParentPad = wrap(Constant::getNullValue(Ty));
3157   }
3158   return wrap(unwrap(B)->CreateCleanupPad(unwrap(ParentPad),
3159                                           makeArrayRef(unwrap(Args), NumArgs),
3160                                           Name));
3161 }
3162 
3163 LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn) {
3164   return wrap(unwrap(B)->CreateResume(unwrap(Exn)));
3165 }
3166 
3167 LLVMValueRef LLVMBuildCatchSwitch(LLVMBuilderRef B, LLVMValueRef ParentPad,
3168                                   LLVMBasicBlockRef UnwindBB,
3169                                   unsigned NumHandlers, const char *Name) {
3170   if (ParentPad == nullptr) {
3171     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
3172     ParentPad = wrap(Constant::getNullValue(Ty));
3173   }
3174   return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(UnwindBB),
3175                                            NumHandlers, Name));
3176 }
3177 
3178 LLVMValueRef LLVMBuildCatchRet(LLVMBuilderRef B, LLVMValueRef CatchPad,
3179                                LLVMBasicBlockRef BB) {
3180   return wrap(unwrap(B)->CreateCatchRet(unwrap<CatchPadInst>(CatchPad),
3181                                         unwrap(BB)));
3182 }
3183 
3184 LLVMValueRef LLVMBuildCleanupRet(LLVMBuilderRef B, LLVMValueRef CatchPad,
3185                                  LLVMBasicBlockRef BB) {
3186   return wrap(unwrap(B)->CreateCleanupRet(unwrap<CleanupPadInst>(CatchPad),
3187                                           unwrap(BB)));
3188 }
3189 
3190 LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef B) {
3191   return wrap(unwrap(B)->CreateUnreachable());
3192 }
3193 
3194 void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal,
3195                  LLVMBasicBlockRef Dest) {
3196   unwrap<SwitchInst>(Switch)->addCase(unwrap<ConstantInt>(OnVal), unwrap(Dest));
3197 }
3198 
3199 void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) {
3200   unwrap<IndirectBrInst>(IndirectBr)->addDestination(unwrap(Dest));
3201 }
3202 
3203 unsigned LLVMGetNumClauses(LLVMValueRef LandingPad) {
3204   return unwrap<LandingPadInst>(LandingPad)->getNumClauses();
3205 }
3206 
3207 LLVMValueRef LLVMGetClause(LLVMValueRef LandingPad, unsigned Idx) {
3208   return wrap(unwrap<LandingPadInst>(LandingPad)->getClause(Idx));
3209 }
3210 
3211 void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal) {
3212   unwrap<LandingPadInst>(LandingPad)->
3213     addClause(cast<Constant>(unwrap(ClauseVal)));
3214 }
3215 
3216 LLVMBool LLVMIsCleanup(LLVMValueRef LandingPad) {
3217   return unwrap<LandingPadInst>(LandingPad)->isCleanup();
3218 }
3219 
3220 void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val) {
3221   unwrap<LandingPadInst>(LandingPad)->setCleanup(Val);
3222 }
3223 
3224 void LLVMAddHandler(LLVMValueRef CatchSwitch, LLVMBasicBlockRef Dest) {
3225   unwrap<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Dest));
3226 }
3227 
3228 unsigned LLVMGetNumHandlers(LLVMValueRef CatchSwitch) {
3229   return unwrap<CatchSwitchInst>(CatchSwitch)->getNumHandlers();
3230 }
3231 
3232 void LLVMGetHandlers(LLVMValueRef CatchSwitch, LLVMBasicBlockRef *Handlers) {
3233   CatchSwitchInst *CSI = unwrap<CatchSwitchInst>(CatchSwitch);
3234   for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3235                                          E = CSI->handler_end(); I != E; ++I)
3236     *Handlers++ = wrap(*I);
3237 }
3238 
3239 LLVMValueRef LLVMGetParentCatchSwitch(LLVMValueRef CatchPad) {
3240   return wrap(unwrap<CatchPadInst>(CatchPad)->getCatchSwitch());
3241 }
3242 
3243 void LLVMSetParentCatchSwitch(LLVMValueRef CatchPad, LLVMValueRef CatchSwitch) {
3244   unwrap<CatchPadInst>(CatchPad)
3245     ->setCatchSwitch(unwrap<CatchSwitchInst>(CatchSwitch));
3246 }
3247 
3248 /*--.. Funclets ...........................................................--*/
3249 
3250 LLVMValueRef LLVMGetArgOperand(LLVMValueRef Funclet, unsigned i) {
3251   return wrap(unwrap<FuncletPadInst>(Funclet)->getArgOperand(i));
3252 }
3253 
3254 void LLVMSetArgOperand(LLVMValueRef Funclet, unsigned i, LLVMValueRef value) {
3255   unwrap<FuncletPadInst>(Funclet)->setArgOperand(i, unwrap(value));
3256 }
3257 
3258 /*--.. Arithmetic ..........................................................--*/
3259 
3260 LLVMValueRef LLVMBuildAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3261                           const char *Name) {
3262   return wrap(unwrap(B)->CreateAdd(unwrap(LHS), unwrap(RHS), Name));
3263 }
3264 
3265 LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3266                           const char *Name) {
3267   return wrap(unwrap(B)->CreateNSWAdd(unwrap(LHS), unwrap(RHS), Name));
3268 }
3269 
3270 LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3271                           const char *Name) {
3272   return wrap(unwrap(B)->CreateNUWAdd(unwrap(LHS), unwrap(RHS), Name));
3273 }
3274 
3275 LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3276                           const char *Name) {
3277   return wrap(unwrap(B)->CreateFAdd(unwrap(LHS), unwrap(RHS), Name));
3278 }
3279 
3280 LLVMValueRef LLVMBuildSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3281                           const char *Name) {
3282   return wrap(unwrap(B)->CreateSub(unwrap(LHS), unwrap(RHS), Name));
3283 }
3284 
3285 LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3286                           const char *Name) {
3287   return wrap(unwrap(B)->CreateNSWSub(unwrap(LHS), unwrap(RHS), Name));
3288 }
3289 
3290 LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3291                           const char *Name) {
3292   return wrap(unwrap(B)->CreateNUWSub(unwrap(LHS), unwrap(RHS), Name));
3293 }
3294 
3295 LLVMValueRef LLVMBuildFSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3296                           const char *Name) {
3297   return wrap(unwrap(B)->CreateFSub(unwrap(LHS), unwrap(RHS), Name));
3298 }
3299 
3300 LLVMValueRef LLVMBuildMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3301                           const char *Name) {
3302   return wrap(unwrap(B)->CreateMul(unwrap(LHS), unwrap(RHS), Name));
3303 }
3304 
3305 LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3306                           const char *Name) {
3307   return wrap(unwrap(B)->CreateNSWMul(unwrap(LHS), unwrap(RHS), Name));
3308 }
3309 
3310 LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3311                           const char *Name) {
3312   return wrap(unwrap(B)->CreateNUWMul(unwrap(LHS), unwrap(RHS), Name));
3313 }
3314 
3315 LLVMValueRef LLVMBuildFMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3316                           const char *Name) {
3317   return wrap(unwrap(B)->CreateFMul(unwrap(LHS), unwrap(RHS), Name));
3318 }
3319 
3320 LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3321                            const char *Name) {
3322   return wrap(unwrap(B)->CreateUDiv(unwrap(LHS), unwrap(RHS), Name));
3323 }
3324 
3325 LLVMValueRef LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,
3326                                 LLVMValueRef RHS, const char *Name) {
3327   return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));
3328 }
3329 
3330 LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3331                            const char *Name) {
3332   return wrap(unwrap(B)->CreateSDiv(unwrap(LHS), unwrap(RHS), Name));
3333 }
3334 
3335 LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef B, LLVMValueRef LHS,
3336                                 LLVMValueRef RHS, const char *Name) {
3337   return wrap(unwrap(B)->CreateExactSDiv(unwrap(LHS), unwrap(RHS), Name));
3338 }
3339 
3340 LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3341                            const char *Name) {
3342   return wrap(unwrap(B)->CreateFDiv(unwrap(LHS), unwrap(RHS), Name));
3343 }
3344 
3345 LLVMValueRef LLVMBuildURem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3346                            const char *Name) {
3347   return wrap(unwrap(B)->CreateURem(unwrap(LHS), unwrap(RHS), Name));
3348 }
3349 
3350 LLVMValueRef LLVMBuildSRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3351                            const char *Name) {
3352   return wrap(unwrap(B)->CreateSRem(unwrap(LHS), unwrap(RHS), Name));
3353 }
3354 
3355 LLVMValueRef LLVMBuildFRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3356                            const char *Name) {
3357   return wrap(unwrap(B)->CreateFRem(unwrap(LHS), unwrap(RHS), Name));
3358 }
3359 
3360 LLVMValueRef LLVMBuildShl(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3361                           const char *Name) {
3362   return wrap(unwrap(B)->CreateShl(unwrap(LHS), unwrap(RHS), Name));
3363 }
3364 
3365 LLVMValueRef LLVMBuildLShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3366                            const char *Name) {
3367   return wrap(unwrap(B)->CreateLShr(unwrap(LHS), unwrap(RHS), Name));
3368 }
3369 
3370 LLVMValueRef LLVMBuildAShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3371                            const char *Name) {
3372   return wrap(unwrap(B)->CreateAShr(unwrap(LHS), unwrap(RHS), Name));
3373 }
3374 
3375 LLVMValueRef LLVMBuildAnd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3376                           const char *Name) {
3377   return wrap(unwrap(B)->CreateAnd(unwrap(LHS), unwrap(RHS), Name));
3378 }
3379 
3380 LLVMValueRef LLVMBuildOr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3381                          const char *Name) {
3382   return wrap(unwrap(B)->CreateOr(unwrap(LHS), unwrap(RHS), Name));
3383 }
3384 
3385 LLVMValueRef LLVMBuildXor(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3386                           const char *Name) {
3387   return wrap(unwrap(B)->CreateXor(unwrap(LHS), unwrap(RHS), Name));
3388 }
3389 
3390 LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op,
3391                             LLVMValueRef LHS, LLVMValueRef RHS,
3392                             const char *Name) {
3393   return wrap(unwrap(B)->CreateBinOp(Instruction::BinaryOps(map_from_llvmopcode(Op)), unwrap(LHS),
3394                                      unwrap(RHS), Name));
3395 }
3396 
3397 LLVMValueRef LLVMBuildNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3398   return wrap(unwrap(B)->CreateNeg(unwrap(V), Name));
3399 }
3400 
3401 LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V,
3402                              const char *Name) {
3403   return wrap(unwrap(B)->CreateNSWNeg(unwrap(V), Name));
3404 }
3405 
3406 LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,
3407                              const char *Name) {
3408   return wrap(unwrap(B)->CreateNUWNeg(unwrap(V), Name));
3409 }
3410 
3411 LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3412   return wrap(unwrap(B)->CreateFNeg(unwrap(V), Name));
3413 }
3414 
3415 LLVMValueRef LLVMBuildNot(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3416   return wrap(unwrap(B)->CreateNot(unwrap(V), Name));
3417 }
3418 
3419 /*--.. Memory ..............................................................--*/
3420 
3421 LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
3422                              const char *Name) {
3423   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
3424   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
3425   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
3426   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
3427                                                ITy, unwrap(Ty), AllocSize,
3428                                                nullptr, nullptr, "");
3429   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
3430 }
3431 
3432 LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
3433                                   LLVMValueRef Val, const char *Name) {
3434   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
3435   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
3436   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
3437   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
3438                                                ITy, unwrap(Ty), AllocSize,
3439                                                unwrap(Val), nullptr, "");
3440   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
3441 }
3442 
3443 LLVMValueRef LLVMBuildMemSet(LLVMBuilderRef B, LLVMValueRef Ptr,
3444                              LLVMValueRef Val, LLVMValueRef Len,
3445                              unsigned Align) {
3446   return wrap(unwrap(B)->CreateMemSet(unwrap(Ptr), unwrap(Val), unwrap(Len),
3447                                       MaybeAlign(Align)));
3448 }
3449 
3450 LLVMValueRef LLVMBuildMemCpy(LLVMBuilderRef B,
3451                              LLVMValueRef Dst, unsigned DstAlign,
3452                              LLVMValueRef Src, unsigned SrcAlign,
3453                              LLVMValueRef Size) {
3454   return wrap(unwrap(B)->CreateMemCpy(unwrap(Dst), MaybeAlign(DstAlign),
3455                                       unwrap(Src), MaybeAlign(SrcAlign),
3456                                       unwrap(Size)));
3457 }
3458 
3459 LLVMValueRef LLVMBuildMemMove(LLVMBuilderRef B,
3460                               LLVMValueRef Dst, unsigned DstAlign,
3461                               LLVMValueRef Src, unsigned SrcAlign,
3462                               LLVMValueRef Size) {
3463   return wrap(unwrap(B)->CreateMemMove(unwrap(Dst), MaybeAlign(DstAlign),
3464                                        unwrap(Src), MaybeAlign(SrcAlign),
3465                                        unwrap(Size)));
3466 }
3467 
3468 LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
3469                              const char *Name) {
3470   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), nullptr, Name));
3471 }
3472 
3473 LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
3474                                   LLVMValueRef Val, const char *Name) {
3475   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), unwrap(Val), Name));
3476 }
3477 
3478 LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) {
3479   return wrap(unwrap(B)->Insert(
3480      CallInst::CreateFree(unwrap(PointerVal), unwrap(B)->GetInsertBlock())));
3481 }
3482 
3483 LLVMValueRef LLVMBuildLoad(LLVMBuilderRef B, LLVMValueRef PointerVal,
3484                            const char *Name) {
3485   Value *V = unwrap(PointerVal);
3486   PointerType *Ty = cast<PointerType>(V->getType());
3487 
3488   return wrap(unwrap(B)->CreateLoad(Ty->getElementType(), V, Name));
3489 }
3490 
3491 LLVMValueRef LLVMBuildLoad2(LLVMBuilderRef B, LLVMTypeRef Ty,
3492                             LLVMValueRef PointerVal, const char *Name) {
3493   return wrap(unwrap(B)->CreateLoad(unwrap(Ty), unwrap(PointerVal), Name));
3494 }
3495 
3496 LLVMValueRef LLVMBuildStore(LLVMBuilderRef B, LLVMValueRef Val,
3497                             LLVMValueRef PointerVal) {
3498   return wrap(unwrap(B)->CreateStore(unwrap(Val), unwrap(PointerVal)));
3499 }
3500 
3501 static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) {
3502   switch (Ordering) {
3503     case LLVMAtomicOrderingNotAtomic: return AtomicOrdering::NotAtomic;
3504     case LLVMAtomicOrderingUnordered: return AtomicOrdering::Unordered;
3505     case LLVMAtomicOrderingMonotonic: return AtomicOrdering::Monotonic;
3506     case LLVMAtomicOrderingAcquire: return AtomicOrdering::Acquire;
3507     case LLVMAtomicOrderingRelease: return AtomicOrdering::Release;
3508     case LLVMAtomicOrderingAcquireRelease:
3509       return AtomicOrdering::AcquireRelease;
3510     case LLVMAtomicOrderingSequentiallyConsistent:
3511       return AtomicOrdering::SequentiallyConsistent;
3512   }
3513 
3514   llvm_unreachable("Invalid LLVMAtomicOrdering value!");
3515 }
3516 
3517 static LLVMAtomicOrdering mapToLLVMOrdering(AtomicOrdering Ordering) {
3518   switch (Ordering) {
3519     case AtomicOrdering::NotAtomic: return LLVMAtomicOrderingNotAtomic;
3520     case AtomicOrdering::Unordered: return LLVMAtomicOrderingUnordered;
3521     case AtomicOrdering::Monotonic: return LLVMAtomicOrderingMonotonic;
3522     case AtomicOrdering::Acquire: return LLVMAtomicOrderingAcquire;
3523     case AtomicOrdering::Release: return LLVMAtomicOrderingRelease;
3524     case AtomicOrdering::AcquireRelease:
3525       return LLVMAtomicOrderingAcquireRelease;
3526     case AtomicOrdering::SequentiallyConsistent:
3527       return LLVMAtomicOrderingSequentiallyConsistent;
3528   }
3529 
3530   llvm_unreachable("Invalid AtomicOrdering value!");
3531 }
3532 
3533 static AtomicRMWInst::BinOp mapFromLLVMRMWBinOp(LLVMAtomicRMWBinOp BinOp) {
3534   switch (BinOp) {
3535     case LLVMAtomicRMWBinOpXchg: return AtomicRMWInst::Xchg;
3536     case LLVMAtomicRMWBinOpAdd: return AtomicRMWInst::Add;
3537     case LLVMAtomicRMWBinOpSub: return AtomicRMWInst::Sub;
3538     case LLVMAtomicRMWBinOpAnd: return AtomicRMWInst::And;
3539     case LLVMAtomicRMWBinOpNand: return AtomicRMWInst::Nand;
3540     case LLVMAtomicRMWBinOpOr: return AtomicRMWInst::Or;
3541     case LLVMAtomicRMWBinOpXor: return AtomicRMWInst::Xor;
3542     case LLVMAtomicRMWBinOpMax: return AtomicRMWInst::Max;
3543     case LLVMAtomicRMWBinOpMin: return AtomicRMWInst::Min;
3544     case LLVMAtomicRMWBinOpUMax: return AtomicRMWInst::UMax;
3545     case LLVMAtomicRMWBinOpUMin: return AtomicRMWInst::UMin;
3546     case LLVMAtomicRMWBinOpFAdd: return AtomicRMWInst::FAdd;
3547     case LLVMAtomicRMWBinOpFSub: return AtomicRMWInst::FSub;
3548   }
3549 
3550   llvm_unreachable("Invalid LLVMAtomicRMWBinOp value!");
3551 }
3552 
3553 static LLVMAtomicRMWBinOp mapToLLVMRMWBinOp(AtomicRMWInst::BinOp BinOp) {
3554   switch (BinOp) {
3555     case AtomicRMWInst::Xchg: return LLVMAtomicRMWBinOpXchg;
3556     case AtomicRMWInst::Add: return LLVMAtomicRMWBinOpAdd;
3557     case AtomicRMWInst::Sub: return LLVMAtomicRMWBinOpSub;
3558     case AtomicRMWInst::And: return LLVMAtomicRMWBinOpAnd;
3559     case AtomicRMWInst::Nand: return LLVMAtomicRMWBinOpNand;
3560     case AtomicRMWInst::Or: return LLVMAtomicRMWBinOpOr;
3561     case AtomicRMWInst::Xor: return LLVMAtomicRMWBinOpXor;
3562     case AtomicRMWInst::Max: return LLVMAtomicRMWBinOpMax;
3563     case AtomicRMWInst::Min: return LLVMAtomicRMWBinOpMin;
3564     case AtomicRMWInst::UMax: return LLVMAtomicRMWBinOpUMax;
3565     case AtomicRMWInst::UMin: return LLVMAtomicRMWBinOpUMin;
3566     case AtomicRMWInst::FAdd: return LLVMAtomicRMWBinOpFAdd;
3567     case AtomicRMWInst::FSub: return LLVMAtomicRMWBinOpFSub;
3568     default: break;
3569   }
3570 
3571   llvm_unreachable("Invalid AtomicRMWBinOp value!");
3572 }
3573 
3574 // TODO: Should this and other atomic instructions support building with
3575 // "syncscope"?
3576 LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering Ordering,
3577                             LLVMBool isSingleThread, const char *Name) {
3578   return wrap(
3579     unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering),
3580                            isSingleThread ? SyncScope::SingleThread
3581                                           : SyncScope::System,
3582                            Name));
3583 }
3584 
3585 LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3586                           LLVMValueRef *Indices, unsigned NumIndices,
3587                           const char *Name) {
3588   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3589   Value *Val = unwrap(Pointer);
3590   Type *Ty =
3591       cast<PointerType>(Val->getType()->getScalarType())->getElementType();
3592   return wrap(unwrap(B)->CreateGEP(Ty, Val, IdxList, Name));
3593 }
3594 
3595 LLVMValueRef LLVMBuildGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3596                            LLVMValueRef Pointer, LLVMValueRef *Indices,
3597                            unsigned NumIndices, const char *Name) {
3598   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3599   return wrap(unwrap(B)->CreateGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));
3600 }
3601 
3602 LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3603                                   LLVMValueRef *Indices, unsigned NumIndices,
3604                                   const char *Name) {
3605   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3606   Value *Val = unwrap(Pointer);
3607   Type *Ty =
3608       cast<PointerType>(Val->getType()->getScalarType())->getElementType();
3609   return wrap(unwrap(B)->CreateInBoundsGEP(Ty, Val, IdxList, Name));
3610 }
3611 
3612 LLVMValueRef LLVMBuildInBoundsGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3613                                    LLVMValueRef Pointer, LLVMValueRef *Indices,
3614                                    unsigned NumIndices, const char *Name) {
3615   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3616   return wrap(
3617       unwrap(B)->CreateInBoundsGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));
3618 }
3619 
3620 LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3621                                 unsigned Idx, const char *Name) {
3622   Value *Val = unwrap(Pointer);
3623   Type *Ty =
3624       cast<PointerType>(Val->getType()->getScalarType())->getElementType();
3625   return wrap(unwrap(B)->CreateStructGEP(Ty, Val, Idx, Name));
3626 }
3627 
3628 LLVMValueRef LLVMBuildStructGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3629                                  LLVMValueRef Pointer, unsigned Idx,
3630                                  const char *Name) {
3631   return wrap(
3632       unwrap(B)->CreateStructGEP(unwrap(Ty), unwrap(Pointer), Idx, Name));
3633 }
3634 
3635 LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str,
3636                                    const char *Name) {
3637   return wrap(unwrap(B)->CreateGlobalString(Str, Name));
3638 }
3639 
3640 LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,
3641                                       const char *Name) {
3642   return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name));
3643 }
3644 
3645 LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) {
3646   Value *P = unwrap<Value>(MemAccessInst);
3647   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3648     return LI->isVolatile();
3649   if (StoreInst *SI = dyn_cast<StoreInst>(P))
3650     return SI->isVolatile();
3651   if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(P))
3652     return AI->isVolatile();
3653   return cast<AtomicCmpXchgInst>(P)->isVolatile();
3654 }
3655 
3656 void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) {
3657   Value *P = unwrap<Value>(MemAccessInst);
3658   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3659     return LI->setVolatile(isVolatile);
3660   if (StoreInst *SI = dyn_cast<StoreInst>(P))
3661     return SI->setVolatile(isVolatile);
3662   if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(P))
3663     return AI->setVolatile(isVolatile);
3664   return cast<AtomicCmpXchgInst>(P)->setVolatile(isVolatile);
3665 }
3666 
3667 LLVMBool LLVMGetWeak(LLVMValueRef CmpXchgInst) {
3668   return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->isWeak();
3669 }
3670 
3671 void LLVMSetWeak(LLVMValueRef CmpXchgInst, LLVMBool isWeak) {
3672   return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->setWeak(isWeak);
3673 }
3674 
3675 LLVMAtomicOrdering LLVMGetOrdering(LLVMValueRef MemAccessInst) {
3676   Value *P = unwrap<Value>(MemAccessInst);
3677   AtomicOrdering O;
3678   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3679     O = LI->getOrdering();
3680   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
3681     O = SI->getOrdering();
3682   else
3683     O = cast<AtomicRMWInst>(P)->getOrdering();
3684   return mapToLLVMOrdering(O);
3685 }
3686 
3687 void LLVMSetOrdering(LLVMValueRef MemAccessInst, LLVMAtomicOrdering Ordering) {
3688   Value *P = unwrap<Value>(MemAccessInst);
3689   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
3690 
3691   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3692     return LI->setOrdering(O);
3693   return cast<StoreInst>(P)->setOrdering(O);
3694 }
3695 
3696 LLVMAtomicRMWBinOp LLVMGetAtomicRMWBinOp(LLVMValueRef Inst) {
3697   return mapToLLVMRMWBinOp(unwrap<AtomicRMWInst>(Inst)->getOperation());
3698 }
3699 
3700 void LLVMSetAtomicRMWBinOp(LLVMValueRef Inst, LLVMAtomicRMWBinOp BinOp) {
3701   unwrap<AtomicRMWInst>(Inst)->setOperation(mapFromLLVMRMWBinOp(BinOp));
3702 }
3703 
3704 /*--.. Casts ...............................................................--*/
3705 
3706 LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val,
3707                             LLVMTypeRef DestTy, const char *Name) {
3708   return wrap(unwrap(B)->CreateTrunc(unwrap(Val), unwrap(DestTy), Name));
3709 }
3710 
3711 LLVMValueRef LLVMBuildZExt(LLVMBuilderRef B, LLVMValueRef Val,
3712                            LLVMTypeRef DestTy, const char *Name) {
3713   return wrap(unwrap(B)->CreateZExt(unwrap(Val), unwrap(DestTy), Name));
3714 }
3715 
3716 LLVMValueRef LLVMBuildSExt(LLVMBuilderRef B, LLVMValueRef Val,
3717                            LLVMTypeRef DestTy, const char *Name) {
3718   return wrap(unwrap(B)->CreateSExt(unwrap(Val), unwrap(DestTy), Name));
3719 }
3720 
3721 LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef B, LLVMValueRef Val,
3722                              LLVMTypeRef DestTy, const char *Name) {
3723   return wrap(unwrap(B)->CreateFPToUI(unwrap(Val), unwrap(DestTy), Name));
3724 }
3725 
3726 LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef B, LLVMValueRef Val,
3727                              LLVMTypeRef DestTy, const char *Name) {
3728   return wrap(unwrap(B)->CreateFPToSI(unwrap(Val), unwrap(DestTy), Name));
3729 }
3730 
3731 LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef B, LLVMValueRef Val,
3732                              LLVMTypeRef DestTy, const char *Name) {
3733   return wrap(unwrap(B)->CreateUIToFP(unwrap(Val), unwrap(DestTy), Name));
3734 }
3735 
3736 LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef B, LLVMValueRef Val,
3737                              LLVMTypeRef DestTy, const char *Name) {
3738   return wrap(unwrap(B)->CreateSIToFP(unwrap(Val), unwrap(DestTy), Name));
3739 }
3740 
3741 LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef B, LLVMValueRef Val,
3742                               LLVMTypeRef DestTy, const char *Name) {
3743   return wrap(unwrap(B)->CreateFPTrunc(unwrap(Val), unwrap(DestTy), Name));
3744 }
3745 
3746 LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef B, LLVMValueRef Val,
3747                             LLVMTypeRef DestTy, const char *Name) {
3748   return wrap(unwrap(B)->CreateFPExt(unwrap(Val), unwrap(DestTy), Name));
3749 }
3750 
3751 LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef B, LLVMValueRef Val,
3752                                LLVMTypeRef DestTy, const char *Name) {
3753   return wrap(unwrap(B)->CreatePtrToInt(unwrap(Val), unwrap(DestTy), Name));
3754 }
3755 
3756 LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef B, LLVMValueRef Val,
3757                                LLVMTypeRef DestTy, const char *Name) {
3758   return wrap(unwrap(B)->CreateIntToPtr(unwrap(Val), unwrap(DestTy), Name));
3759 }
3760 
3761 LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3762                               LLVMTypeRef DestTy, const char *Name) {
3763   return wrap(unwrap(B)->CreateBitCast(unwrap(Val), unwrap(DestTy), Name));
3764 }
3765 
3766 LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef B, LLVMValueRef Val,
3767                                     LLVMTypeRef DestTy, const char *Name) {
3768   return wrap(unwrap(B)->CreateAddrSpaceCast(unwrap(Val), unwrap(DestTy), Name));
3769 }
3770 
3771 LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3772                                     LLVMTypeRef DestTy, const char *Name) {
3773   return wrap(unwrap(B)->CreateZExtOrBitCast(unwrap(Val), unwrap(DestTy),
3774                                              Name));
3775 }
3776 
3777 LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3778                                     LLVMTypeRef DestTy, const char *Name) {
3779   return wrap(unwrap(B)->CreateSExtOrBitCast(unwrap(Val), unwrap(DestTy),
3780                                              Name));
3781 }
3782 
3783 LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3784                                      LLVMTypeRef DestTy, const char *Name) {
3785   return wrap(unwrap(B)->CreateTruncOrBitCast(unwrap(Val), unwrap(DestTy),
3786                                               Name));
3787 }
3788 
3789 LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val,
3790                            LLVMTypeRef DestTy, const char *Name) {
3791   return wrap(unwrap(B)->CreateCast(Instruction::CastOps(map_from_llvmopcode(Op)), unwrap(Val),
3792                                     unwrap(DestTy), Name));
3793 }
3794 
3795 LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef B, LLVMValueRef Val,
3796                                   LLVMTypeRef DestTy, const char *Name) {
3797   return wrap(unwrap(B)->CreatePointerCast(unwrap(Val), unwrap(DestTy), Name));
3798 }
3799 
3800 LLVMValueRef LLVMBuildIntCast2(LLVMBuilderRef B, LLVMValueRef Val,
3801                                LLVMTypeRef DestTy, LLVMBool IsSigned,
3802                                const char *Name) {
3803   return wrap(
3804       unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), IsSigned, Name));
3805 }
3806 
3807 LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
3808                               LLVMTypeRef DestTy, const char *Name) {
3809   return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy),
3810                                        /*isSigned*/true, Name));
3811 }
3812 
3813 LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef B, LLVMValueRef Val,
3814                              LLVMTypeRef DestTy, const char *Name) {
3815   return wrap(unwrap(B)->CreateFPCast(unwrap(Val), unwrap(DestTy), Name));
3816 }
3817 
3818 /*--.. Comparisons .........................................................--*/
3819 
3820 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op,
3821                            LLVMValueRef LHS, LLVMValueRef RHS,
3822                            const char *Name) {
3823   return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op),
3824                                     unwrap(LHS), unwrap(RHS), Name));
3825 }
3826 
3827 LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op,
3828                            LLVMValueRef LHS, LLVMValueRef RHS,
3829                            const char *Name) {
3830   return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op),
3831                                     unwrap(LHS), unwrap(RHS), Name));
3832 }
3833 
3834 /*--.. Miscellaneous instructions ..........................................--*/
3835 
3836 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) {
3837   return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name));
3838 }
3839 
3840 LLVMValueRef LLVMBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
3841                            LLVMValueRef *Args, unsigned NumArgs,
3842                            const char *Name) {
3843   Value *V = unwrap(Fn);
3844   FunctionType *FnT =
3845       cast<FunctionType>(cast<PointerType>(V->getType())->getElementType());
3846 
3847   return wrap(unwrap(B)->CreateCall(FnT, unwrap(Fn),
3848                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3849 }
3850 
3851 LLVMValueRef LLVMBuildCall2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
3852                             LLVMValueRef *Args, unsigned NumArgs,
3853                             const char *Name) {
3854   FunctionType *FTy = unwrap<FunctionType>(Ty);
3855   return wrap(unwrap(B)->CreateCall(FTy, unwrap(Fn),
3856                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3857 }
3858 
3859 LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If,
3860                              LLVMValueRef Then, LLVMValueRef Else,
3861                              const char *Name) {
3862   return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else),
3863                                       Name));
3864 }
3865 
3866 LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List,
3867                             LLVMTypeRef Ty, const char *Name) {
3868   return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name));
3869 }
3870 
3871 LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal,
3872                                       LLVMValueRef Index, const char *Name) {
3873   return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index),
3874                                               Name));
3875 }
3876 
3877 LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal,
3878                                     LLVMValueRef EltVal, LLVMValueRef Index,
3879                                     const char *Name) {
3880   return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal),
3881                                              unwrap(Index), Name));
3882 }
3883 
3884 LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1,
3885                                     LLVMValueRef V2, LLVMValueRef Mask,
3886                                     const char *Name) {
3887   return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2),
3888                                              unwrap(Mask), Name));
3889 }
3890 
3891 LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal,
3892                                    unsigned Index, const char *Name) {
3893   return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name));
3894 }
3895 
3896 LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal,
3897                                   LLVMValueRef EltVal, unsigned Index,
3898                                   const char *Name) {
3899   return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal),
3900                                            Index, Name));
3901 }
3902 
3903 LLVMValueRef LLVMBuildFreeze(LLVMBuilderRef B, LLVMValueRef Val,
3904                              const char *Name) {
3905   return wrap(unwrap(B)->CreateFreeze(unwrap(Val), Name));
3906 }
3907 
3908 LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val,
3909                              const char *Name) {
3910   return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name));
3911 }
3912 
3913 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val,
3914                                 const char *Name) {
3915   return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name));
3916 }
3917 
3918 LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef B, LLVMValueRef LHS,
3919                               LLVMValueRef RHS, const char *Name) {
3920   return wrap(unwrap(B)->CreatePtrDiff(unwrap(LHS), unwrap(RHS), Name));
3921 }
3922 
3923 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op,
3924                                LLVMValueRef PTR, LLVMValueRef Val,
3925                                LLVMAtomicOrdering ordering,
3926                                LLVMBool singleThread) {
3927   AtomicRMWInst::BinOp intop = mapFromLLVMRMWBinOp(op);
3928   return wrap(unwrap(B)->CreateAtomicRMW(intop, unwrap(PTR), unwrap(Val),
3929     mapFromLLVMOrdering(ordering), singleThread ? SyncScope::SingleThread
3930                                                 : SyncScope::System));
3931 }
3932 
3933 LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Ptr,
3934                                     LLVMValueRef Cmp, LLVMValueRef New,
3935                                     LLVMAtomicOrdering SuccessOrdering,
3936                                     LLVMAtomicOrdering FailureOrdering,
3937                                     LLVMBool singleThread) {
3938 
3939   return wrap(unwrap(B)->CreateAtomicCmpXchg(unwrap(Ptr), unwrap(Cmp),
3940                 unwrap(New), mapFromLLVMOrdering(SuccessOrdering),
3941                 mapFromLLVMOrdering(FailureOrdering),
3942                 singleThread ? SyncScope::SingleThread : SyncScope::System));
3943 }
3944 
3945 
3946 LLVMBool LLVMIsAtomicSingleThread(LLVMValueRef AtomicInst) {
3947   Value *P = unwrap<Value>(AtomicInst);
3948 
3949   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
3950     return I->getSyncScopeID() == SyncScope::SingleThread;
3951   return cast<AtomicCmpXchgInst>(P)->getSyncScopeID() ==
3952              SyncScope::SingleThread;
3953 }
3954 
3955 void LLVMSetAtomicSingleThread(LLVMValueRef AtomicInst, LLVMBool NewValue) {
3956   Value *P = unwrap<Value>(AtomicInst);
3957   SyncScope::ID SSID = NewValue ? SyncScope::SingleThread : SyncScope::System;
3958 
3959   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
3960     return I->setSyncScopeID(SSID);
3961   return cast<AtomicCmpXchgInst>(P)->setSyncScopeID(SSID);
3962 }
3963 
3964 LLVMAtomicOrdering LLVMGetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst)  {
3965   Value *P = unwrap<Value>(CmpXchgInst);
3966   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getSuccessOrdering());
3967 }
3968 
3969 void LLVMSetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst,
3970                                    LLVMAtomicOrdering Ordering) {
3971   Value *P = unwrap<Value>(CmpXchgInst);
3972   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
3973 
3974   return cast<AtomicCmpXchgInst>(P)->setSuccessOrdering(O);
3975 }
3976 
3977 LLVMAtomicOrdering LLVMGetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst)  {
3978   Value *P = unwrap<Value>(CmpXchgInst);
3979   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getFailureOrdering());
3980 }
3981 
3982 void LLVMSetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst,
3983                                    LLVMAtomicOrdering Ordering) {
3984   Value *P = unwrap<Value>(CmpXchgInst);
3985   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
3986 
3987   return cast<AtomicCmpXchgInst>(P)->setFailureOrdering(O);
3988 }
3989 
3990 /*===-- Module providers --------------------------------------------------===*/
3991 
3992 LLVMModuleProviderRef
3993 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {
3994   return reinterpret_cast<LLVMModuleProviderRef>(M);
3995 }
3996 
3997 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {
3998   delete unwrap(MP);
3999 }
4000 
4001 
4002 /*===-- Memory buffers ----------------------------------------------------===*/
4003 
4004 LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(
4005     const char *Path,
4006     LLVMMemoryBufferRef *OutMemBuf,
4007     char **OutMessage) {
4008 
4009   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
4010   if (std::error_code EC = MBOrErr.getError()) {
4011     *OutMessage = strdup(EC.message().c_str());
4012     return 1;
4013   }
4014   *OutMemBuf = wrap(MBOrErr.get().release());
4015   return 0;
4016 }
4017 
4018 LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
4019                                          char **OutMessage) {
4020   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();
4021   if (std::error_code EC = MBOrErr.getError()) {
4022     *OutMessage = strdup(EC.message().c_str());
4023     return 1;
4024   }
4025   *OutMemBuf = wrap(MBOrErr.get().release());
4026   return 0;
4027 }
4028 
4029 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
4030     const char *InputData,
4031     size_t InputDataLength,
4032     const char *BufferName,
4033     LLVMBool RequiresNullTerminator) {
4034 
4035   return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength),
4036                                          StringRef(BufferName),
4037                                          RequiresNullTerminator).release());
4038 }
4039 
4040 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(
4041     const char *InputData,
4042     size_t InputDataLength,
4043     const char *BufferName) {
4044 
4045   return wrap(
4046       MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength),
4047                                      StringRef(BufferName)).release());
4048 }
4049 
4050 const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) {
4051   return unwrap(MemBuf)->getBufferStart();
4052 }
4053 
4054 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) {
4055   return unwrap(MemBuf)->getBufferSize();
4056 }
4057 
4058 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) {
4059   delete unwrap(MemBuf);
4060 }
4061 
4062 /*===-- Pass Registry -----------------------------------------------------===*/
4063 
4064 LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void) {
4065   return wrap(PassRegistry::getPassRegistry());
4066 }
4067 
4068 /*===-- Pass Manager ------------------------------------------------------===*/
4069 
4070 LLVMPassManagerRef LLVMCreatePassManager() {
4071   return wrap(new legacy::PassManager());
4072 }
4073 
4074 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
4075   return wrap(new legacy::FunctionPassManager(unwrap(M)));
4076 }
4077 
4078 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
4079   return LLVMCreateFunctionPassManagerForModule(
4080                                             reinterpret_cast<LLVMModuleRef>(P));
4081 }
4082 
4083 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
4084   return unwrap<legacy::PassManager>(PM)->run(*unwrap(M));
4085 }
4086 
4087 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
4088   return unwrap<legacy::FunctionPassManager>(FPM)->doInitialization();
4089 }
4090 
4091 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
4092   return unwrap<legacy::FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
4093 }
4094 
4095 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
4096   return unwrap<legacy::FunctionPassManager>(FPM)->doFinalization();
4097 }
4098 
4099 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
4100   delete unwrap(PM);
4101 }
4102 
4103 /*===-- Threading ------------------------------------------------------===*/
4104 
4105 LLVMBool LLVMStartMultithreaded() {
4106   return LLVMIsMultithreaded();
4107 }
4108 
4109 void LLVMStopMultithreaded() {
4110 }
4111 
4112 LLVMBool LLVMIsMultithreaded() {
4113   return llvm_is_multithreaded();
4114 }
4115