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