xref: /llvm-project-15.0.7/llvm/lib/IR/Core.cpp (revision 7283f48a)
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 LLVMContextSetOpaquePointers(LLVMContextRef C, LLVMBool OpaquePointers) {
119   unwrap(C)->setOpaquePointers(OpaquePointers);
120 }
121 
122 void LLVMContextDispose(LLVMContextRef C) {
123   delete unwrap(C);
124 }
125 
126 unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char *Name,
127                                   unsigned SLen) {
128   return unwrap(C)->getMDKindID(StringRef(Name, SLen));
129 }
130 
131 unsigned LLVMGetMDKindID(const char *Name, unsigned SLen) {
132   return LLVMGetMDKindIDInContext(LLVMGetGlobalContext(), Name, SLen);
133 }
134 
135 unsigned LLVMGetEnumAttributeKindForName(const char *Name, size_t SLen) {
136   return Attribute::getAttrKindFromName(StringRef(Name, SLen));
137 }
138 
139 unsigned LLVMGetLastEnumAttributeKind(void) {
140   return Attribute::AttrKind::EndAttrKinds;
141 }
142 
143 LLVMAttributeRef LLVMCreateEnumAttribute(LLVMContextRef C, unsigned KindID,
144                                          uint64_t Val) {
145   auto &Ctx = *unwrap(C);
146   auto AttrKind = (Attribute::AttrKind)KindID;
147 
148   if (AttrKind == Attribute::AttrKind::ByVal) {
149     // After r362128, byval attributes need to have a type attribute. Provide a
150     // NULL one until a proper API is added for this.
151     return wrap(Attribute::getWithByValType(Ctx, nullptr));
152   }
153 
154   if (AttrKind == Attribute::AttrKind::StructRet) {
155     // Same as byval.
156     return wrap(Attribute::getWithStructRetType(Ctx, nullptr));
157   }
158 
159   return wrap(Attribute::get(Ctx, AttrKind, Val));
160 }
161 
162 unsigned LLVMGetEnumAttributeKind(LLVMAttributeRef A) {
163   return unwrap(A).getKindAsEnum();
164 }
165 
166 uint64_t LLVMGetEnumAttributeValue(LLVMAttributeRef A) {
167   auto Attr = unwrap(A);
168   if (Attr.isEnumAttribute())
169     return 0;
170   return Attr.getValueAsInt();
171 }
172 
173 LLVMAttributeRef LLVMCreateTypeAttribute(LLVMContextRef C, unsigned KindID,
174                                          LLVMTypeRef type_ref) {
175   auto &Ctx = *unwrap(C);
176   auto AttrKind = (Attribute::AttrKind)KindID;
177   return wrap(Attribute::get(Ctx, AttrKind, unwrap(type_ref)));
178 }
179 
180 LLVMTypeRef LLVMGetTypeAttributeValue(LLVMAttributeRef A) {
181   auto Attr = unwrap(A);
182   return wrap(Attr.getValueAsType());
183 }
184 
185 LLVMAttributeRef LLVMCreateStringAttribute(LLVMContextRef C,
186                                            const char *K, unsigned KLength,
187                                            const char *V, unsigned VLength) {
188   return wrap(Attribute::get(*unwrap(C), StringRef(K, KLength),
189                              StringRef(V, VLength)));
190 }
191 
192 const char *LLVMGetStringAttributeKind(LLVMAttributeRef A,
193                                        unsigned *Length) {
194   auto S = unwrap(A).getKindAsString();
195   *Length = S.size();
196   return S.data();
197 }
198 
199 const char *LLVMGetStringAttributeValue(LLVMAttributeRef A,
200                                         unsigned *Length) {
201   auto S = unwrap(A).getValueAsString();
202   *Length = S.size();
203   return S.data();
204 }
205 
206 LLVMBool LLVMIsEnumAttribute(LLVMAttributeRef A) {
207   auto Attr = unwrap(A);
208   return Attr.isEnumAttribute() || Attr.isIntAttribute();
209 }
210 
211 LLVMBool LLVMIsStringAttribute(LLVMAttributeRef A) {
212   return unwrap(A).isStringAttribute();
213 }
214 
215 LLVMBool LLVMIsTypeAttribute(LLVMAttributeRef A) {
216   return unwrap(A).isTypeAttribute();
217 }
218 
219 char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {
220   std::string MsgStorage;
221   raw_string_ostream Stream(MsgStorage);
222   DiagnosticPrinterRawOStream DP(Stream);
223 
224   unwrap(DI)->print(DP);
225   Stream.flush();
226 
227   return LLVMCreateMessage(MsgStorage.c_str());
228 }
229 
230 LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI) {
231     LLVMDiagnosticSeverity severity;
232 
233     switch(unwrap(DI)->getSeverity()) {
234     default:
235       severity = LLVMDSError;
236       break;
237     case DS_Warning:
238       severity = LLVMDSWarning;
239       break;
240     case DS_Remark:
241       severity = LLVMDSRemark;
242       break;
243     case DS_Note:
244       severity = LLVMDSNote;
245       break;
246     }
247 
248     return severity;
249 }
250 
251 /*===-- Operations on modules ---------------------------------------------===*/
252 
253 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {
254   return wrap(new Module(ModuleID, *GlobalContext));
255 }
256 
257 LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,
258                                                 LLVMContextRef C) {
259   return wrap(new Module(ModuleID, *unwrap(C)));
260 }
261 
262 void LLVMDisposeModule(LLVMModuleRef M) {
263   delete unwrap(M);
264 }
265 
266 const char *LLVMGetModuleIdentifier(LLVMModuleRef M, size_t *Len) {
267   auto &Str = unwrap(M)->getModuleIdentifier();
268   *Len = Str.length();
269   return Str.c_str();
270 }
271 
272 void LLVMSetModuleIdentifier(LLVMModuleRef M, const char *Ident, size_t Len) {
273   unwrap(M)->setModuleIdentifier(StringRef(Ident, Len));
274 }
275 
276 const char *LLVMGetSourceFileName(LLVMModuleRef M, size_t *Len) {
277   auto &Str = unwrap(M)->getSourceFileName();
278   *Len = Str.length();
279   return Str.c_str();
280 }
281 
282 void LLVMSetSourceFileName(LLVMModuleRef M, const char *Name, size_t Len) {
283   unwrap(M)->setSourceFileName(StringRef(Name, Len));
284 }
285 
286 /*--.. Data layout .........................................................--*/
287 const char *LLVMGetDataLayoutStr(LLVMModuleRef M) {
288   return unwrap(M)->getDataLayoutStr().c_str();
289 }
290 
291 const char *LLVMGetDataLayout(LLVMModuleRef M) {
292   return LLVMGetDataLayoutStr(M);
293 }
294 
295 void LLVMSetDataLayout(LLVMModuleRef M, const char *DataLayoutStr) {
296   unwrap(M)->setDataLayout(DataLayoutStr);
297 }
298 
299 /*--.. Target triple .......................................................--*/
300 const char * LLVMGetTarget(LLVMModuleRef M) {
301   return unwrap(M)->getTargetTriple().c_str();
302 }
303 
304 void LLVMSetTarget(LLVMModuleRef M, const char *Triple) {
305   unwrap(M)->setTargetTriple(Triple);
306 }
307 
308 /*--.. Module flags ........................................................--*/
309 struct LLVMOpaqueModuleFlagEntry {
310   LLVMModuleFlagBehavior Behavior;
311   const char *Key;
312   size_t KeyLen;
313   LLVMMetadataRef Metadata;
314 };
315 
316 static Module::ModFlagBehavior
317 map_to_llvmModFlagBehavior(LLVMModuleFlagBehavior Behavior) {
318   switch (Behavior) {
319   case LLVMModuleFlagBehaviorError:
320     return Module::ModFlagBehavior::Error;
321   case LLVMModuleFlagBehaviorWarning:
322     return Module::ModFlagBehavior::Warning;
323   case LLVMModuleFlagBehaviorRequire:
324     return Module::ModFlagBehavior::Require;
325   case LLVMModuleFlagBehaviorOverride:
326     return Module::ModFlagBehavior::Override;
327   case LLVMModuleFlagBehaviorAppend:
328     return Module::ModFlagBehavior::Append;
329   case LLVMModuleFlagBehaviorAppendUnique:
330     return Module::ModFlagBehavior::AppendUnique;
331   }
332   llvm_unreachable("Unknown LLVMModuleFlagBehavior");
333 }
334 
335 static LLVMModuleFlagBehavior
336 map_from_llvmModFlagBehavior(Module::ModFlagBehavior Behavior) {
337   switch (Behavior) {
338   case Module::ModFlagBehavior::Error:
339     return LLVMModuleFlagBehaviorError;
340   case Module::ModFlagBehavior::Warning:
341     return LLVMModuleFlagBehaviorWarning;
342   case Module::ModFlagBehavior::Require:
343     return LLVMModuleFlagBehaviorRequire;
344   case Module::ModFlagBehavior::Override:
345     return LLVMModuleFlagBehaviorOverride;
346   case Module::ModFlagBehavior::Append:
347     return LLVMModuleFlagBehaviorAppend;
348   case Module::ModFlagBehavior::AppendUnique:
349     return LLVMModuleFlagBehaviorAppendUnique;
350   default:
351     llvm_unreachable("Unhandled Flag Behavior");
352   }
353 }
354 
355 LLVMModuleFlagEntry *LLVMCopyModuleFlagsMetadata(LLVMModuleRef M, size_t *Len) {
356   SmallVector<Module::ModuleFlagEntry, 8> MFEs;
357   unwrap(M)->getModuleFlagsMetadata(MFEs);
358 
359   LLVMOpaqueModuleFlagEntry *Result = static_cast<LLVMOpaqueModuleFlagEntry *>(
360       safe_malloc(MFEs.size() * sizeof(LLVMOpaqueModuleFlagEntry)));
361   for (unsigned i = 0; i < MFEs.size(); ++i) {
362     const auto &ModuleFlag = MFEs[i];
363     Result[i].Behavior = map_from_llvmModFlagBehavior(ModuleFlag.Behavior);
364     Result[i].Key = ModuleFlag.Key->getString().data();
365     Result[i].KeyLen = ModuleFlag.Key->getString().size();
366     Result[i].Metadata = wrap(ModuleFlag.Val);
367   }
368   *Len = MFEs.size();
369   return Result;
370 }
371 
372 void LLVMDisposeModuleFlagsMetadata(LLVMModuleFlagEntry *Entries) {
373   free(Entries);
374 }
375 
376 LLVMModuleFlagBehavior
377 LLVMModuleFlagEntriesGetFlagBehavior(LLVMModuleFlagEntry *Entries,
378                                      unsigned Index) {
379   LLVMOpaqueModuleFlagEntry MFE =
380       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
381   return MFE.Behavior;
382 }
383 
384 const char *LLVMModuleFlagEntriesGetKey(LLVMModuleFlagEntry *Entries,
385                                         unsigned Index, size_t *Len) {
386   LLVMOpaqueModuleFlagEntry MFE =
387       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
388   *Len = MFE.KeyLen;
389   return MFE.Key;
390 }
391 
392 LLVMMetadataRef LLVMModuleFlagEntriesGetMetadata(LLVMModuleFlagEntry *Entries,
393                                                  unsigned Index) {
394   LLVMOpaqueModuleFlagEntry MFE =
395       static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);
396   return MFE.Metadata;
397 }
398 
399 LLVMMetadataRef LLVMGetModuleFlag(LLVMModuleRef M,
400                                   const char *Key, size_t KeyLen) {
401   return wrap(unwrap(M)->getModuleFlag({Key, KeyLen}));
402 }
403 
404 void LLVMAddModuleFlag(LLVMModuleRef M, LLVMModuleFlagBehavior Behavior,
405                        const char *Key, size_t KeyLen,
406                        LLVMMetadataRef Val) {
407   unwrap(M)->addModuleFlag(map_to_llvmModFlagBehavior(Behavior),
408                            {Key, KeyLen}, unwrap(Val));
409 }
410 
411 /*--.. Printing modules ....................................................--*/
412 
413 void LLVMDumpModule(LLVMModuleRef M) {
414   unwrap(M)->print(errs(), nullptr,
415                    /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
416 }
417 
418 LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename,
419                                char **ErrorMessage) {
420   std::error_code EC;
421   raw_fd_ostream dest(Filename, EC, sys::fs::OF_TextWithCRLF);
422   if (EC) {
423     *ErrorMessage = strdup(EC.message().c_str());
424     return true;
425   }
426 
427   unwrap(M)->print(dest, nullptr);
428 
429   dest.close();
430 
431   if (dest.has_error()) {
432     std::string E = "Error printing to file: " + dest.error().message();
433     *ErrorMessage = strdup(E.c_str());
434     return true;
435   }
436 
437   return false;
438 }
439 
440 char *LLVMPrintModuleToString(LLVMModuleRef M) {
441   std::string buf;
442   raw_string_ostream os(buf);
443 
444   unwrap(M)->print(os, nullptr);
445   os.flush();
446 
447   return strdup(buf.c_str());
448 }
449 
450 /*--.. Operations on inline assembler ......................................--*/
451 void LLVMSetModuleInlineAsm2(LLVMModuleRef M, const char *Asm, size_t Len) {
452   unwrap(M)->setModuleInlineAsm(StringRef(Asm, Len));
453 }
454 
455 void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
456   unwrap(M)->setModuleInlineAsm(StringRef(Asm));
457 }
458 
459 void LLVMAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm, size_t Len) {
460   unwrap(M)->appendModuleInlineAsm(StringRef(Asm, Len));
461 }
462 
463 const char *LLVMGetModuleInlineAsm(LLVMModuleRef M, size_t *Len) {
464   auto &Str = unwrap(M)->getModuleInlineAsm();
465   *Len = Str.length();
466   return Str.c_str();
467 }
468 
469 LLVMValueRef LLVMGetInlineAsm(LLVMTypeRef Ty, char *AsmString,
470                               size_t AsmStringSize, char *Constraints,
471                               size_t ConstraintsSize, LLVMBool HasSideEffects,
472                               LLVMBool IsAlignStack,
473                               LLVMInlineAsmDialect Dialect, LLVMBool CanThrow) {
474   InlineAsm::AsmDialect AD;
475   switch (Dialect) {
476   case LLVMInlineAsmDialectATT:
477     AD = InlineAsm::AD_ATT;
478     break;
479   case LLVMInlineAsmDialectIntel:
480     AD = InlineAsm::AD_Intel;
481     break;
482   }
483   return wrap(InlineAsm::get(unwrap<FunctionType>(Ty),
484                              StringRef(AsmString, AsmStringSize),
485                              StringRef(Constraints, ConstraintsSize),
486                              HasSideEffects, IsAlignStack, AD, CanThrow));
487 }
488 
489 /*--.. Operations on module contexts ......................................--*/
490 LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M) {
491   return wrap(&unwrap(M)->getContext());
492 }
493 
494 
495 /*===-- Operations on types -----------------------------------------------===*/
496 
497 /*--.. Operations on all types (mostly) ....................................--*/
498 
499 LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty) {
500   switch (unwrap(Ty)->getTypeID()) {
501   case Type::VoidTyID:
502     return LLVMVoidTypeKind;
503   case Type::HalfTyID:
504     return LLVMHalfTypeKind;
505   case Type::BFloatTyID:
506     return LLVMBFloatTypeKind;
507   case Type::FloatTyID:
508     return LLVMFloatTypeKind;
509   case Type::DoubleTyID:
510     return LLVMDoubleTypeKind;
511   case Type::X86_FP80TyID:
512     return LLVMX86_FP80TypeKind;
513   case Type::FP128TyID:
514     return LLVMFP128TypeKind;
515   case Type::PPC_FP128TyID:
516     return LLVMPPC_FP128TypeKind;
517   case Type::LabelTyID:
518     return LLVMLabelTypeKind;
519   case Type::MetadataTyID:
520     return LLVMMetadataTypeKind;
521   case Type::IntegerTyID:
522     return LLVMIntegerTypeKind;
523   case Type::FunctionTyID:
524     return LLVMFunctionTypeKind;
525   case Type::StructTyID:
526     return LLVMStructTypeKind;
527   case Type::ArrayTyID:
528     return LLVMArrayTypeKind;
529   case Type::PointerTyID:
530     return LLVMPointerTypeKind;
531   case Type::FixedVectorTyID:
532     return LLVMVectorTypeKind;
533   case Type::X86_MMXTyID:
534     return LLVMX86_MMXTypeKind;
535   case Type::X86_AMXTyID:
536     return LLVMX86_AMXTypeKind;
537   case Type::TokenTyID:
538     return LLVMTokenTypeKind;
539   case Type::ScalableVectorTyID:
540     return LLVMScalableVectorTypeKind;
541   case Type::DXILPointerTyID:
542     llvm_unreachable("DXIL pointers are unsupported via the C API");
543   }
544   llvm_unreachable("Unhandled TypeID.");
545 }
546 
547 LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty)
548 {
549     return unwrap(Ty)->isSized();
550 }
551 
552 LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty) {
553   return wrap(&unwrap(Ty)->getContext());
554 }
555 
556 void LLVMDumpType(LLVMTypeRef Ty) {
557   return unwrap(Ty)->print(errs(), /*IsForDebug=*/true);
558 }
559 
560 char *LLVMPrintTypeToString(LLVMTypeRef Ty) {
561   std::string buf;
562   raw_string_ostream os(buf);
563 
564   if (unwrap(Ty))
565     unwrap(Ty)->print(os);
566   else
567     os << "Printing <null> Type";
568 
569   os.flush();
570 
571   return strdup(buf.c_str());
572 }
573 
574 /*--.. Operations on integer types .........................................--*/
575 
576 LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C)  {
577   return (LLVMTypeRef) Type::getInt1Ty(*unwrap(C));
578 }
579 LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C)  {
580   return (LLVMTypeRef) Type::getInt8Ty(*unwrap(C));
581 }
582 LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C) {
583   return (LLVMTypeRef) Type::getInt16Ty(*unwrap(C));
584 }
585 LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C) {
586   return (LLVMTypeRef) Type::getInt32Ty(*unwrap(C));
587 }
588 LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C) {
589   return (LLVMTypeRef) Type::getInt64Ty(*unwrap(C));
590 }
591 LLVMTypeRef LLVMInt128TypeInContext(LLVMContextRef C) {
592   return (LLVMTypeRef) Type::getInt128Ty(*unwrap(C));
593 }
594 LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits) {
595   return wrap(IntegerType::get(*unwrap(C), NumBits));
596 }
597 
598 LLVMTypeRef LLVMInt1Type(void)  {
599   return LLVMInt1TypeInContext(LLVMGetGlobalContext());
600 }
601 LLVMTypeRef LLVMInt8Type(void)  {
602   return LLVMInt8TypeInContext(LLVMGetGlobalContext());
603 }
604 LLVMTypeRef LLVMInt16Type(void) {
605   return LLVMInt16TypeInContext(LLVMGetGlobalContext());
606 }
607 LLVMTypeRef LLVMInt32Type(void) {
608   return LLVMInt32TypeInContext(LLVMGetGlobalContext());
609 }
610 LLVMTypeRef LLVMInt64Type(void) {
611   return LLVMInt64TypeInContext(LLVMGetGlobalContext());
612 }
613 LLVMTypeRef LLVMInt128Type(void) {
614   return LLVMInt128TypeInContext(LLVMGetGlobalContext());
615 }
616 LLVMTypeRef LLVMIntType(unsigned NumBits) {
617   return LLVMIntTypeInContext(LLVMGetGlobalContext(), NumBits);
618 }
619 
620 unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy) {
621   return unwrap<IntegerType>(IntegerTy)->getBitWidth();
622 }
623 
624 /*--.. Operations on real types ............................................--*/
625 
626 LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C) {
627   return (LLVMTypeRef) Type::getHalfTy(*unwrap(C));
628 }
629 LLVMTypeRef LLVMBFloatTypeInContext(LLVMContextRef C) {
630   return (LLVMTypeRef) Type::getBFloatTy(*unwrap(C));
631 }
632 LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C) {
633   return (LLVMTypeRef) Type::getFloatTy(*unwrap(C));
634 }
635 LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C) {
636   return (LLVMTypeRef) Type::getDoubleTy(*unwrap(C));
637 }
638 LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C) {
639   return (LLVMTypeRef) Type::getX86_FP80Ty(*unwrap(C));
640 }
641 LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C) {
642   return (LLVMTypeRef) Type::getFP128Ty(*unwrap(C));
643 }
644 LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C) {
645   return (LLVMTypeRef) Type::getPPC_FP128Ty(*unwrap(C));
646 }
647 LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C) {
648   return (LLVMTypeRef) Type::getX86_MMXTy(*unwrap(C));
649 }
650 LLVMTypeRef LLVMX86AMXTypeInContext(LLVMContextRef C) {
651   return (LLVMTypeRef) Type::getX86_AMXTy(*unwrap(C));
652 }
653 
654 LLVMTypeRef LLVMHalfType(void) {
655   return LLVMHalfTypeInContext(LLVMGetGlobalContext());
656 }
657 LLVMTypeRef LLVMBFloatType(void) {
658   return LLVMBFloatTypeInContext(LLVMGetGlobalContext());
659 }
660 LLVMTypeRef LLVMFloatType(void) {
661   return LLVMFloatTypeInContext(LLVMGetGlobalContext());
662 }
663 LLVMTypeRef LLVMDoubleType(void) {
664   return LLVMDoubleTypeInContext(LLVMGetGlobalContext());
665 }
666 LLVMTypeRef LLVMX86FP80Type(void) {
667   return LLVMX86FP80TypeInContext(LLVMGetGlobalContext());
668 }
669 LLVMTypeRef LLVMFP128Type(void) {
670   return LLVMFP128TypeInContext(LLVMGetGlobalContext());
671 }
672 LLVMTypeRef LLVMPPCFP128Type(void) {
673   return LLVMPPCFP128TypeInContext(LLVMGetGlobalContext());
674 }
675 LLVMTypeRef LLVMX86MMXType(void) {
676   return LLVMX86MMXTypeInContext(LLVMGetGlobalContext());
677 }
678 LLVMTypeRef LLVMX86AMXType(void) {
679   return LLVMX86AMXTypeInContext(LLVMGetGlobalContext());
680 }
681 
682 /*--.. Operations on function types ........................................--*/
683 
684 LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType,
685                              LLVMTypeRef *ParamTypes, unsigned ParamCount,
686                              LLVMBool IsVarArg) {
687   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
688   return wrap(FunctionType::get(unwrap(ReturnType), Tys, IsVarArg != 0));
689 }
690 
691 LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy) {
692   return unwrap<FunctionType>(FunctionTy)->isVarArg();
693 }
694 
695 LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy) {
696   return wrap(unwrap<FunctionType>(FunctionTy)->getReturnType());
697 }
698 
699 unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy) {
700   return unwrap<FunctionType>(FunctionTy)->getNumParams();
701 }
702 
703 void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest) {
704   FunctionType *Ty = unwrap<FunctionType>(FunctionTy);
705   for (Type *T : Ty->params())
706     *Dest++ = wrap(T);
707 }
708 
709 /*--.. Operations on struct types ..........................................--*/
710 
711 LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,
712                            unsigned ElementCount, LLVMBool Packed) {
713   ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);
714   return wrap(StructType::get(*unwrap(C), Tys, Packed != 0));
715 }
716 
717 LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes,
718                            unsigned ElementCount, LLVMBool Packed) {
719   return LLVMStructTypeInContext(LLVMGetGlobalContext(), ElementTypes,
720                                  ElementCount, Packed);
721 }
722 
723 LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name)
724 {
725   return wrap(StructType::create(*unwrap(C), Name));
726 }
727 
728 const char *LLVMGetStructName(LLVMTypeRef Ty)
729 {
730   StructType *Type = unwrap<StructType>(Ty);
731   if (!Type->hasName())
732     return nullptr;
733   return Type->getName().data();
734 }
735 
736 void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes,
737                        unsigned ElementCount, LLVMBool Packed) {
738   ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);
739   unwrap<StructType>(StructTy)->setBody(Tys, Packed != 0);
740 }
741 
742 unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy) {
743   return unwrap<StructType>(StructTy)->getNumElements();
744 }
745 
746 void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest) {
747   StructType *Ty = unwrap<StructType>(StructTy);
748   for (Type *T : Ty->elements())
749     *Dest++ = wrap(T);
750 }
751 
752 LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i) {
753   StructType *Ty = unwrap<StructType>(StructTy);
754   return wrap(Ty->getTypeAtIndex(i));
755 }
756 
757 LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy) {
758   return unwrap<StructType>(StructTy)->isPacked();
759 }
760 
761 LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy) {
762   return unwrap<StructType>(StructTy)->isOpaque();
763 }
764 
765 LLVMBool LLVMIsLiteralStruct(LLVMTypeRef StructTy) {
766   return unwrap<StructType>(StructTy)->isLiteral();
767 }
768 
769 LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) {
770   return wrap(StructType::getTypeByName(unwrap(M)->getContext(), Name));
771 }
772 
773 LLVMTypeRef LLVMGetTypeByName2(LLVMContextRef C, const char *Name) {
774   return wrap(StructType::getTypeByName(*unwrap(C), Name));
775 }
776 
777 /*--.. Operations on array, pointer, and vector types (sequence types) .....--*/
778 
779 void LLVMGetSubtypes(LLVMTypeRef Tp, LLVMTypeRef *Arr) {
780     int i = 0;
781     for (auto *T : unwrap(Tp)->subtypes()) {
782         Arr[i] = wrap(T);
783         i++;
784     }
785 }
786 
787 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount) {
788   return wrap(ArrayType::get(unwrap(ElementType), ElementCount));
789 }
790 
791 LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace) {
792   return wrap(PointerType::get(unwrap(ElementType), AddressSpace));
793 }
794 
795 LLVMBool LLVMPointerTypeIsOpaque(LLVMTypeRef Ty) {
796   return unwrap(Ty)->isOpaquePointerTy();
797 }
798 
799 LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount) {
800   return wrap(FixedVectorType::get(unwrap(ElementType), ElementCount));
801 }
802 
803 LLVMTypeRef LLVMScalableVectorType(LLVMTypeRef ElementType,
804                                    unsigned ElementCount) {
805   return wrap(ScalableVectorType::get(unwrap(ElementType), ElementCount));
806 }
807 
808 LLVMTypeRef LLVMGetElementType(LLVMTypeRef WrappedTy) {
809   auto *Ty = unwrap<Type>(WrappedTy);
810   if (auto *PTy = dyn_cast<PointerType>(Ty))
811     return wrap(PTy->getNonOpaquePointerElementType());
812   if (auto *ATy = dyn_cast<ArrayType>(Ty))
813     return wrap(ATy->getElementType());
814   return wrap(cast<VectorType>(Ty)->getElementType());
815 }
816 
817 unsigned LLVMGetNumContainedTypes(LLVMTypeRef Tp) {
818     return unwrap(Tp)->getNumContainedTypes();
819 }
820 
821 unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy) {
822   return unwrap<ArrayType>(ArrayTy)->getNumElements();
823 }
824 
825 unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy) {
826   return unwrap<PointerType>(PointerTy)->getAddressSpace();
827 }
828 
829 unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy) {
830   return unwrap<VectorType>(VectorTy)->getElementCount().getKnownMinValue();
831 }
832 
833 /*--.. Operations on other types ...........................................--*/
834 
835 LLVMTypeRef LLVMPointerTypeInContext(LLVMContextRef C, unsigned AddressSpace) {
836   return wrap(PointerType::get(*unwrap(C), AddressSpace));
837 }
838 
839 LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C)  {
840   return wrap(Type::getVoidTy(*unwrap(C)));
841 }
842 LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C) {
843   return wrap(Type::getLabelTy(*unwrap(C)));
844 }
845 LLVMTypeRef LLVMTokenTypeInContext(LLVMContextRef C) {
846   return wrap(Type::getTokenTy(*unwrap(C)));
847 }
848 LLVMTypeRef LLVMMetadataTypeInContext(LLVMContextRef C) {
849   return wrap(Type::getMetadataTy(*unwrap(C)));
850 }
851 
852 LLVMTypeRef LLVMVoidType(void)  {
853   return LLVMVoidTypeInContext(LLVMGetGlobalContext());
854 }
855 LLVMTypeRef LLVMLabelType(void) {
856   return LLVMLabelTypeInContext(LLVMGetGlobalContext());
857 }
858 
859 /*===-- Operations on values ----------------------------------------------===*/
860 
861 /*--.. Operations on all values ............................................--*/
862 
863 LLVMTypeRef LLVMTypeOf(LLVMValueRef Val) {
864   return wrap(unwrap(Val)->getType());
865 }
866 
867 LLVMValueKind LLVMGetValueKind(LLVMValueRef Val) {
868     switch(unwrap(Val)->getValueID()) {
869 #define LLVM_C_API 1
870 #define HANDLE_VALUE(Name) \
871   case Value::Name##Val: \
872     return LLVM##Name##ValueKind;
873 #include "llvm/IR/Value.def"
874   default:
875     return LLVMInstructionValueKind;
876   }
877 }
878 
879 const char *LLVMGetValueName2(LLVMValueRef Val, size_t *Length) {
880   auto *V = unwrap(Val);
881   *Length = V->getName().size();
882   return V->getName().data();
883 }
884 
885 void LLVMSetValueName2(LLVMValueRef Val, const char *Name, size_t NameLen) {
886   unwrap(Val)->setName(StringRef(Name, NameLen));
887 }
888 
889 const char *LLVMGetValueName(LLVMValueRef Val) {
890   return unwrap(Val)->getName().data();
891 }
892 
893 void LLVMSetValueName(LLVMValueRef Val, const char *Name) {
894   unwrap(Val)->setName(Name);
895 }
896 
897 void LLVMDumpValue(LLVMValueRef Val) {
898   unwrap(Val)->print(errs(), /*IsForDebug=*/true);
899 }
900 
901 char* LLVMPrintValueToString(LLVMValueRef Val) {
902   std::string buf;
903   raw_string_ostream os(buf);
904 
905   if (unwrap(Val))
906     unwrap(Val)->print(os);
907   else
908     os << "Printing <null> Value";
909 
910   os.flush();
911 
912   return strdup(buf.c_str());
913 }
914 
915 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {
916   unwrap(OldVal)->replaceAllUsesWith(unwrap(NewVal));
917 }
918 
919 int LLVMHasMetadata(LLVMValueRef Inst) {
920   return unwrap<Instruction>(Inst)->hasMetadata();
921 }
922 
923 LLVMValueRef LLVMGetMetadata(LLVMValueRef Inst, unsigned KindID) {
924   auto *I = unwrap<Instruction>(Inst);
925   assert(I && "Expected instruction");
926   if (auto *MD = I->getMetadata(KindID))
927     return wrap(MetadataAsValue::get(I->getContext(), MD));
928   return nullptr;
929 }
930 
931 // MetadataAsValue uses a canonical format which strips the actual MDNode for
932 // MDNode with just a single constant value, storing just a ConstantAsMetadata
933 // This undoes this canonicalization, reconstructing the MDNode.
934 static MDNode *extractMDNode(MetadataAsValue *MAV) {
935   Metadata *MD = MAV->getMetadata();
936   assert((isa<MDNode>(MD) || isa<ConstantAsMetadata>(MD)) &&
937       "Expected a metadata node or a canonicalized constant");
938 
939   if (MDNode *N = dyn_cast<MDNode>(MD))
940     return N;
941 
942   return MDNode::get(MAV->getContext(), MD);
943 }
944 
945 void LLVMSetMetadata(LLVMValueRef Inst, unsigned KindID, LLVMValueRef Val) {
946   MDNode *N = Val ? extractMDNode(unwrap<MetadataAsValue>(Val)) : nullptr;
947 
948   unwrap<Instruction>(Inst)->setMetadata(KindID, N);
949 }
950 
951 struct LLVMOpaqueValueMetadataEntry {
952   unsigned Kind;
953   LLVMMetadataRef Metadata;
954 };
955 
956 using MetadataEntries = SmallVectorImpl<std::pair<unsigned, MDNode *>>;
957 static LLVMValueMetadataEntry *
958 llvm_getMetadata(size_t *NumEntries,
959                  llvm::function_ref<void(MetadataEntries &)> AccessMD) {
960   SmallVector<std::pair<unsigned, MDNode *>, 8> MVEs;
961   AccessMD(MVEs);
962 
963   LLVMOpaqueValueMetadataEntry *Result =
964   static_cast<LLVMOpaqueValueMetadataEntry *>(
965                                               safe_malloc(MVEs.size() * sizeof(LLVMOpaqueValueMetadataEntry)));
966   for (unsigned i = 0; i < MVEs.size(); ++i) {
967     const auto &ModuleFlag = MVEs[i];
968     Result[i].Kind = ModuleFlag.first;
969     Result[i].Metadata = wrap(ModuleFlag.second);
970   }
971   *NumEntries = MVEs.size();
972   return Result;
973 }
974 
975 LLVMValueMetadataEntry *
976 LLVMInstructionGetAllMetadataOtherThanDebugLoc(LLVMValueRef Value,
977                                                size_t *NumEntries) {
978   return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {
979     Entries.clear();
980     unwrap<Instruction>(Value)->getAllMetadata(Entries);
981   });
982 }
983 
984 /*--.. Conversion functions ................................................--*/
985 
986 #define LLVM_DEFINE_VALUE_CAST(name)                                       \
987   LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                           \
988     return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \
989   }
990 
991 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)
992 
993 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {
994   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
995     if (isa<MDNode>(MD->getMetadata()) ||
996         isa<ValueAsMetadata>(MD->getMetadata()))
997       return Val;
998   return nullptr;
999 }
1000 
1001 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) {
1002   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
1003     if (isa<MDString>(MD->getMetadata()))
1004       return Val;
1005   return nullptr;
1006 }
1007 
1008 /*--.. Operations on Uses ..................................................--*/
1009 LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val) {
1010   Value *V = unwrap(Val);
1011   Value::use_iterator I = V->use_begin();
1012   if (I == V->use_end())
1013     return nullptr;
1014   return wrap(&*I);
1015 }
1016 
1017 LLVMUseRef LLVMGetNextUse(LLVMUseRef U) {
1018   Use *Next = unwrap(U)->getNext();
1019   if (Next)
1020     return wrap(Next);
1021   return nullptr;
1022 }
1023 
1024 LLVMValueRef LLVMGetUser(LLVMUseRef U) {
1025   return wrap(unwrap(U)->getUser());
1026 }
1027 
1028 LLVMValueRef LLVMGetUsedValue(LLVMUseRef U) {
1029   return wrap(unwrap(U)->get());
1030 }
1031 
1032 /*--.. Operations on Users .................................................--*/
1033 
1034 static LLVMValueRef getMDNodeOperandImpl(LLVMContext &Context, const MDNode *N,
1035                                          unsigned Index) {
1036   Metadata *Op = N->getOperand(Index);
1037   if (!Op)
1038     return nullptr;
1039   if (auto *C = dyn_cast<ConstantAsMetadata>(Op))
1040     return wrap(C->getValue());
1041   return wrap(MetadataAsValue::get(Context, Op));
1042 }
1043 
1044 LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index) {
1045   Value *V = unwrap(Val);
1046   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1047     if (auto *L = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
1048       assert(Index == 0 && "Function-local metadata can only have one operand");
1049       return wrap(L->getValue());
1050     }
1051     return getMDNodeOperandImpl(V->getContext(),
1052                                 cast<MDNode>(MD->getMetadata()), Index);
1053   }
1054 
1055   return wrap(cast<User>(V)->getOperand(Index));
1056 }
1057 
1058 LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index) {
1059   Value *V = unwrap(Val);
1060   return wrap(&cast<User>(V)->getOperandUse(Index));
1061 }
1062 
1063 void LLVMSetOperand(LLVMValueRef Val, unsigned Index, LLVMValueRef Op) {
1064   unwrap<User>(Val)->setOperand(Index, unwrap(Op));
1065 }
1066 
1067 int LLVMGetNumOperands(LLVMValueRef Val) {
1068   Value *V = unwrap(Val);
1069   if (isa<MetadataAsValue>(V))
1070     return LLVMGetMDNodeNumOperands(Val);
1071 
1072   return cast<User>(V)->getNumOperands();
1073 }
1074 
1075 /*--.. Operations on constants of any type .................................--*/
1076 
1077 LLVMValueRef LLVMConstNull(LLVMTypeRef Ty) {
1078   return wrap(Constant::getNullValue(unwrap(Ty)));
1079 }
1080 
1081 LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty) {
1082   return wrap(Constant::getAllOnesValue(unwrap(Ty)));
1083 }
1084 
1085 LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty) {
1086   return wrap(UndefValue::get(unwrap(Ty)));
1087 }
1088 
1089 LLVMValueRef LLVMGetPoison(LLVMTypeRef Ty) {
1090   return wrap(PoisonValue::get(unwrap(Ty)));
1091 }
1092 
1093 LLVMBool LLVMIsConstant(LLVMValueRef Ty) {
1094   return isa<Constant>(unwrap(Ty));
1095 }
1096 
1097 LLVMBool LLVMIsNull(LLVMValueRef Val) {
1098   if (Constant *C = dyn_cast<Constant>(unwrap(Val)))
1099     return C->isNullValue();
1100   return false;
1101 }
1102 
1103 LLVMBool LLVMIsUndef(LLVMValueRef Val) {
1104   return isa<UndefValue>(unwrap(Val));
1105 }
1106 
1107 LLVMBool LLVMIsPoison(LLVMValueRef Val) {
1108   return isa<PoisonValue>(unwrap(Val));
1109 }
1110 
1111 LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty) {
1112   return wrap(ConstantPointerNull::get(unwrap<PointerType>(Ty)));
1113 }
1114 
1115 /*--.. Operations on metadata nodes ........................................--*/
1116 
1117 LLVMMetadataRef LLVMMDStringInContext2(LLVMContextRef C, const char *Str,
1118                                        size_t SLen) {
1119   return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen)));
1120 }
1121 
1122 LLVMMetadataRef LLVMMDNodeInContext2(LLVMContextRef C, LLVMMetadataRef *MDs,
1123                                      size_t Count) {
1124   return wrap(MDNode::get(*unwrap(C), ArrayRef<Metadata*>(unwrap(MDs), Count)));
1125 }
1126 
1127 LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
1128                                    unsigned SLen) {
1129   LLVMContext &Context = *unwrap(C);
1130   return wrap(MetadataAsValue::get(
1131       Context, MDString::get(Context, StringRef(Str, SLen))));
1132 }
1133 
1134 LLVMValueRef LLVMMDString(const char *Str, unsigned SLen) {
1135   return LLVMMDStringInContext(LLVMGetGlobalContext(), Str, SLen);
1136 }
1137 
1138 LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
1139                                  unsigned Count) {
1140   LLVMContext &Context = *unwrap(C);
1141   SmallVector<Metadata *, 8> MDs;
1142   for (auto *OV : makeArrayRef(Vals, Count)) {
1143     Value *V = unwrap(OV);
1144     Metadata *MD;
1145     if (!V)
1146       MD = nullptr;
1147     else if (auto *C = dyn_cast<Constant>(V))
1148       MD = ConstantAsMetadata::get(C);
1149     else if (auto *MDV = dyn_cast<MetadataAsValue>(V)) {
1150       MD = MDV->getMetadata();
1151       assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata "
1152                                           "outside of direct argument to call");
1153     } else {
1154       // This is function-local metadata.  Pretend to make an MDNode.
1155       assert(Count == 1 &&
1156              "Expected only one operand to function-local metadata");
1157       return wrap(MetadataAsValue::get(Context, LocalAsMetadata::get(V)));
1158     }
1159 
1160     MDs.push_back(MD);
1161   }
1162   return wrap(MetadataAsValue::get(Context, MDNode::get(Context, MDs)));
1163 }
1164 
1165 LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count) {
1166   return LLVMMDNodeInContext(LLVMGetGlobalContext(), Vals, Count);
1167 }
1168 
1169 LLVMValueRef LLVMMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
1170   return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
1171 }
1172 
1173 LLVMMetadataRef LLVMValueAsMetadata(LLVMValueRef Val) {
1174   auto *V = unwrap(Val);
1175   if (auto *C = dyn_cast<Constant>(V))
1176     return wrap(ConstantAsMetadata::get(C));
1177   if (auto *MAV = dyn_cast<MetadataAsValue>(V))
1178     return wrap(MAV->getMetadata());
1179   return wrap(ValueAsMetadata::get(V));
1180 }
1181 
1182 const char *LLVMGetMDString(LLVMValueRef V, unsigned *Length) {
1183   if (const auto *MD = dyn_cast<MetadataAsValue>(unwrap(V)))
1184     if (const MDString *S = dyn_cast<MDString>(MD->getMetadata())) {
1185       *Length = S->getString().size();
1186       return S->getString().data();
1187     }
1188   *Length = 0;
1189   return nullptr;
1190 }
1191 
1192 unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V) {
1193   auto *MD = cast<MetadataAsValue>(unwrap(V));
1194   if (isa<ValueAsMetadata>(MD->getMetadata()))
1195     return 1;
1196   return cast<MDNode>(MD->getMetadata())->getNumOperands();
1197 }
1198 
1199 LLVMNamedMDNodeRef LLVMGetFirstNamedMetadata(LLVMModuleRef M) {
1200   Module *Mod = unwrap(M);
1201   Module::named_metadata_iterator I = Mod->named_metadata_begin();
1202   if (I == Mod->named_metadata_end())
1203     return nullptr;
1204   return wrap(&*I);
1205 }
1206 
1207 LLVMNamedMDNodeRef LLVMGetLastNamedMetadata(LLVMModuleRef M) {
1208   Module *Mod = unwrap(M);
1209   Module::named_metadata_iterator I = Mod->named_metadata_end();
1210   if (I == Mod->named_metadata_begin())
1211     return nullptr;
1212   return wrap(&*--I);
1213 }
1214 
1215 LLVMNamedMDNodeRef LLVMGetNextNamedMetadata(LLVMNamedMDNodeRef NMD) {
1216   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1217   Module::named_metadata_iterator I(NamedNode);
1218   if (++I == NamedNode->getParent()->named_metadata_end())
1219     return nullptr;
1220   return wrap(&*I);
1221 }
1222 
1223 LLVMNamedMDNodeRef LLVMGetPreviousNamedMetadata(LLVMNamedMDNodeRef NMD) {
1224   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1225   Module::named_metadata_iterator I(NamedNode);
1226   if (I == NamedNode->getParent()->named_metadata_begin())
1227     return nullptr;
1228   return wrap(&*--I);
1229 }
1230 
1231 LLVMNamedMDNodeRef LLVMGetNamedMetadata(LLVMModuleRef M,
1232                                         const char *Name, size_t NameLen) {
1233   return wrap(unwrap(M)->getNamedMetadata(StringRef(Name, NameLen)));
1234 }
1235 
1236 LLVMNamedMDNodeRef LLVMGetOrInsertNamedMetadata(LLVMModuleRef M,
1237                                                 const char *Name, size_t NameLen) {
1238   return wrap(unwrap(M)->getOrInsertNamedMetadata({Name, NameLen}));
1239 }
1240 
1241 const char *LLVMGetNamedMetadataName(LLVMNamedMDNodeRef NMD, size_t *NameLen) {
1242   NamedMDNode *NamedNode = unwrap<NamedMDNode>(NMD);
1243   *NameLen = NamedNode->getName().size();
1244   return NamedNode->getName().data();
1245 }
1246 
1247 void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest) {
1248   auto *MD = cast<MetadataAsValue>(unwrap(V));
1249   if (auto *MDV = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
1250     *Dest = wrap(MDV->getValue());
1251     return;
1252   }
1253   const auto *N = cast<MDNode>(MD->getMetadata());
1254   const unsigned numOperands = N->getNumOperands();
1255   LLVMContext &Context = unwrap(V)->getContext();
1256   for (unsigned i = 0; i < numOperands; i++)
1257     Dest[i] = getMDNodeOperandImpl(Context, N, i);
1258 }
1259 
1260 unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char *Name) {
1261   if (NamedMDNode *N = unwrap(M)->getNamedMetadata(Name)) {
1262     return N->getNumOperands();
1263   }
1264   return 0;
1265 }
1266 
1267 void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char *Name,
1268                                   LLVMValueRef *Dest) {
1269   NamedMDNode *N = unwrap(M)->getNamedMetadata(Name);
1270   if (!N)
1271     return;
1272   LLVMContext &Context = unwrap(M)->getContext();
1273   for (unsigned i=0;i<N->getNumOperands();i++)
1274     Dest[i] = wrap(MetadataAsValue::get(Context, N->getOperand(i)));
1275 }
1276 
1277 void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name,
1278                                  LLVMValueRef Val) {
1279   NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(Name);
1280   if (!N)
1281     return;
1282   if (!Val)
1283     return;
1284   N->addOperand(extractMDNode(unwrap<MetadataAsValue>(Val)));
1285 }
1286 
1287 const char *LLVMGetDebugLocDirectory(LLVMValueRef Val, unsigned *Length) {
1288   if (!Length) return nullptr;
1289   StringRef S;
1290   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1291     if (const auto &DL = I->getDebugLoc()) {
1292       S = DL->getDirectory();
1293     }
1294   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1295     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1296     GV->getDebugInfo(GVEs);
1297     if (GVEs.size())
1298       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1299         S = DGV->getDirectory();
1300   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1301     if (const DISubprogram *DSP = F->getSubprogram())
1302       S = DSP->getDirectory();
1303   } else {
1304     assert(0 && "Expected Instruction, GlobalVariable or Function");
1305     return nullptr;
1306   }
1307   *Length = S.size();
1308   return S.data();
1309 }
1310 
1311 const char *LLVMGetDebugLocFilename(LLVMValueRef Val, unsigned *Length) {
1312   if (!Length) return nullptr;
1313   StringRef S;
1314   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1315     if (const auto &DL = I->getDebugLoc()) {
1316       S = DL->getFilename();
1317     }
1318   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1319     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1320     GV->getDebugInfo(GVEs);
1321     if (GVEs.size())
1322       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1323         S = DGV->getFilename();
1324   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1325     if (const DISubprogram *DSP = F->getSubprogram())
1326       S = DSP->getFilename();
1327   } else {
1328     assert(0 && "Expected Instruction, GlobalVariable or Function");
1329     return nullptr;
1330   }
1331   *Length = S.size();
1332   return S.data();
1333 }
1334 
1335 unsigned LLVMGetDebugLocLine(LLVMValueRef Val) {
1336   unsigned L = 0;
1337   if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {
1338     if (const auto &DL = I->getDebugLoc()) {
1339       L = DL->getLine();
1340     }
1341   } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {
1342     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
1343     GV->getDebugInfo(GVEs);
1344     if (GVEs.size())
1345       if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())
1346         L = DGV->getLine();
1347   } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {
1348     if (const DISubprogram *DSP = F->getSubprogram())
1349       L = DSP->getLine();
1350   } else {
1351     assert(0 && "Expected Instruction, GlobalVariable or Function");
1352     return -1;
1353   }
1354   return L;
1355 }
1356 
1357 unsigned LLVMGetDebugLocColumn(LLVMValueRef Val) {
1358   unsigned C = 0;
1359   if (const auto *I = dyn_cast<Instruction>(unwrap(Val)))
1360     if (const auto &DL = I->getDebugLoc())
1361       C = DL->getColumn();
1362   return C;
1363 }
1364 
1365 /*--.. Operations on scalar constants ......................................--*/
1366 
1367 LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
1368                           LLVMBool SignExtend) {
1369   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), N, SignExtend != 0));
1370 }
1371 
1372 LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,
1373                                               unsigned NumWords,
1374                                               const uint64_t Words[]) {
1375     IntegerType *Ty = unwrap<IntegerType>(IntTy);
1376     return wrap(ConstantInt::get(Ty->getContext(),
1377                                  APInt(Ty->getBitWidth(),
1378                                        makeArrayRef(Words, NumWords))));
1379 }
1380 
1381 LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char Str[],
1382                                   uint8_t Radix) {
1383   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str),
1384                                Radix));
1385 }
1386 
1387 LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char Str[],
1388                                          unsigned SLen, uint8_t Radix) {
1389   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str, SLen),
1390                                Radix));
1391 }
1392 
1393 LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N) {
1394   return wrap(ConstantFP::get(unwrap(RealTy), N));
1395 }
1396 
1397 LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text) {
1398   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Text)));
1399 }
1400 
1401 LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char Str[],
1402                                           unsigned SLen) {
1403   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Str, SLen)));
1404 }
1405 
1406 unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal) {
1407   return unwrap<ConstantInt>(ConstantVal)->getZExtValue();
1408 }
1409 
1410 long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal) {
1411   return unwrap<ConstantInt>(ConstantVal)->getSExtValue();
1412 }
1413 
1414 double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *LosesInfo) {
1415   ConstantFP *cFP = unwrap<ConstantFP>(ConstantVal) ;
1416   Type *Ty = cFP->getType();
1417 
1418   if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
1419       Ty->isDoubleTy()) {
1420     *LosesInfo = false;
1421     return cFP->getValueAPF().convertToDouble();
1422   }
1423 
1424   bool APFLosesInfo;
1425   APFloat APF = cFP->getValueAPF();
1426   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &APFLosesInfo);
1427   *LosesInfo = APFLosesInfo;
1428   return APF.convertToDouble();
1429 }
1430 
1431 /*--.. Operations on composite constants ...................................--*/
1432 
1433 LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,
1434                                       unsigned Length,
1435                                       LLVMBool DontNullTerminate) {
1436   /* Inverted the sense of AddNull because ', 0)' is a
1437      better mnemonic for null termination than ', 1)'. */
1438   return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),
1439                                            DontNullTerminate == 0));
1440 }
1441 
1442 LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
1443                              LLVMBool DontNullTerminate) {
1444   return LLVMConstStringInContext(LLVMGetGlobalContext(), Str, Length,
1445                                   DontNullTerminate);
1446 }
1447 
1448 LLVMValueRef LLVMGetAggregateElement(LLVMValueRef C, unsigned Idx) {
1449   return wrap(unwrap<Constant>(C)->getAggregateElement(Idx));
1450 }
1451 
1452 LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx) {
1453   return wrap(unwrap<ConstantDataSequential>(C)->getElementAsConstant(idx));
1454 }
1455 
1456 LLVMBool LLVMIsConstantString(LLVMValueRef C) {
1457   return unwrap<ConstantDataSequential>(C)->isString();
1458 }
1459 
1460 const char *LLVMGetAsString(LLVMValueRef C, size_t *Length) {
1461   StringRef Str = unwrap<ConstantDataSequential>(C)->getAsString();
1462   *Length = Str.size();
1463   return Str.data();
1464 }
1465 
1466 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
1467                             LLVMValueRef *ConstantVals, unsigned Length) {
1468   ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length);
1469   return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));
1470 }
1471 
1472 LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
1473                                       LLVMValueRef *ConstantVals,
1474                                       unsigned Count, LLVMBool Packed) {
1475   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1476   return wrap(ConstantStruct::getAnon(*unwrap(C), makeArrayRef(Elements, Count),
1477                                       Packed != 0));
1478 }
1479 
1480 LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
1481                              LLVMBool Packed) {
1482   return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count,
1483                                   Packed);
1484 }
1485 
1486 LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
1487                                   LLVMValueRef *ConstantVals,
1488                                   unsigned Count) {
1489   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1490   StructType *Ty = cast<StructType>(unwrap(StructTy));
1491 
1492   return wrap(ConstantStruct::get(Ty, makeArrayRef(Elements, Count)));
1493 }
1494 
1495 LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) {
1496   return wrap(ConstantVector::get(makeArrayRef(
1497                             unwrap<Constant>(ScalarConstantVals, Size), Size)));
1498 }
1499 
1500 /*-- Opcode mapping */
1501 
1502 static LLVMOpcode map_to_llvmopcode(int opcode)
1503 {
1504     switch (opcode) {
1505       default: llvm_unreachable("Unhandled Opcode.");
1506 #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;
1507 #include "llvm/IR/Instruction.def"
1508 #undef HANDLE_INST
1509     }
1510 }
1511 
1512 static int map_from_llvmopcode(LLVMOpcode code)
1513 {
1514     switch (code) {
1515 #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;
1516 #include "llvm/IR/Instruction.def"
1517 #undef HANDLE_INST
1518     }
1519     llvm_unreachable("Unhandled Opcode.");
1520 }
1521 
1522 /*--.. Constant expressions ................................................--*/
1523 
1524 LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) {
1525   return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode());
1526 }
1527 
1528 LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) {
1529   return wrap(ConstantExpr::getAlignOf(unwrap(Ty)));
1530 }
1531 
1532 LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) {
1533   return wrap(ConstantExpr::getSizeOf(unwrap(Ty)));
1534 }
1535 
1536 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) {
1537   return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));
1538 }
1539 
1540 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) {
1541   return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal)));
1542 }
1543 
1544 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) {
1545   return wrap(ConstantExpr::getNUWNeg(unwrap<Constant>(ConstantVal)));
1546 }
1547 
1548 
1549 LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal) {
1550   return wrap(ConstantExpr::getFNeg(unwrap<Constant>(ConstantVal)));
1551 }
1552 
1553 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) {
1554   return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal)));
1555 }
1556 
1557 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1558   return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant),
1559                                    unwrap<Constant>(RHSConstant)));
1560 }
1561 
1562 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant,
1563                              LLVMValueRef RHSConstant) {
1564   return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant),
1565                                       unwrap<Constant>(RHSConstant)));
1566 }
1567 
1568 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant,
1569                              LLVMValueRef RHSConstant) {
1570   return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant),
1571                                       unwrap<Constant>(RHSConstant)));
1572 }
1573 
1574 LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1575   return wrap(ConstantExpr::getFAdd(unwrap<Constant>(LHSConstant),
1576                                     unwrap<Constant>(RHSConstant)));
1577 }
1578 
1579 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1580   return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant),
1581                                    unwrap<Constant>(RHSConstant)));
1582 }
1583 
1584 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant,
1585                              LLVMValueRef RHSConstant) {
1586   return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant),
1587                                       unwrap<Constant>(RHSConstant)));
1588 }
1589 
1590 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant,
1591                              LLVMValueRef RHSConstant) {
1592   return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant),
1593                                       unwrap<Constant>(RHSConstant)));
1594 }
1595 
1596 LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1597   return wrap(ConstantExpr::getFSub(unwrap<Constant>(LHSConstant),
1598                                     unwrap<Constant>(RHSConstant)));
1599 }
1600 
1601 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1602   return wrap(ConstantExpr::getMul(unwrap<Constant>(LHSConstant),
1603                                    unwrap<Constant>(RHSConstant)));
1604 }
1605 
1606 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant,
1607                              LLVMValueRef RHSConstant) {
1608   return wrap(ConstantExpr::getNSWMul(unwrap<Constant>(LHSConstant),
1609                                       unwrap<Constant>(RHSConstant)));
1610 }
1611 
1612 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant,
1613                              LLVMValueRef RHSConstant) {
1614   return wrap(ConstantExpr::getNUWMul(unwrap<Constant>(LHSConstant),
1615                                       unwrap<Constant>(RHSConstant)));
1616 }
1617 
1618 LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1619   return wrap(ConstantExpr::getFMul(unwrap<Constant>(LHSConstant),
1620                                     unwrap<Constant>(RHSConstant)));
1621 }
1622 
1623 LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1624   return wrap(ConstantExpr::getUDiv(unwrap<Constant>(LHSConstant),
1625                                     unwrap<Constant>(RHSConstant)));
1626 }
1627 
1628 LLVMValueRef LLVMConstExactUDiv(LLVMValueRef LHSConstant,
1629                                 LLVMValueRef RHSConstant) {
1630   return wrap(ConstantExpr::getExactUDiv(unwrap<Constant>(LHSConstant),
1631                                          unwrap<Constant>(RHSConstant)));
1632 }
1633 
1634 LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1635   return wrap(ConstantExpr::getSDiv(unwrap<Constant>(LHSConstant),
1636                                     unwrap<Constant>(RHSConstant)));
1637 }
1638 
1639 LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant,
1640                                 LLVMValueRef RHSConstant) {
1641   return wrap(ConstantExpr::getExactSDiv(unwrap<Constant>(LHSConstant),
1642                                          unwrap<Constant>(RHSConstant)));
1643 }
1644 
1645 LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1646   return wrap(ConstantExpr::getFDiv(unwrap<Constant>(LHSConstant),
1647                                     unwrap<Constant>(RHSConstant)));
1648 }
1649 
1650 LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1651   return wrap(ConstantExpr::getURem(unwrap<Constant>(LHSConstant),
1652                                     unwrap<Constant>(RHSConstant)));
1653 }
1654 
1655 LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1656   return wrap(ConstantExpr::getSRem(unwrap<Constant>(LHSConstant),
1657                                     unwrap<Constant>(RHSConstant)));
1658 }
1659 
1660 LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1661   return wrap(ConstantExpr::getFRem(unwrap<Constant>(LHSConstant),
1662                                     unwrap<Constant>(RHSConstant)));
1663 }
1664 
1665 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1666   return wrap(ConstantExpr::getAnd(unwrap<Constant>(LHSConstant),
1667                                    unwrap<Constant>(RHSConstant)));
1668 }
1669 
1670 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1671   return wrap(ConstantExpr::getOr(unwrap<Constant>(LHSConstant),
1672                                   unwrap<Constant>(RHSConstant)));
1673 }
1674 
1675 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1676   return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant),
1677                                    unwrap<Constant>(RHSConstant)));
1678 }
1679 
1680 LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate,
1681                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1682   return wrap(ConstantExpr::getICmp(Predicate,
1683                                     unwrap<Constant>(LHSConstant),
1684                                     unwrap<Constant>(RHSConstant)));
1685 }
1686 
1687 LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
1688                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1689   return wrap(ConstantExpr::getFCmp(Predicate,
1690                                     unwrap<Constant>(LHSConstant),
1691                                     unwrap<Constant>(RHSConstant)));
1692 }
1693 
1694 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1695   return wrap(ConstantExpr::getShl(unwrap<Constant>(LHSConstant),
1696                                    unwrap<Constant>(RHSConstant)));
1697 }
1698 
1699 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1700   return wrap(ConstantExpr::getLShr(unwrap<Constant>(LHSConstant),
1701                                     unwrap<Constant>(RHSConstant)));
1702 }
1703 
1704 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1705   return wrap(ConstantExpr::getAShr(unwrap<Constant>(LHSConstant),
1706                                     unwrap<Constant>(RHSConstant)));
1707 }
1708 
1709 LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
1710                           LLVMValueRef *ConstantIndices, 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::getGetElementPtr(Ty, Val, IdxList));
1716 }
1717 
1718 LLVMValueRef LLVMConstGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
1719                            LLVMValueRef *ConstantIndices, unsigned NumIndices) {
1720   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1721                                NumIndices);
1722   Constant *Val = unwrap<Constant>(ConstantVal);
1723   return wrap(ConstantExpr::getGetElementPtr(unwrap(Ty), Val, IdxList));
1724 }
1725 
1726 LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
1727                                   LLVMValueRef *ConstantIndices,
1728                                   unsigned NumIndices) {
1729   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1730                                NumIndices);
1731   Constant *Val = unwrap<Constant>(ConstantVal);
1732   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
1733   return wrap(ConstantExpr::getInBoundsGetElementPtr(Ty, Val, IdxList));
1734 }
1735 
1736 LLVMValueRef LLVMConstInBoundsGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
1737                                    LLVMValueRef *ConstantIndices,
1738                                    unsigned NumIndices) {
1739   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1740                                NumIndices);
1741   Constant *Val = unwrap<Constant>(ConstantVal);
1742   return wrap(ConstantExpr::getInBoundsGetElementPtr(unwrap(Ty), Val, IdxList));
1743 }
1744 
1745 LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1746   return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal),
1747                                      unwrap(ToType)));
1748 }
1749 
1750 LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1751   return wrap(ConstantExpr::getSExt(unwrap<Constant>(ConstantVal),
1752                                     unwrap(ToType)));
1753 }
1754 
1755 LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1756   return wrap(ConstantExpr::getZExt(unwrap<Constant>(ConstantVal),
1757                                     unwrap(ToType)));
1758 }
1759 
1760 LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1761   return wrap(ConstantExpr::getFPTrunc(unwrap<Constant>(ConstantVal),
1762                                        unwrap(ToType)));
1763 }
1764 
1765 LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1766   return wrap(ConstantExpr::getFPExtend(unwrap<Constant>(ConstantVal),
1767                                         unwrap(ToType)));
1768 }
1769 
1770 LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1771   return wrap(ConstantExpr::getUIToFP(unwrap<Constant>(ConstantVal),
1772                                       unwrap(ToType)));
1773 }
1774 
1775 LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1776   return wrap(ConstantExpr::getSIToFP(unwrap<Constant>(ConstantVal),
1777                                       unwrap(ToType)));
1778 }
1779 
1780 LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1781   return wrap(ConstantExpr::getFPToUI(unwrap<Constant>(ConstantVal),
1782                                       unwrap(ToType)));
1783 }
1784 
1785 LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1786   return wrap(ConstantExpr::getFPToSI(unwrap<Constant>(ConstantVal),
1787                                       unwrap(ToType)));
1788 }
1789 
1790 LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1791   return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal),
1792                                         unwrap(ToType)));
1793 }
1794 
1795 LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1796   return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal),
1797                                         unwrap(ToType)));
1798 }
1799 
1800 LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1801   return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal),
1802                                        unwrap(ToType)));
1803 }
1804 
1805 LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal,
1806                                     LLVMTypeRef ToType) {
1807   return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal),
1808                                              unwrap(ToType)));
1809 }
1810 
1811 LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal,
1812                                     LLVMTypeRef ToType) {
1813   return wrap(ConstantExpr::getZExtOrBitCast(unwrap<Constant>(ConstantVal),
1814                                              unwrap(ToType)));
1815 }
1816 
1817 LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal,
1818                                     LLVMTypeRef ToType) {
1819   return wrap(ConstantExpr::getSExtOrBitCast(unwrap<Constant>(ConstantVal),
1820                                              unwrap(ToType)));
1821 }
1822 
1823 LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,
1824                                      LLVMTypeRef ToType) {
1825   return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal),
1826                                               unwrap(ToType)));
1827 }
1828 
1829 LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
1830                                   LLVMTypeRef ToType) {
1831   return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal),
1832                                            unwrap(ToType)));
1833 }
1834 
1835 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
1836                               LLVMBool isSigned) {
1837   return wrap(ConstantExpr::getIntegerCast(unwrap<Constant>(ConstantVal),
1838                                            unwrap(ToType), isSigned));
1839 }
1840 
1841 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1842   return wrap(ConstantExpr::getFPCast(unwrap<Constant>(ConstantVal),
1843                                       unwrap(ToType)));
1844 }
1845 
1846 LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
1847                              LLVMValueRef ConstantIfTrue,
1848                              LLVMValueRef ConstantIfFalse) {
1849   return wrap(ConstantExpr::getSelect(unwrap<Constant>(ConstantCondition),
1850                                       unwrap<Constant>(ConstantIfTrue),
1851                                       unwrap<Constant>(ConstantIfFalse)));
1852 }
1853 
1854 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
1855                                      LLVMValueRef IndexConstant) {
1856   return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant),
1857                                               unwrap<Constant>(IndexConstant)));
1858 }
1859 
1860 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
1861                                     LLVMValueRef ElementValueConstant,
1862                                     LLVMValueRef IndexConstant) {
1863   return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant),
1864                                          unwrap<Constant>(ElementValueConstant),
1865                                              unwrap<Constant>(IndexConstant)));
1866 }
1867 
1868 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
1869                                     LLVMValueRef VectorBConstant,
1870                                     LLVMValueRef MaskConstant) {
1871   SmallVector<int, 16> IntMask;
1872   ShuffleVectorInst::getShuffleMask(unwrap<Constant>(MaskConstant), IntMask);
1873   return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant),
1874                                              unwrap<Constant>(VectorBConstant),
1875                                              IntMask));
1876 }
1877 
1878 LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString,
1879                                 const char *Constraints,
1880                                 LLVMBool HasSideEffects,
1881                                 LLVMBool IsAlignStack) {
1882   return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString,
1883                              Constraints, HasSideEffects, IsAlignStack));
1884 }
1885 
1886 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) {
1887   return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB)));
1888 }
1889 
1890 /*--.. Operations on global variables, functions, and aliases (globals) ....--*/
1891 
1892 LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) {
1893   return wrap(unwrap<GlobalValue>(Global)->getParent());
1894 }
1895 
1896 LLVMBool LLVMIsDeclaration(LLVMValueRef Global) {
1897   return unwrap<GlobalValue>(Global)->isDeclaration();
1898 }
1899 
1900 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {
1901   switch (unwrap<GlobalValue>(Global)->getLinkage()) {
1902   case GlobalValue::ExternalLinkage:
1903     return LLVMExternalLinkage;
1904   case GlobalValue::AvailableExternallyLinkage:
1905     return LLVMAvailableExternallyLinkage;
1906   case GlobalValue::LinkOnceAnyLinkage:
1907     return LLVMLinkOnceAnyLinkage;
1908   case GlobalValue::LinkOnceODRLinkage:
1909     return LLVMLinkOnceODRLinkage;
1910   case GlobalValue::WeakAnyLinkage:
1911     return LLVMWeakAnyLinkage;
1912   case GlobalValue::WeakODRLinkage:
1913     return LLVMWeakODRLinkage;
1914   case GlobalValue::AppendingLinkage:
1915     return LLVMAppendingLinkage;
1916   case GlobalValue::InternalLinkage:
1917     return LLVMInternalLinkage;
1918   case GlobalValue::PrivateLinkage:
1919     return LLVMPrivateLinkage;
1920   case GlobalValue::ExternalWeakLinkage:
1921     return LLVMExternalWeakLinkage;
1922   case GlobalValue::CommonLinkage:
1923     return LLVMCommonLinkage;
1924   }
1925 
1926   llvm_unreachable("Invalid GlobalValue linkage!");
1927 }
1928 
1929 void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {
1930   GlobalValue *GV = unwrap<GlobalValue>(Global);
1931 
1932   switch (Linkage) {
1933   case LLVMExternalLinkage:
1934     GV->setLinkage(GlobalValue::ExternalLinkage);
1935     break;
1936   case LLVMAvailableExternallyLinkage:
1937     GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1938     break;
1939   case LLVMLinkOnceAnyLinkage:
1940     GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
1941     break;
1942   case LLVMLinkOnceODRLinkage:
1943     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
1944     break;
1945   case LLVMLinkOnceODRAutoHideLinkage:
1946     LLVM_DEBUG(
1947         errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no "
1948                   "longer supported.");
1949     break;
1950   case LLVMWeakAnyLinkage:
1951     GV->setLinkage(GlobalValue::WeakAnyLinkage);
1952     break;
1953   case LLVMWeakODRLinkage:
1954     GV->setLinkage(GlobalValue::WeakODRLinkage);
1955     break;
1956   case LLVMAppendingLinkage:
1957     GV->setLinkage(GlobalValue::AppendingLinkage);
1958     break;
1959   case LLVMInternalLinkage:
1960     GV->setLinkage(GlobalValue::InternalLinkage);
1961     break;
1962   case LLVMPrivateLinkage:
1963     GV->setLinkage(GlobalValue::PrivateLinkage);
1964     break;
1965   case LLVMLinkerPrivateLinkage:
1966     GV->setLinkage(GlobalValue::PrivateLinkage);
1967     break;
1968   case LLVMLinkerPrivateWeakLinkage:
1969     GV->setLinkage(GlobalValue::PrivateLinkage);
1970     break;
1971   case LLVMDLLImportLinkage:
1972     LLVM_DEBUG(
1973         errs()
1974         << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported.");
1975     break;
1976   case LLVMDLLExportLinkage:
1977     LLVM_DEBUG(
1978         errs()
1979         << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported.");
1980     break;
1981   case LLVMExternalWeakLinkage:
1982     GV->setLinkage(GlobalValue::ExternalWeakLinkage);
1983     break;
1984   case LLVMGhostLinkage:
1985     LLVM_DEBUG(
1986         errs() << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");
1987     break;
1988   case LLVMCommonLinkage:
1989     GV->setLinkage(GlobalValue::CommonLinkage);
1990     break;
1991   }
1992 }
1993 
1994 const char *LLVMGetSection(LLVMValueRef Global) {
1995   // Using .data() is safe because of how GlobalObject::setSection is
1996   // implemented.
1997   return unwrap<GlobalValue>(Global)->getSection().data();
1998 }
1999 
2000 void LLVMSetSection(LLVMValueRef Global, const char *Section) {
2001   unwrap<GlobalObject>(Global)->setSection(Section);
2002 }
2003 
2004 LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) {
2005   return static_cast<LLVMVisibility>(
2006     unwrap<GlobalValue>(Global)->getVisibility());
2007 }
2008 
2009 void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) {
2010   unwrap<GlobalValue>(Global)
2011     ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz));
2012 }
2013 
2014 LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) {
2015   return static_cast<LLVMDLLStorageClass>(
2016       unwrap<GlobalValue>(Global)->getDLLStorageClass());
2017 }
2018 
2019 void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) {
2020   unwrap<GlobalValue>(Global)->setDLLStorageClass(
2021       static_cast<GlobalValue::DLLStorageClassTypes>(Class));
2022 }
2023 
2024 LLVMUnnamedAddr LLVMGetUnnamedAddress(LLVMValueRef Global) {
2025   switch (unwrap<GlobalValue>(Global)->getUnnamedAddr()) {
2026   case GlobalVariable::UnnamedAddr::None:
2027     return LLVMNoUnnamedAddr;
2028   case GlobalVariable::UnnamedAddr::Local:
2029     return LLVMLocalUnnamedAddr;
2030   case GlobalVariable::UnnamedAddr::Global:
2031     return LLVMGlobalUnnamedAddr;
2032   }
2033   llvm_unreachable("Unknown UnnamedAddr kind!");
2034 }
2035 
2036 void LLVMSetUnnamedAddress(LLVMValueRef Global, LLVMUnnamedAddr UnnamedAddr) {
2037   GlobalValue *GV = unwrap<GlobalValue>(Global);
2038 
2039   switch (UnnamedAddr) {
2040   case LLVMNoUnnamedAddr:
2041     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::None);
2042   case LLVMLocalUnnamedAddr:
2043     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Local);
2044   case LLVMGlobalUnnamedAddr:
2045     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Global);
2046   }
2047 }
2048 
2049 LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) {
2050   return unwrap<GlobalValue>(Global)->hasGlobalUnnamedAddr();
2051 }
2052 
2053 void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) {
2054   unwrap<GlobalValue>(Global)->setUnnamedAddr(
2055       HasUnnamedAddr ? GlobalValue::UnnamedAddr::Global
2056                      : GlobalValue::UnnamedAddr::None);
2057 }
2058 
2059 LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef Global) {
2060   return wrap(unwrap<GlobalValue>(Global)->getValueType());
2061 }
2062 
2063 /*--.. Operations on global variables, load and store instructions .........--*/
2064 
2065 unsigned LLVMGetAlignment(LLVMValueRef V) {
2066   Value *P = unwrap<Value>(V);
2067   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
2068     return GV->getAlign() ? GV->getAlign()->value() : 0;
2069   if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
2070     return AI->getAlign().value();
2071   if (LoadInst *LI = dyn_cast<LoadInst>(P))
2072     return LI->getAlign().value();
2073   if (StoreInst *SI = dyn_cast<StoreInst>(P))
2074     return SI->getAlign().value();
2075   if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))
2076     return RMWI->getAlign().value();
2077   if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))
2078     return CXI->getAlign().value();
2079 
2080   llvm_unreachable(
2081       "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, "
2082       "and AtomicCmpXchgInst have alignment");
2083 }
2084 
2085 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) {
2086   Value *P = unwrap<Value>(V);
2087   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
2088     GV->setAlignment(MaybeAlign(Bytes));
2089   else if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
2090     AI->setAlignment(Align(Bytes));
2091   else if (LoadInst *LI = dyn_cast<LoadInst>(P))
2092     LI->setAlignment(Align(Bytes));
2093   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
2094     SI->setAlignment(Align(Bytes));
2095   else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))
2096     RMWI->setAlignment(Align(Bytes));
2097   else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))
2098     CXI->setAlignment(Align(Bytes));
2099   else
2100     llvm_unreachable(
2101         "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, and "
2102         "and AtomicCmpXchgInst have alignment");
2103 }
2104 
2105 LLVMValueMetadataEntry *LLVMGlobalCopyAllMetadata(LLVMValueRef Value,
2106                                                   size_t *NumEntries) {
2107   return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {
2108     Entries.clear();
2109     if (Instruction *Instr = dyn_cast<Instruction>(unwrap(Value))) {
2110       Instr->getAllMetadata(Entries);
2111     } else {
2112       unwrap<GlobalObject>(Value)->getAllMetadata(Entries);
2113     }
2114   });
2115 }
2116 
2117 unsigned LLVMValueMetadataEntriesGetKind(LLVMValueMetadataEntry *Entries,
2118                                          unsigned Index) {
2119   LLVMOpaqueValueMetadataEntry MVE =
2120       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2121   return MVE.Kind;
2122 }
2123 
2124 LLVMMetadataRef
2125 LLVMValueMetadataEntriesGetMetadata(LLVMValueMetadataEntry *Entries,
2126                                     unsigned Index) {
2127   LLVMOpaqueValueMetadataEntry MVE =
2128       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2129   return MVE.Metadata;
2130 }
2131 
2132 void LLVMDisposeValueMetadataEntries(LLVMValueMetadataEntry *Entries) {
2133   free(Entries);
2134 }
2135 
2136 void LLVMGlobalSetMetadata(LLVMValueRef Global, unsigned Kind,
2137                            LLVMMetadataRef MD) {
2138   unwrap<GlobalObject>(Global)->setMetadata(Kind, unwrap<MDNode>(MD));
2139 }
2140 
2141 void LLVMGlobalEraseMetadata(LLVMValueRef Global, unsigned Kind) {
2142   unwrap<GlobalObject>(Global)->eraseMetadata(Kind);
2143 }
2144 
2145 void LLVMGlobalClearMetadata(LLVMValueRef Global) {
2146   unwrap<GlobalObject>(Global)->clearMetadata();
2147 }
2148 
2149 /*--.. Operations on global variables ......................................--*/
2150 
2151 LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) {
2152   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2153                                  GlobalValue::ExternalLinkage, nullptr, Name));
2154 }
2155 
2156 LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
2157                                          const char *Name,
2158                                          unsigned AddressSpace) {
2159   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2160                                  GlobalValue::ExternalLinkage, nullptr, Name,
2161                                  nullptr, GlobalVariable::NotThreadLocal,
2162                                  AddressSpace));
2163 }
2164 
2165 LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) {
2166   return wrap(unwrap(M)->getNamedGlobal(Name));
2167 }
2168 
2169 LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) {
2170   Module *Mod = unwrap(M);
2171   Module::global_iterator I = Mod->global_begin();
2172   if (I == Mod->global_end())
2173     return nullptr;
2174   return wrap(&*I);
2175 }
2176 
2177 LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
2178   Module *Mod = unwrap(M);
2179   Module::global_iterator I = Mod->global_end();
2180   if (I == Mod->global_begin())
2181     return nullptr;
2182   return wrap(&*--I);
2183 }
2184 
2185 LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
2186   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2187   Module::global_iterator I(GV);
2188   if (++I == GV->getParent()->global_end())
2189     return nullptr;
2190   return wrap(&*I);
2191 }
2192 
2193 LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
2194   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2195   Module::global_iterator I(GV);
2196   if (I == GV->getParent()->global_begin())
2197     return nullptr;
2198   return wrap(&*--I);
2199 }
2200 
2201 void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
2202   unwrap<GlobalVariable>(GlobalVar)->eraseFromParent();
2203 }
2204 
2205 LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
2206   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
2207   if ( !GV->hasInitializer() )
2208     return nullptr;
2209   return wrap(GV->getInitializer());
2210 }
2211 
2212 void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) {
2213   unwrap<GlobalVariable>(GlobalVar)
2214     ->setInitializer(unwrap<Constant>(ConstantVal));
2215 }
2216 
2217 LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) {
2218   return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal();
2219 }
2220 
2221 void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) {
2222   unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0);
2223 }
2224 
2225 LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) {
2226   return unwrap<GlobalVariable>(GlobalVar)->isConstant();
2227 }
2228 
2229 void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) {
2230   unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0);
2231 }
2232 
2233 LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) {
2234   switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) {
2235   case GlobalVariable::NotThreadLocal:
2236     return LLVMNotThreadLocal;
2237   case GlobalVariable::GeneralDynamicTLSModel:
2238     return LLVMGeneralDynamicTLSModel;
2239   case GlobalVariable::LocalDynamicTLSModel:
2240     return LLVMLocalDynamicTLSModel;
2241   case GlobalVariable::InitialExecTLSModel:
2242     return LLVMInitialExecTLSModel;
2243   case GlobalVariable::LocalExecTLSModel:
2244     return LLVMLocalExecTLSModel;
2245   }
2246 
2247   llvm_unreachable("Invalid GlobalVariable thread local mode");
2248 }
2249 
2250 void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) {
2251   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2252 
2253   switch (Mode) {
2254   case LLVMNotThreadLocal:
2255     GV->setThreadLocalMode(GlobalVariable::NotThreadLocal);
2256     break;
2257   case LLVMGeneralDynamicTLSModel:
2258     GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel);
2259     break;
2260   case LLVMLocalDynamicTLSModel:
2261     GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel);
2262     break;
2263   case LLVMInitialExecTLSModel:
2264     GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
2265     break;
2266   case LLVMLocalExecTLSModel:
2267     GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel);
2268     break;
2269   }
2270 }
2271 
2272 LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) {
2273   return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized();
2274 }
2275 
2276 void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) {
2277   unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit);
2278 }
2279 
2280 /*--.. Operations on aliases ......................................--*/
2281 
2282 LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
2283                           const char *Name) {
2284   auto *PTy = cast<PointerType>(unwrap(Ty));
2285   return wrap(GlobalAlias::create(PTy->getNonOpaquePointerElementType(),
2286                                   PTy->getAddressSpace(),
2287                                   GlobalValue::ExternalLinkage, Name,
2288                                   unwrap<Constant>(Aliasee), unwrap(M)));
2289 }
2290 
2291 LLVMValueRef LLVMAddAlias2(LLVMModuleRef M, LLVMTypeRef ValueTy,
2292                            unsigned AddrSpace, LLVMValueRef Aliasee,
2293                            const char *Name) {
2294   return wrap(GlobalAlias::create(unwrap(ValueTy), AddrSpace,
2295                                   GlobalValue::ExternalLinkage, Name,
2296                                   unwrap<Constant>(Aliasee), unwrap(M)));
2297 }
2298 
2299 LLVMValueRef LLVMGetNamedGlobalAlias(LLVMModuleRef M,
2300                                      const char *Name, size_t NameLen) {
2301   return wrap(unwrap(M)->getNamedAlias(StringRef(Name, NameLen)));
2302 }
2303 
2304 LLVMValueRef LLVMGetFirstGlobalAlias(LLVMModuleRef M) {
2305   Module *Mod = unwrap(M);
2306   Module::alias_iterator I = Mod->alias_begin();
2307   if (I == Mod->alias_end())
2308     return nullptr;
2309   return wrap(&*I);
2310 }
2311 
2312 LLVMValueRef LLVMGetLastGlobalAlias(LLVMModuleRef M) {
2313   Module *Mod = unwrap(M);
2314   Module::alias_iterator I = Mod->alias_end();
2315   if (I == Mod->alias_begin())
2316     return nullptr;
2317   return wrap(&*--I);
2318 }
2319 
2320 LLVMValueRef LLVMGetNextGlobalAlias(LLVMValueRef GA) {
2321   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2322   Module::alias_iterator I(Alias);
2323   if (++I == Alias->getParent()->alias_end())
2324     return nullptr;
2325   return wrap(&*I);
2326 }
2327 
2328 LLVMValueRef LLVMGetPreviousGlobalAlias(LLVMValueRef GA) {
2329   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2330   Module::alias_iterator I(Alias);
2331   if (I == Alias->getParent()->alias_begin())
2332     return nullptr;
2333   return wrap(&*--I);
2334 }
2335 
2336 LLVMValueRef LLVMAliasGetAliasee(LLVMValueRef Alias) {
2337   return wrap(unwrap<GlobalAlias>(Alias)->getAliasee());
2338 }
2339 
2340 void LLVMAliasSetAliasee(LLVMValueRef Alias, LLVMValueRef Aliasee) {
2341   unwrap<GlobalAlias>(Alias)->setAliasee(unwrap<Constant>(Aliasee));
2342 }
2343 
2344 /*--.. Operations on functions .............................................--*/
2345 
2346 LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
2347                              LLVMTypeRef FunctionTy) {
2348   return wrap(Function::Create(unwrap<FunctionType>(FunctionTy),
2349                                GlobalValue::ExternalLinkage, Name, unwrap(M)));
2350 }
2351 
2352 LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) {
2353   return wrap(unwrap(M)->getFunction(Name));
2354 }
2355 
2356 LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) {
2357   Module *Mod = unwrap(M);
2358   Module::iterator I = Mod->begin();
2359   if (I == Mod->end())
2360     return nullptr;
2361   return wrap(&*I);
2362 }
2363 
2364 LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
2365   Module *Mod = unwrap(M);
2366   Module::iterator I = Mod->end();
2367   if (I == Mod->begin())
2368     return nullptr;
2369   return wrap(&*--I);
2370 }
2371 
2372 LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
2373   Function *Func = unwrap<Function>(Fn);
2374   Module::iterator I(Func);
2375   if (++I == Func->getParent()->end())
2376     return nullptr;
2377   return wrap(&*I);
2378 }
2379 
2380 LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
2381   Function *Func = unwrap<Function>(Fn);
2382   Module::iterator I(Func);
2383   if (I == Func->getParent()->begin())
2384     return nullptr;
2385   return wrap(&*--I);
2386 }
2387 
2388 void LLVMDeleteFunction(LLVMValueRef Fn) {
2389   unwrap<Function>(Fn)->eraseFromParent();
2390 }
2391 
2392 LLVMBool LLVMHasPersonalityFn(LLVMValueRef Fn) {
2393   return unwrap<Function>(Fn)->hasPersonalityFn();
2394 }
2395 
2396 LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn) {
2397   return wrap(unwrap<Function>(Fn)->getPersonalityFn());
2398 }
2399 
2400 void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn) {
2401   unwrap<Function>(Fn)->setPersonalityFn(unwrap<Constant>(PersonalityFn));
2402 }
2403 
2404 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
2405   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
2406     return F->getIntrinsicID();
2407   return 0;
2408 }
2409 
2410 static Intrinsic::ID llvm_map_to_intrinsic_id(unsigned ID) {
2411   assert(ID < llvm::Intrinsic::num_intrinsics && "Intrinsic ID out of range");
2412   return llvm::Intrinsic::ID(ID);
2413 }
2414 
2415 LLVMValueRef LLVMGetIntrinsicDeclaration(LLVMModuleRef Mod,
2416                                          unsigned ID,
2417                                          LLVMTypeRef *ParamTypes,
2418                                          size_t ParamCount) {
2419   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2420   auto IID = llvm_map_to_intrinsic_id(ID);
2421   return wrap(llvm::Intrinsic::getDeclaration(unwrap(Mod), IID, Tys));
2422 }
2423 
2424 const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength) {
2425   auto IID = llvm_map_to_intrinsic_id(ID);
2426   auto Str = llvm::Intrinsic::getName(IID);
2427   *NameLength = Str.size();
2428   return Str.data();
2429 }
2430 
2431 LLVMTypeRef LLVMIntrinsicGetType(LLVMContextRef Ctx, unsigned ID,
2432                                  LLVMTypeRef *ParamTypes, size_t ParamCount) {
2433   auto IID = llvm_map_to_intrinsic_id(ID);
2434   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2435   return wrap(llvm::Intrinsic::getType(*unwrap(Ctx), IID, Tys));
2436 }
2437 
2438 const char *LLVMIntrinsicCopyOverloadedName(unsigned ID,
2439                                             LLVMTypeRef *ParamTypes,
2440                                             size_t ParamCount,
2441                                             size_t *NameLength) {
2442   auto IID = llvm_map_to_intrinsic_id(ID);
2443   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2444   auto Str = llvm::Intrinsic::getNameNoUnnamedTypes(IID, Tys);
2445   *NameLength = Str.length();
2446   return strdup(Str.c_str());
2447 }
2448 
2449 const char *LLVMIntrinsicCopyOverloadedName2(LLVMModuleRef Mod, unsigned ID,
2450                                              LLVMTypeRef *ParamTypes,
2451                                              size_t ParamCount,
2452                                              size_t *NameLength) {
2453   auto IID = llvm_map_to_intrinsic_id(ID);
2454   ArrayRef<Type *> Tys(unwrap(ParamTypes), ParamCount);
2455   auto Str = llvm::Intrinsic::getName(IID, Tys, unwrap(Mod));
2456   *NameLength = Str.length();
2457   return strdup(Str.c_str());
2458 }
2459 
2460 unsigned LLVMLookupIntrinsicID(const char *Name, size_t NameLen) {
2461   return Function::lookupIntrinsicID({Name, NameLen});
2462 }
2463 
2464 LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID) {
2465   auto IID = llvm_map_to_intrinsic_id(ID);
2466   return llvm::Intrinsic::isOverloaded(IID);
2467 }
2468 
2469 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {
2470   return unwrap<Function>(Fn)->getCallingConv();
2471 }
2472 
2473 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) {
2474   return unwrap<Function>(Fn)->setCallingConv(
2475     static_cast<CallingConv::ID>(CC));
2476 }
2477 
2478 const char *LLVMGetGC(LLVMValueRef Fn) {
2479   Function *F = unwrap<Function>(Fn);
2480   return F->hasGC()? F->getGC().c_str() : nullptr;
2481 }
2482 
2483 void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
2484   Function *F = unwrap<Function>(Fn);
2485   if (GC)
2486     F->setGC(GC);
2487   else
2488     F->clearGC();
2489 }
2490 
2491 void LLVMAddAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2492                              LLVMAttributeRef A) {
2493   unwrap<Function>(F)->addAttributeAtIndex(Idx, unwrap(A));
2494 }
2495 
2496 unsigned LLVMGetAttributeCountAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx) {
2497   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2498   return AS.getNumAttributes();
2499 }
2500 
2501 void LLVMGetAttributesAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2502                               LLVMAttributeRef *Attrs) {
2503   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2504   for (auto A : AS)
2505     *Attrs++ = wrap(A);
2506 }
2507 
2508 LLVMAttributeRef LLVMGetEnumAttributeAtIndex(LLVMValueRef F,
2509                                              LLVMAttributeIndex Idx,
2510                                              unsigned KindID) {
2511   return wrap(unwrap<Function>(F)->getAttributeAtIndex(
2512       Idx, (Attribute::AttrKind)KindID));
2513 }
2514 
2515 LLVMAttributeRef LLVMGetStringAttributeAtIndex(LLVMValueRef F,
2516                                                LLVMAttributeIndex Idx,
2517                                                const char *K, unsigned KLen) {
2518   return wrap(
2519       unwrap<Function>(F)->getAttributeAtIndex(Idx, StringRef(K, KLen)));
2520 }
2521 
2522 void LLVMRemoveEnumAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2523                                     unsigned KindID) {
2524   unwrap<Function>(F)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);
2525 }
2526 
2527 void LLVMRemoveStringAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2528                                       const char *K, unsigned KLen) {
2529   unwrap<Function>(F)->removeAttributeAtIndex(Idx, StringRef(K, KLen));
2530 }
2531 
2532 void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A,
2533                                         const char *V) {
2534   Function *Func = unwrap<Function>(Fn);
2535   Attribute Attr = Attribute::get(Func->getContext(), A, V);
2536   Func->addFnAttr(Attr);
2537 }
2538 
2539 /*--.. Operations on parameters ............................................--*/
2540 
2541 unsigned LLVMCountParams(LLVMValueRef FnRef) {
2542   // This function is strictly redundant to
2543   //   LLVMCountParamTypes(LLVMGetElementType(LLVMTypeOf(FnRef)))
2544   return unwrap<Function>(FnRef)->arg_size();
2545 }
2546 
2547 void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) {
2548   Function *Fn = unwrap<Function>(FnRef);
2549   for (Argument &A : Fn->args())
2550     *ParamRefs++ = wrap(&A);
2551 }
2552 
2553 LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
2554   Function *Fn = unwrap<Function>(FnRef);
2555   return wrap(&Fn->arg_begin()[index]);
2556 }
2557 
2558 LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
2559   return wrap(unwrap<Argument>(V)->getParent());
2560 }
2561 
2562 LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) {
2563   Function *Func = unwrap<Function>(Fn);
2564   Function::arg_iterator I = Func->arg_begin();
2565   if (I == Func->arg_end())
2566     return nullptr;
2567   return wrap(&*I);
2568 }
2569 
2570 LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
2571   Function *Func = unwrap<Function>(Fn);
2572   Function::arg_iterator I = Func->arg_end();
2573   if (I == Func->arg_begin())
2574     return nullptr;
2575   return wrap(&*--I);
2576 }
2577 
2578 LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
2579   Argument *A = unwrap<Argument>(Arg);
2580   Function *Fn = A->getParent();
2581   if (A->getArgNo() + 1 >= Fn->arg_size())
2582     return nullptr;
2583   return wrap(&Fn->arg_begin()[A->getArgNo() + 1]);
2584 }
2585 
2586 LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
2587   Argument *A = unwrap<Argument>(Arg);
2588   if (A->getArgNo() == 0)
2589     return nullptr;
2590   return wrap(&A->getParent()->arg_begin()[A->getArgNo() - 1]);
2591 }
2592 
2593 void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) {
2594   Argument *A = unwrap<Argument>(Arg);
2595   A->addAttr(Attribute::getWithAlignment(A->getContext(), Align(align)));
2596 }
2597 
2598 /*--.. Operations on ifuncs ................................................--*/
2599 
2600 LLVMValueRef LLVMAddGlobalIFunc(LLVMModuleRef M,
2601                                 const char *Name, size_t NameLen,
2602                                 LLVMTypeRef Ty, unsigned AddrSpace,
2603                                 LLVMValueRef Resolver) {
2604   return wrap(GlobalIFunc::create(unwrap(Ty), AddrSpace,
2605                                   GlobalValue::ExternalLinkage,
2606                                   StringRef(Name, NameLen),
2607                                   unwrap<Constant>(Resolver), unwrap(M)));
2608 }
2609 
2610 LLVMValueRef LLVMGetNamedGlobalIFunc(LLVMModuleRef M,
2611                                      const char *Name, size_t NameLen) {
2612   return wrap(unwrap(M)->getNamedIFunc(StringRef(Name, NameLen)));
2613 }
2614 
2615 LLVMValueRef LLVMGetFirstGlobalIFunc(LLVMModuleRef M) {
2616   Module *Mod = unwrap(M);
2617   Module::ifunc_iterator I = Mod->ifunc_begin();
2618   if (I == Mod->ifunc_end())
2619     return nullptr;
2620   return wrap(&*I);
2621 }
2622 
2623 LLVMValueRef LLVMGetLastGlobalIFunc(LLVMModuleRef M) {
2624   Module *Mod = unwrap(M);
2625   Module::ifunc_iterator I = Mod->ifunc_end();
2626   if (I == Mod->ifunc_begin())
2627     return nullptr;
2628   return wrap(&*--I);
2629 }
2630 
2631 LLVMValueRef LLVMGetNextGlobalIFunc(LLVMValueRef IFunc) {
2632   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2633   Module::ifunc_iterator I(GIF);
2634   if (++I == GIF->getParent()->ifunc_end())
2635     return nullptr;
2636   return wrap(&*I);
2637 }
2638 
2639 LLVMValueRef LLVMGetPreviousGlobalIFunc(LLVMValueRef IFunc) {
2640   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2641   Module::ifunc_iterator I(GIF);
2642   if (I == GIF->getParent()->ifunc_begin())
2643     return nullptr;
2644   return wrap(&*--I);
2645 }
2646 
2647 LLVMValueRef LLVMGetGlobalIFuncResolver(LLVMValueRef IFunc) {
2648   return wrap(unwrap<GlobalIFunc>(IFunc)->getResolver());
2649 }
2650 
2651 void LLVMSetGlobalIFuncResolver(LLVMValueRef IFunc, LLVMValueRef Resolver) {
2652   unwrap<GlobalIFunc>(IFunc)->setResolver(unwrap<Constant>(Resolver));
2653 }
2654 
2655 void LLVMEraseGlobalIFunc(LLVMValueRef IFunc) {
2656   unwrap<GlobalIFunc>(IFunc)->eraseFromParent();
2657 }
2658 
2659 void LLVMRemoveGlobalIFunc(LLVMValueRef IFunc) {
2660   unwrap<GlobalIFunc>(IFunc)->removeFromParent();
2661 }
2662 
2663 /*--.. Operations on basic blocks ..........................................--*/
2664 
2665 LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) {
2666   return wrap(static_cast<Value*>(unwrap(BB)));
2667 }
2668 
2669 LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) {
2670   return isa<BasicBlock>(unwrap(Val));
2671 }
2672 
2673 LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) {
2674   return wrap(unwrap<BasicBlock>(Val));
2675 }
2676 
2677 const char *LLVMGetBasicBlockName(LLVMBasicBlockRef BB) {
2678   return unwrap(BB)->getName().data();
2679 }
2680 
2681 LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) {
2682   return wrap(unwrap(BB)->getParent());
2683 }
2684 
2685 LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) {
2686   return wrap(unwrap(BB)->getTerminator());
2687 }
2688 
2689 unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) {
2690   return unwrap<Function>(FnRef)->size();
2691 }
2692 
2693 void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
2694   Function *Fn = unwrap<Function>(FnRef);
2695   for (BasicBlock &BB : *Fn)
2696     *BasicBlocksRefs++ = wrap(&BB);
2697 }
2698 
2699 LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
2700   return wrap(&unwrap<Function>(Fn)->getEntryBlock());
2701 }
2702 
2703 LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) {
2704   Function *Func = unwrap<Function>(Fn);
2705   Function::iterator I = Func->begin();
2706   if (I == Func->end())
2707     return nullptr;
2708   return wrap(&*I);
2709 }
2710 
2711 LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
2712   Function *Func = unwrap<Function>(Fn);
2713   Function::iterator I = Func->end();
2714   if (I == Func->begin())
2715     return nullptr;
2716   return wrap(&*--I);
2717 }
2718 
2719 LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
2720   BasicBlock *Block = unwrap(BB);
2721   Function::iterator I(Block);
2722   if (++I == Block->getParent()->end())
2723     return nullptr;
2724   return wrap(&*I);
2725 }
2726 
2727 LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
2728   BasicBlock *Block = unwrap(BB);
2729   Function::iterator I(Block);
2730   if (I == Block->getParent()->begin())
2731     return nullptr;
2732   return wrap(&*--I);
2733 }
2734 
2735 LLVMBasicBlockRef LLVMCreateBasicBlockInContext(LLVMContextRef C,
2736                                                 const char *Name) {
2737   return wrap(llvm::BasicBlock::Create(*unwrap(C), Name));
2738 }
2739 
2740 void LLVMInsertExistingBasicBlockAfterInsertBlock(LLVMBuilderRef Builder,
2741                                                   LLVMBasicBlockRef BB) {
2742   BasicBlock *ToInsert = unwrap(BB);
2743   BasicBlock *CurBB = unwrap(Builder)->GetInsertBlock();
2744   assert(CurBB && "current insertion point is invalid!");
2745   CurBB->getParent()->getBasicBlockList().insertAfter(CurBB->getIterator(),
2746                                                       ToInsert);
2747 }
2748 
2749 void LLVMAppendExistingBasicBlock(LLVMValueRef Fn,
2750                                   LLVMBasicBlockRef BB) {
2751   unwrap<Function>(Fn)->getBasicBlockList().push_back(unwrap(BB));
2752 }
2753 
2754 LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
2755                                                 LLVMValueRef FnRef,
2756                                                 const char *Name) {
2757   return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef)));
2758 }
2759 
2760 LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) {
2761   return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name);
2762 }
2763 
2764 LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
2765                                                 LLVMBasicBlockRef BBRef,
2766                                                 const char *Name) {
2767   BasicBlock *BB = unwrap(BBRef);
2768   return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB));
2769 }
2770 
2771 LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef,
2772                                        const char *Name) {
2773   return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name);
2774 }
2775 
2776 void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) {
2777   unwrap(BBRef)->eraseFromParent();
2778 }
2779 
2780 void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) {
2781   unwrap(BBRef)->removeFromParent();
2782 }
2783 
2784 void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2785   unwrap(BB)->moveBefore(unwrap(MovePos));
2786 }
2787 
2788 void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2789   unwrap(BB)->moveAfter(unwrap(MovePos));
2790 }
2791 
2792 /*--.. Operations on instructions ..........................................--*/
2793 
2794 LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) {
2795   return wrap(unwrap<Instruction>(Inst)->getParent());
2796 }
2797 
2798 LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) {
2799   BasicBlock *Block = unwrap(BB);
2800   BasicBlock::iterator I = Block->begin();
2801   if (I == Block->end())
2802     return nullptr;
2803   return wrap(&*I);
2804 }
2805 
2806 LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
2807   BasicBlock *Block = unwrap(BB);
2808   BasicBlock::iterator I = Block->end();
2809   if (I == Block->begin())
2810     return nullptr;
2811   return wrap(&*--I);
2812 }
2813 
2814 LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
2815   Instruction *Instr = unwrap<Instruction>(Inst);
2816   BasicBlock::iterator I(Instr);
2817   if (++I == Instr->getParent()->end())
2818     return nullptr;
2819   return wrap(&*I);
2820 }
2821 
2822 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
2823   Instruction *Instr = unwrap<Instruction>(Inst);
2824   BasicBlock::iterator I(Instr);
2825   if (I == Instr->getParent()->begin())
2826     return nullptr;
2827   return wrap(&*--I);
2828 }
2829 
2830 void LLVMInstructionRemoveFromParent(LLVMValueRef Inst) {
2831   unwrap<Instruction>(Inst)->removeFromParent();
2832 }
2833 
2834 void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
2835   unwrap<Instruction>(Inst)->eraseFromParent();
2836 }
2837 
2838 LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) {
2839   if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst)))
2840     return (LLVMIntPredicate)I->getPredicate();
2841   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2842     if (CE->getOpcode() == Instruction::ICmp)
2843       return (LLVMIntPredicate)CE->getPredicate();
2844   return (LLVMIntPredicate)0;
2845 }
2846 
2847 LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) {
2848   if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst)))
2849     return (LLVMRealPredicate)I->getPredicate();
2850   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2851     if (CE->getOpcode() == Instruction::FCmp)
2852       return (LLVMRealPredicate)CE->getPredicate();
2853   return (LLVMRealPredicate)0;
2854 }
2855 
2856 LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) {
2857   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2858     return map_to_llvmopcode(C->getOpcode());
2859   return (LLVMOpcode)0;
2860 }
2861 
2862 LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) {
2863   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2864     return wrap(C->clone());
2865   return nullptr;
2866 }
2867 
2868 LLVMValueRef LLVMIsATerminatorInst(LLVMValueRef Inst) {
2869   Instruction *I = dyn_cast<Instruction>(unwrap(Inst));
2870   return (I && I->isTerminator()) ? wrap(I) : nullptr;
2871 }
2872 
2873 unsigned LLVMGetNumArgOperands(LLVMValueRef Instr) {
2874   if (FuncletPadInst *FPI = dyn_cast<FuncletPadInst>(unwrap(Instr))) {
2875     return FPI->getNumArgOperands();
2876   }
2877   return unwrap<CallBase>(Instr)->arg_size();
2878 }
2879 
2880 /*--.. Call and invoke instructions ........................................--*/
2881 
2882 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) {
2883   return unwrap<CallBase>(Instr)->getCallingConv();
2884 }
2885 
2886 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {
2887   return unwrap<CallBase>(Instr)->setCallingConv(
2888       static_cast<CallingConv::ID>(CC));
2889 }
2890 
2891 void LLVMSetInstrParamAlignment(LLVMValueRef Instr, LLVMAttributeIndex Idx,
2892                                 unsigned align) {
2893   auto *Call = unwrap<CallBase>(Instr);
2894   Attribute AlignAttr =
2895       Attribute::getWithAlignment(Call->getContext(), Align(align));
2896   Call->addAttributeAtIndex(Idx, AlignAttr);
2897 }
2898 
2899 void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2900                               LLVMAttributeRef A) {
2901   unwrap<CallBase>(C)->addAttributeAtIndex(Idx, unwrap(A));
2902 }
2903 
2904 unsigned LLVMGetCallSiteAttributeCount(LLVMValueRef C,
2905                                        LLVMAttributeIndex Idx) {
2906   auto *Call = unwrap<CallBase>(C);
2907   auto AS = Call->getAttributes().getAttributes(Idx);
2908   return AS.getNumAttributes();
2909 }
2910 
2911 void LLVMGetCallSiteAttributes(LLVMValueRef C, LLVMAttributeIndex Idx,
2912                                LLVMAttributeRef *Attrs) {
2913   auto *Call = unwrap<CallBase>(C);
2914   auto AS = Call->getAttributes().getAttributes(Idx);
2915   for (auto A : AS)
2916     *Attrs++ = wrap(A);
2917 }
2918 
2919 LLVMAttributeRef LLVMGetCallSiteEnumAttribute(LLVMValueRef C,
2920                                               LLVMAttributeIndex Idx,
2921                                               unsigned KindID) {
2922   return wrap(unwrap<CallBase>(C)->getAttributeAtIndex(
2923       Idx, (Attribute::AttrKind)KindID));
2924 }
2925 
2926 LLVMAttributeRef LLVMGetCallSiteStringAttribute(LLVMValueRef C,
2927                                                 LLVMAttributeIndex Idx,
2928                                                 const char *K, unsigned KLen) {
2929   return wrap(
2930       unwrap<CallBase>(C)->getAttributeAtIndex(Idx, StringRef(K, KLen)));
2931 }
2932 
2933 void LLVMRemoveCallSiteEnumAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2934                                      unsigned KindID) {
2935   unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);
2936 }
2937 
2938 void LLVMRemoveCallSiteStringAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2939                                        const char *K, unsigned KLen) {
2940   unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, StringRef(K, KLen));
2941 }
2942 
2943 LLVMValueRef LLVMGetCalledValue(LLVMValueRef Instr) {
2944   return wrap(unwrap<CallBase>(Instr)->getCalledOperand());
2945 }
2946 
2947 LLVMTypeRef LLVMGetCalledFunctionType(LLVMValueRef Instr) {
2948   return wrap(unwrap<CallBase>(Instr)->getFunctionType());
2949 }
2950 
2951 /*--.. Operations on call instructions (only) ..............................--*/
2952 
2953 LLVMBool LLVMIsTailCall(LLVMValueRef Call) {
2954   return unwrap<CallInst>(Call)->isTailCall();
2955 }
2956 
2957 void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) {
2958   unwrap<CallInst>(Call)->setTailCall(isTailCall);
2959 }
2960 
2961 /*--.. Operations on invoke instructions (only) ............................--*/
2962 
2963 LLVMBasicBlockRef LLVMGetNormalDest(LLVMValueRef Invoke) {
2964   return wrap(unwrap<InvokeInst>(Invoke)->getNormalDest());
2965 }
2966 
2967 LLVMBasicBlockRef LLVMGetUnwindDest(LLVMValueRef Invoke) {
2968   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2969     return wrap(CRI->getUnwindDest());
2970   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2971     return wrap(CSI->getUnwindDest());
2972   }
2973   return wrap(unwrap<InvokeInst>(Invoke)->getUnwindDest());
2974 }
2975 
2976 void LLVMSetNormalDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2977   unwrap<InvokeInst>(Invoke)->setNormalDest(unwrap(B));
2978 }
2979 
2980 void LLVMSetUnwindDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2981   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2982     return CRI->setUnwindDest(unwrap(B));
2983   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2984     return CSI->setUnwindDest(unwrap(B));
2985   }
2986   unwrap<InvokeInst>(Invoke)->setUnwindDest(unwrap(B));
2987 }
2988 
2989 /*--.. Operations on terminators ...........................................--*/
2990 
2991 unsigned LLVMGetNumSuccessors(LLVMValueRef Term) {
2992   return unwrap<Instruction>(Term)->getNumSuccessors();
2993 }
2994 
2995 LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) {
2996   return wrap(unwrap<Instruction>(Term)->getSuccessor(i));
2997 }
2998 
2999 void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) {
3000   return unwrap<Instruction>(Term)->setSuccessor(i, unwrap(block));
3001 }
3002 
3003 /*--.. Operations on branch instructions (only) ............................--*/
3004 
3005 LLVMBool LLVMIsConditional(LLVMValueRef Branch) {
3006   return unwrap<BranchInst>(Branch)->isConditional();
3007 }
3008 
3009 LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) {
3010   return wrap(unwrap<BranchInst>(Branch)->getCondition());
3011 }
3012 
3013 void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) {
3014   return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond));
3015 }
3016 
3017 /*--.. Operations on switch instructions (only) ............................--*/
3018 
3019 LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) {
3020   return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest());
3021 }
3022 
3023 /*--.. Operations on alloca instructions (only) ............................--*/
3024 
3025 LLVMTypeRef LLVMGetAllocatedType(LLVMValueRef Alloca) {
3026   return wrap(unwrap<AllocaInst>(Alloca)->getAllocatedType());
3027 }
3028 
3029 /*--.. Operations on gep instructions (only) ...............................--*/
3030 
3031 LLVMBool LLVMIsInBounds(LLVMValueRef GEP) {
3032   return unwrap<GEPOperator>(GEP)->isInBounds();
3033 }
3034 
3035 void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds) {
3036   return unwrap<GetElementPtrInst>(GEP)->setIsInBounds(InBounds);
3037 }
3038 
3039 LLVMTypeRef LLVMGetGEPSourceElementType(LLVMValueRef GEP) {
3040   return wrap(unwrap<GEPOperator>(GEP)->getSourceElementType());
3041 }
3042 
3043 /*--.. Operations on phi nodes .............................................--*/
3044 
3045 void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
3046                      LLVMBasicBlockRef *IncomingBlocks, unsigned Count) {
3047   PHINode *PhiVal = unwrap<PHINode>(PhiNode);
3048   for (unsigned I = 0; I != Count; ++I)
3049     PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I]));
3050 }
3051 
3052 unsigned LLVMCountIncoming(LLVMValueRef PhiNode) {
3053   return unwrap<PHINode>(PhiNode)->getNumIncomingValues();
3054 }
3055 
3056 LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) {
3057   return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index));
3058 }
3059 
3060 LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) {
3061   return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index));
3062 }
3063 
3064 /*--.. Operations on extractvalue and insertvalue nodes ....................--*/
3065 
3066 unsigned LLVMGetNumIndices(LLVMValueRef Inst) {
3067   auto *I = unwrap(Inst);
3068   if (auto *GEP = dyn_cast<GEPOperator>(I))
3069     return GEP->getNumIndices();
3070   if (auto *EV = dyn_cast<ExtractValueInst>(I))
3071     return EV->getNumIndices();
3072   if (auto *IV = dyn_cast<InsertValueInst>(I))
3073     return IV->getNumIndices();
3074   llvm_unreachable(
3075     "LLVMGetNumIndices applies only to extractvalue and insertvalue!");
3076 }
3077 
3078 const unsigned *LLVMGetIndices(LLVMValueRef Inst) {
3079   auto *I = unwrap(Inst);
3080   if (auto *EV = dyn_cast<ExtractValueInst>(I))
3081     return EV->getIndices().data();
3082   if (auto *IV = dyn_cast<InsertValueInst>(I))
3083     return IV->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 LLVMOpcode LLVMGetCastOpcode(LLVMValueRef Src, LLVMBool SrcIsSigned,
3923                              LLVMTypeRef DestTy, LLVMBool DestIsSigned) {
3924   return map_to_llvmopcode(CastInst::getCastOpcode(
3925       unwrap(Src), SrcIsSigned, unwrap(DestTy), DestIsSigned));
3926 }
3927 
3928 /*--.. Comparisons .........................................................--*/
3929 
3930 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op,
3931                            LLVMValueRef LHS, LLVMValueRef RHS,
3932                            const char *Name) {
3933   return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op),
3934                                     unwrap(LHS), unwrap(RHS), Name));
3935 }
3936 
3937 LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op,
3938                            LLVMValueRef LHS, LLVMValueRef RHS,
3939                            const char *Name) {
3940   return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op),
3941                                     unwrap(LHS), unwrap(RHS), Name));
3942 }
3943 
3944 /*--.. Miscellaneous instructions ..........................................--*/
3945 
3946 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) {
3947   return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name));
3948 }
3949 
3950 LLVMValueRef LLVMBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
3951                            LLVMValueRef *Args, unsigned NumArgs,
3952                            const char *Name) {
3953   Value *V = unwrap(Fn);
3954   FunctionType *FnT =
3955       cast<FunctionType>(V->getType()->getNonOpaquePointerElementType());
3956 
3957   return wrap(unwrap(B)->CreateCall(FnT, unwrap(Fn),
3958                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3959 }
3960 
3961 LLVMValueRef LLVMBuildCall2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
3962                             LLVMValueRef *Args, unsigned NumArgs,
3963                             const char *Name) {
3964   FunctionType *FTy = unwrap<FunctionType>(Ty);
3965   return wrap(unwrap(B)->CreateCall(FTy, unwrap(Fn),
3966                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3967 }
3968 
3969 LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If,
3970                              LLVMValueRef Then, LLVMValueRef Else,
3971                              const char *Name) {
3972   return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else),
3973                                       Name));
3974 }
3975 
3976 LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List,
3977                             LLVMTypeRef Ty, const char *Name) {
3978   return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name));
3979 }
3980 
3981 LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal,
3982                                       LLVMValueRef Index, const char *Name) {
3983   return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index),
3984                                               Name));
3985 }
3986 
3987 LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal,
3988                                     LLVMValueRef EltVal, LLVMValueRef Index,
3989                                     const char *Name) {
3990   return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal),
3991                                              unwrap(Index), Name));
3992 }
3993 
3994 LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1,
3995                                     LLVMValueRef V2, LLVMValueRef Mask,
3996                                     const char *Name) {
3997   return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2),
3998                                              unwrap(Mask), Name));
3999 }
4000 
4001 LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal,
4002                                    unsigned Index, const char *Name) {
4003   return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name));
4004 }
4005 
4006 LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal,
4007                                   LLVMValueRef EltVal, unsigned Index,
4008                                   const char *Name) {
4009   return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal),
4010                                            Index, Name));
4011 }
4012 
4013 LLVMValueRef LLVMBuildFreeze(LLVMBuilderRef B, LLVMValueRef Val,
4014                              const char *Name) {
4015   return wrap(unwrap(B)->CreateFreeze(unwrap(Val), Name));
4016 }
4017 
4018 LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val,
4019                              const char *Name) {
4020   return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name));
4021 }
4022 
4023 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val,
4024                                 const char *Name) {
4025   return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name));
4026 }
4027 
4028 LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef B, LLVMValueRef LHS,
4029                               LLVMValueRef RHS, const char *Name) {
4030   Value *L = unwrap(LHS);
4031   Type *ElemTy = L->getType()->getNonOpaquePointerElementType();
4032   return wrap(unwrap(B)->CreatePtrDiff(ElemTy, L, unwrap(RHS), Name));
4033 }
4034 
4035 LLVMValueRef LLVMBuildPtrDiff2(LLVMBuilderRef B, LLVMTypeRef ElemTy,
4036                                LLVMValueRef LHS, LLVMValueRef RHS,
4037                                const char *Name) {
4038   return wrap(unwrap(B)->CreatePtrDiff(unwrap(ElemTy), unwrap(LHS),
4039                                        unwrap(RHS), Name));
4040 }
4041 
4042 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op,
4043                                LLVMValueRef PTR, LLVMValueRef Val,
4044                                LLVMAtomicOrdering ordering,
4045                                LLVMBool singleThread) {
4046   AtomicRMWInst::BinOp intop = mapFromLLVMRMWBinOp(op);
4047   return wrap(unwrap(B)->CreateAtomicRMW(
4048       intop, unwrap(PTR), unwrap(Val), MaybeAlign(),
4049       mapFromLLVMOrdering(ordering),
4050       singleThread ? SyncScope::SingleThread : SyncScope::System));
4051 }
4052 
4053 LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Ptr,
4054                                     LLVMValueRef Cmp, LLVMValueRef New,
4055                                     LLVMAtomicOrdering SuccessOrdering,
4056                                     LLVMAtomicOrdering FailureOrdering,
4057                                     LLVMBool singleThread) {
4058 
4059   return wrap(unwrap(B)->CreateAtomicCmpXchg(
4060       unwrap(Ptr), unwrap(Cmp), unwrap(New), MaybeAlign(),
4061       mapFromLLVMOrdering(SuccessOrdering),
4062       mapFromLLVMOrdering(FailureOrdering),
4063       singleThread ? SyncScope::SingleThread : SyncScope::System));
4064 }
4065 
4066 unsigned LLVMGetNumMaskElements(LLVMValueRef SVInst) {
4067   Value *P = unwrap<Value>(SVInst);
4068   ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);
4069   return I->getShuffleMask().size();
4070 }
4071 
4072 int LLVMGetMaskValue(LLVMValueRef SVInst, unsigned Elt) {
4073   Value *P = unwrap<Value>(SVInst);
4074   ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);
4075   return I->getMaskValue(Elt);
4076 }
4077 
4078 int LLVMGetUndefMaskElem(void) { return UndefMaskElem; }
4079 
4080 LLVMBool LLVMIsAtomicSingleThread(LLVMValueRef AtomicInst) {
4081   Value *P = unwrap<Value>(AtomicInst);
4082 
4083   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
4084     return I->getSyncScopeID() == SyncScope::SingleThread;
4085   return cast<AtomicCmpXchgInst>(P)->getSyncScopeID() ==
4086              SyncScope::SingleThread;
4087 }
4088 
4089 void LLVMSetAtomicSingleThread(LLVMValueRef AtomicInst, LLVMBool NewValue) {
4090   Value *P = unwrap<Value>(AtomicInst);
4091   SyncScope::ID SSID = NewValue ? SyncScope::SingleThread : SyncScope::System;
4092 
4093   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
4094     return I->setSyncScopeID(SSID);
4095   return cast<AtomicCmpXchgInst>(P)->setSyncScopeID(SSID);
4096 }
4097 
4098 LLVMAtomicOrdering LLVMGetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst)  {
4099   Value *P = unwrap<Value>(CmpXchgInst);
4100   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getSuccessOrdering());
4101 }
4102 
4103 void LLVMSetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst,
4104                                    LLVMAtomicOrdering Ordering) {
4105   Value *P = unwrap<Value>(CmpXchgInst);
4106   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
4107 
4108   return cast<AtomicCmpXchgInst>(P)->setSuccessOrdering(O);
4109 }
4110 
4111 LLVMAtomicOrdering LLVMGetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst)  {
4112   Value *P = unwrap<Value>(CmpXchgInst);
4113   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getFailureOrdering());
4114 }
4115 
4116 void LLVMSetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst,
4117                                    LLVMAtomicOrdering Ordering) {
4118   Value *P = unwrap<Value>(CmpXchgInst);
4119   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
4120 
4121   return cast<AtomicCmpXchgInst>(P)->setFailureOrdering(O);
4122 }
4123 
4124 /*===-- Module providers --------------------------------------------------===*/
4125 
4126 LLVMModuleProviderRef
4127 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {
4128   return reinterpret_cast<LLVMModuleProviderRef>(M);
4129 }
4130 
4131 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {
4132   delete unwrap(MP);
4133 }
4134 
4135 
4136 /*===-- Memory buffers ----------------------------------------------------===*/
4137 
4138 LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(
4139     const char *Path,
4140     LLVMMemoryBufferRef *OutMemBuf,
4141     char **OutMessage) {
4142 
4143   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
4144   if (std::error_code EC = MBOrErr.getError()) {
4145     *OutMessage = strdup(EC.message().c_str());
4146     return 1;
4147   }
4148   *OutMemBuf = wrap(MBOrErr.get().release());
4149   return 0;
4150 }
4151 
4152 LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
4153                                          char **OutMessage) {
4154   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();
4155   if (std::error_code EC = MBOrErr.getError()) {
4156     *OutMessage = strdup(EC.message().c_str());
4157     return 1;
4158   }
4159   *OutMemBuf = wrap(MBOrErr.get().release());
4160   return 0;
4161 }
4162 
4163 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
4164     const char *InputData,
4165     size_t InputDataLength,
4166     const char *BufferName,
4167     LLVMBool RequiresNullTerminator) {
4168 
4169   return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength),
4170                                          StringRef(BufferName),
4171                                          RequiresNullTerminator).release());
4172 }
4173 
4174 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(
4175     const char *InputData,
4176     size_t InputDataLength,
4177     const char *BufferName) {
4178 
4179   return wrap(
4180       MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength),
4181                                      StringRef(BufferName)).release());
4182 }
4183 
4184 const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) {
4185   return unwrap(MemBuf)->getBufferStart();
4186 }
4187 
4188 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) {
4189   return unwrap(MemBuf)->getBufferSize();
4190 }
4191 
4192 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) {
4193   delete unwrap(MemBuf);
4194 }
4195 
4196 /*===-- Pass Registry -----------------------------------------------------===*/
4197 
4198 LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void) {
4199   return wrap(PassRegistry::getPassRegistry());
4200 }
4201 
4202 /*===-- Pass Manager ------------------------------------------------------===*/
4203 
4204 LLVMPassManagerRef LLVMCreatePassManager() {
4205   return wrap(new legacy::PassManager());
4206 }
4207 
4208 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
4209   return wrap(new legacy::FunctionPassManager(unwrap(M)));
4210 }
4211 
4212 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
4213   return LLVMCreateFunctionPassManagerForModule(
4214                                             reinterpret_cast<LLVMModuleRef>(P));
4215 }
4216 
4217 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
4218   return unwrap<legacy::PassManager>(PM)->run(*unwrap(M));
4219 }
4220 
4221 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
4222   return unwrap<legacy::FunctionPassManager>(FPM)->doInitialization();
4223 }
4224 
4225 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
4226   return unwrap<legacy::FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
4227 }
4228 
4229 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
4230   return unwrap<legacy::FunctionPassManager>(FPM)->doFinalization();
4231 }
4232 
4233 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
4234   delete unwrap(PM);
4235 }
4236 
4237 /*===-- Threading ------------------------------------------------------===*/
4238 
4239 LLVMBool LLVMStartMultithreaded() {
4240   return LLVMIsMultithreaded();
4241 }
4242 
4243 void LLVMStopMultithreaded() {
4244 }
4245 
4246 LLVMBool LLVMIsMultithreaded() {
4247   return llvm_is_multithreaded();
4248 }
4249