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