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