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