xref: /llvm-project-15.0.7/llvm/lib/IR/Core.cpp (revision ad89cf4e)
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 LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx) {
1449   return wrap(unwrap<ConstantDataSequential>(C)->getElementAsConstant(idx));
1450 }
1451 
1452 LLVMBool LLVMIsConstantString(LLVMValueRef C) {
1453   return unwrap<ConstantDataSequential>(C)->isString();
1454 }
1455 
1456 const char *LLVMGetAsString(LLVMValueRef C, size_t *Length) {
1457   StringRef Str = unwrap<ConstantDataSequential>(C)->getAsString();
1458   *Length = Str.size();
1459   return Str.data();
1460 }
1461 
1462 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
1463                             LLVMValueRef *ConstantVals, unsigned Length) {
1464   ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length);
1465   return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));
1466 }
1467 
1468 LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
1469                                       LLVMValueRef *ConstantVals,
1470                                       unsigned Count, LLVMBool Packed) {
1471   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1472   return wrap(ConstantStruct::getAnon(*unwrap(C), makeArrayRef(Elements, Count),
1473                                       Packed != 0));
1474 }
1475 
1476 LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
1477                              LLVMBool Packed) {
1478   return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count,
1479                                   Packed);
1480 }
1481 
1482 LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
1483                                   LLVMValueRef *ConstantVals,
1484                                   unsigned Count) {
1485   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
1486   StructType *Ty = cast<StructType>(unwrap(StructTy));
1487 
1488   return wrap(ConstantStruct::get(Ty, makeArrayRef(Elements, Count)));
1489 }
1490 
1491 LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) {
1492   return wrap(ConstantVector::get(makeArrayRef(
1493                             unwrap<Constant>(ScalarConstantVals, Size), Size)));
1494 }
1495 
1496 /*-- Opcode mapping */
1497 
1498 static LLVMOpcode map_to_llvmopcode(int opcode)
1499 {
1500     switch (opcode) {
1501       default: llvm_unreachable("Unhandled Opcode.");
1502 #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;
1503 #include "llvm/IR/Instruction.def"
1504 #undef HANDLE_INST
1505     }
1506 }
1507 
1508 static int map_from_llvmopcode(LLVMOpcode code)
1509 {
1510     switch (code) {
1511 #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;
1512 #include "llvm/IR/Instruction.def"
1513 #undef HANDLE_INST
1514     }
1515     llvm_unreachable("Unhandled Opcode.");
1516 }
1517 
1518 /*--.. Constant expressions ................................................--*/
1519 
1520 LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) {
1521   return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode());
1522 }
1523 
1524 LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) {
1525   return wrap(ConstantExpr::getAlignOf(unwrap(Ty)));
1526 }
1527 
1528 LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) {
1529   return wrap(ConstantExpr::getSizeOf(unwrap(Ty)));
1530 }
1531 
1532 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) {
1533   return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));
1534 }
1535 
1536 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) {
1537   return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal)));
1538 }
1539 
1540 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) {
1541   return wrap(ConstantExpr::getNUWNeg(unwrap<Constant>(ConstantVal)));
1542 }
1543 
1544 
1545 LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal) {
1546   return wrap(ConstantExpr::getFNeg(unwrap<Constant>(ConstantVal)));
1547 }
1548 
1549 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) {
1550   return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal)));
1551 }
1552 
1553 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1554   return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant),
1555                                    unwrap<Constant>(RHSConstant)));
1556 }
1557 
1558 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant,
1559                              LLVMValueRef RHSConstant) {
1560   return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant),
1561                                       unwrap<Constant>(RHSConstant)));
1562 }
1563 
1564 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant,
1565                              LLVMValueRef RHSConstant) {
1566   return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant),
1567                                       unwrap<Constant>(RHSConstant)));
1568 }
1569 
1570 LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1571   return wrap(ConstantExpr::getFAdd(unwrap<Constant>(LHSConstant),
1572                                     unwrap<Constant>(RHSConstant)));
1573 }
1574 
1575 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1576   return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant),
1577                                    unwrap<Constant>(RHSConstant)));
1578 }
1579 
1580 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant,
1581                              LLVMValueRef RHSConstant) {
1582   return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant),
1583                                       unwrap<Constant>(RHSConstant)));
1584 }
1585 
1586 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant,
1587                              LLVMValueRef RHSConstant) {
1588   return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant),
1589                                       unwrap<Constant>(RHSConstant)));
1590 }
1591 
1592 LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1593   return wrap(ConstantExpr::getFSub(unwrap<Constant>(LHSConstant),
1594                                     unwrap<Constant>(RHSConstant)));
1595 }
1596 
1597 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1598   return wrap(ConstantExpr::getMul(unwrap<Constant>(LHSConstant),
1599                                    unwrap<Constant>(RHSConstant)));
1600 }
1601 
1602 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant,
1603                              LLVMValueRef RHSConstant) {
1604   return wrap(ConstantExpr::getNSWMul(unwrap<Constant>(LHSConstant),
1605                                       unwrap<Constant>(RHSConstant)));
1606 }
1607 
1608 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant,
1609                              LLVMValueRef RHSConstant) {
1610   return wrap(ConstantExpr::getNUWMul(unwrap<Constant>(LHSConstant),
1611                                       unwrap<Constant>(RHSConstant)));
1612 }
1613 
1614 LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1615   return wrap(ConstantExpr::getFMul(unwrap<Constant>(LHSConstant),
1616                                     unwrap<Constant>(RHSConstant)));
1617 }
1618 
1619 LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1620   return wrap(ConstantExpr::getUDiv(unwrap<Constant>(LHSConstant),
1621                                     unwrap<Constant>(RHSConstant)));
1622 }
1623 
1624 LLVMValueRef LLVMConstExactUDiv(LLVMValueRef LHSConstant,
1625                                 LLVMValueRef RHSConstant) {
1626   return wrap(ConstantExpr::getExactUDiv(unwrap<Constant>(LHSConstant),
1627                                          unwrap<Constant>(RHSConstant)));
1628 }
1629 
1630 LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1631   return wrap(ConstantExpr::getSDiv(unwrap<Constant>(LHSConstant),
1632                                     unwrap<Constant>(RHSConstant)));
1633 }
1634 
1635 LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant,
1636                                 LLVMValueRef RHSConstant) {
1637   return wrap(ConstantExpr::getExactSDiv(unwrap<Constant>(LHSConstant),
1638                                          unwrap<Constant>(RHSConstant)));
1639 }
1640 
1641 LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1642   return wrap(ConstantExpr::getFDiv(unwrap<Constant>(LHSConstant),
1643                                     unwrap<Constant>(RHSConstant)));
1644 }
1645 
1646 LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1647   return wrap(ConstantExpr::getURem(unwrap<Constant>(LHSConstant),
1648                                     unwrap<Constant>(RHSConstant)));
1649 }
1650 
1651 LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1652   return wrap(ConstantExpr::getSRem(unwrap<Constant>(LHSConstant),
1653                                     unwrap<Constant>(RHSConstant)));
1654 }
1655 
1656 LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1657   return wrap(ConstantExpr::getFRem(unwrap<Constant>(LHSConstant),
1658                                     unwrap<Constant>(RHSConstant)));
1659 }
1660 
1661 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1662   return wrap(ConstantExpr::getAnd(unwrap<Constant>(LHSConstant),
1663                                    unwrap<Constant>(RHSConstant)));
1664 }
1665 
1666 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1667   return wrap(ConstantExpr::getOr(unwrap<Constant>(LHSConstant),
1668                                   unwrap<Constant>(RHSConstant)));
1669 }
1670 
1671 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1672   return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant),
1673                                    unwrap<Constant>(RHSConstant)));
1674 }
1675 
1676 LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate,
1677                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1678   return wrap(ConstantExpr::getICmp(Predicate,
1679                                     unwrap<Constant>(LHSConstant),
1680                                     unwrap<Constant>(RHSConstant)));
1681 }
1682 
1683 LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
1684                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1685   return wrap(ConstantExpr::getFCmp(Predicate,
1686                                     unwrap<Constant>(LHSConstant),
1687                                     unwrap<Constant>(RHSConstant)));
1688 }
1689 
1690 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1691   return wrap(ConstantExpr::getShl(unwrap<Constant>(LHSConstant),
1692                                    unwrap<Constant>(RHSConstant)));
1693 }
1694 
1695 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1696   return wrap(ConstantExpr::getLShr(unwrap<Constant>(LHSConstant),
1697                                     unwrap<Constant>(RHSConstant)));
1698 }
1699 
1700 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1701   return wrap(ConstantExpr::getAShr(unwrap<Constant>(LHSConstant),
1702                                     unwrap<Constant>(RHSConstant)));
1703 }
1704 
1705 LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
1706                           LLVMValueRef *ConstantIndices, unsigned NumIndices) {
1707   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1708                                NumIndices);
1709   Constant *Val = unwrap<Constant>(ConstantVal);
1710   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
1711   return wrap(ConstantExpr::getGetElementPtr(Ty, Val, IdxList));
1712 }
1713 
1714 LLVMValueRef LLVMConstGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
1715                            LLVMValueRef *ConstantIndices, unsigned NumIndices) {
1716   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1717                                NumIndices);
1718   Constant *Val = unwrap<Constant>(ConstantVal);
1719   return wrap(ConstantExpr::getGetElementPtr(unwrap(Ty), Val, IdxList));
1720 }
1721 
1722 LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
1723                                   LLVMValueRef *ConstantIndices,
1724                                   unsigned NumIndices) {
1725   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1726                                NumIndices);
1727   Constant *Val = unwrap<Constant>(ConstantVal);
1728   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
1729   return wrap(ConstantExpr::getInBoundsGetElementPtr(Ty, Val, IdxList));
1730 }
1731 
1732 LLVMValueRef LLVMConstInBoundsGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
1733                                    LLVMValueRef *ConstantIndices,
1734                                    unsigned NumIndices) {
1735   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1736                                NumIndices);
1737   Constant *Val = unwrap<Constant>(ConstantVal);
1738   return wrap(ConstantExpr::getInBoundsGetElementPtr(unwrap(Ty), Val, IdxList));
1739 }
1740 
1741 LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1742   return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal),
1743                                      unwrap(ToType)));
1744 }
1745 
1746 LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1747   return wrap(ConstantExpr::getSExt(unwrap<Constant>(ConstantVal),
1748                                     unwrap(ToType)));
1749 }
1750 
1751 LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1752   return wrap(ConstantExpr::getZExt(unwrap<Constant>(ConstantVal),
1753                                     unwrap(ToType)));
1754 }
1755 
1756 LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1757   return wrap(ConstantExpr::getFPTrunc(unwrap<Constant>(ConstantVal),
1758                                        unwrap(ToType)));
1759 }
1760 
1761 LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1762   return wrap(ConstantExpr::getFPExtend(unwrap<Constant>(ConstantVal),
1763                                         unwrap(ToType)));
1764 }
1765 
1766 LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1767   return wrap(ConstantExpr::getUIToFP(unwrap<Constant>(ConstantVal),
1768                                       unwrap(ToType)));
1769 }
1770 
1771 LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1772   return wrap(ConstantExpr::getSIToFP(unwrap<Constant>(ConstantVal),
1773                                       unwrap(ToType)));
1774 }
1775 
1776 LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1777   return wrap(ConstantExpr::getFPToUI(unwrap<Constant>(ConstantVal),
1778                                       unwrap(ToType)));
1779 }
1780 
1781 LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1782   return wrap(ConstantExpr::getFPToSI(unwrap<Constant>(ConstantVal),
1783                                       unwrap(ToType)));
1784 }
1785 
1786 LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1787   return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal),
1788                                         unwrap(ToType)));
1789 }
1790 
1791 LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1792   return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal),
1793                                         unwrap(ToType)));
1794 }
1795 
1796 LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1797   return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal),
1798                                        unwrap(ToType)));
1799 }
1800 
1801 LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal,
1802                                     LLVMTypeRef ToType) {
1803   return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal),
1804                                              unwrap(ToType)));
1805 }
1806 
1807 LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal,
1808                                     LLVMTypeRef ToType) {
1809   return wrap(ConstantExpr::getZExtOrBitCast(unwrap<Constant>(ConstantVal),
1810                                              unwrap(ToType)));
1811 }
1812 
1813 LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal,
1814                                     LLVMTypeRef ToType) {
1815   return wrap(ConstantExpr::getSExtOrBitCast(unwrap<Constant>(ConstantVal),
1816                                              unwrap(ToType)));
1817 }
1818 
1819 LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,
1820                                      LLVMTypeRef ToType) {
1821   return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal),
1822                                               unwrap(ToType)));
1823 }
1824 
1825 LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
1826                                   LLVMTypeRef ToType) {
1827   return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal),
1828                                            unwrap(ToType)));
1829 }
1830 
1831 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
1832                               LLVMBool isSigned) {
1833   return wrap(ConstantExpr::getIntegerCast(unwrap<Constant>(ConstantVal),
1834                                            unwrap(ToType), isSigned));
1835 }
1836 
1837 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1838   return wrap(ConstantExpr::getFPCast(unwrap<Constant>(ConstantVal),
1839                                       unwrap(ToType)));
1840 }
1841 
1842 LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
1843                              LLVMValueRef ConstantIfTrue,
1844                              LLVMValueRef ConstantIfFalse) {
1845   return wrap(ConstantExpr::getSelect(unwrap<Constant>(ConstantCondition),
1846                                       unwrap<Constant>(ConstantIfTrue),
1847                                       unwrap<Constant>(ConstantIfFalse)));
1848 }
1849 
1850 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
1851                                      LLVMValueRef IndexConstant) {
1852   return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant),
1853                                               unwrap<Constant>(IndexConstant)));
1854 }
1855 
1856 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
1857                                     LLVMValueRef ElementValueConstant,
1858                                     LLVMValueRef IndexConstant) {
1859   return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant),
1860                                          unwrap<Constant>(ElementValueConstant),
1861                                              unwrap<Constant>(IndexConstant)));
1862 }
1863 
1864 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
1865                                     LLVMValueRef VectorBConstant,
1866                                     LLVMValueRef MaskConstant) {
1867   SmallVector<int, 16> IntMask;
1868   ShuffleVectorInst::getShuffleMask(unwrap<Constant>(MaskConstant), IntMask);
1869   return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant),
1870                                              unwrap<Constant>(VectorBConstant),
1871                                              IntMask));
1872 }
1873 
1874 LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList,
1875                                    unsigned NumIdx) {
1876   return wrap(ConstantExpr::getExtractValue(unwrap<Constant>(AggConstant),
1877                                             makeArrayRef(IdxList, NumIdx)));
1878 }
1879 
1880 LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant,
1881                                   LLVMValueRef ElementValueConstant,
1882                                   unsigned *IdxList, unsigned NumIdx) {
1883   return wrap(ConstantExpr::getInsertValue(unwrap<Constant>(AggConstant),
1884                                          unwrap<Constant>(ElementValueConstant),
1885                                            makeArrayRef(IdxList, NumIdx)));
1886 }
1887 
1888 LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString,
1889                                 const char *Constraints,
1890                                 LLVMBool HasSideEffects,
1891                                 LLVMBool IsAlignStack) {
1892   return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString,
1893                              Constraints, HasSideEffects, IsAlignStack));
1894 }
1895 
1896 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) {
1897   return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB)));
1898 }
1899 
1900 /*--.. Operations on global variables, functions, and aliases (globals) ....--*/
1901 
1902 LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) {
1903   return wrap(unwrap<GlobalValue>(Global)->getParent());
1904 }
1905 
1906 LLVMBool LLVMIsDeclaration(LLVMValueRef Global) {
1907   return unwrap<GlobalValue>(Global)->isDeclaration();
1908 }
1909 
1910 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {
1911   switch (unwrap<GlobalValue>(Global)->getLinkage()) {
1912   case GlobalValue::ExternalLinkage:
1913     return LLVMExternalLinkage;
1914   case GlobalValue::AvailableExternallyLinkage:
1915     return LLVMAvailableExternallyLinkage;
1916   case GlobalValue::LinkOnceAnyLinkage:
1917     return LLVMLinkOnceAnyLinkage;
1918   case GlobalValue::LinkOnceODRLinkage:
1919     return LLVMLinkOnceODRLinkage;
1920   case GlobalValue::WeakAnyLinkage:
1921     return LLVMWeakAnyLinkage;
1922   case GlobalValue::WeakODRLinkage:
1923     return LLVMWeakODRLinkage;
1924   case GlobalValue::AppendingLinkage:
1925     return LLVMAppendingLinkage;
1926   case GlobalValue::InternalLinkage:
1927     return LLVMInternalLinkage;
1928   case GlobalValue::PrivateLinkage:
1929     return LLVMPrivateLinkage;
1930   case GlobalValue::ExternalWeakLinkage:
1931     return LLVMExternalWeakLinkage;
1932   case GlobalValue::CommonLinkage:
1933     return LLVMCommonLinkage;
1934   }
1935 
1936   llvm_unreachable("Invalid GlobalValue linkage!");
1937 }
1938 
1939 void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {
1940   GlobalValue *GV = unwrap<GlobalValue>(Global);
1941 
1942   switch (Linkage) {
1943   case LLVMExternalLinkage:
1944     GV->setLinkage(GlobalValue::ExternalLinkage);
1945     break;
1946   case LLVMAvailableExternallyLinkage:
1947     GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1948     break;
1949   case LLVMLinkOnceAnyLinkage:
1950     GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
1951     break;
1952   case LLVMLinkOnceODRLinkage:
1953     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
1954     break;
1955   case LLVMLinkOnceODRAutoHideLinkage:
1956     LLVM_DEBUG(
1957         errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no "
1958                   "longer supported.");
1959     break;
1960   case LLVMWeakAnyLinkage:
1961     GV->setLinkage(GlobalValue::WeakAnyLinkage);
1962     break;
1963   case LLVMWeakODRLinkage:
1964     GV->setLinkage(GlobalValue::WeakODRLinkage);
1965     break;
1966   case LLVMAppendingLinkage:
1967     GV->setLinkage(GlobalValue::AppendingLinkage);
1968     break;
1969   case LLVMInternalLinkage:
1970     GV->setLinkage(GlobalValue::InternalLinkage);
1971     break;
1972   case LLVMPrivateLinkage:
1973     GV->setLinkage(GlobalValue::PrivateLinkage);
1974     break;
1975   case LLVMLinkerPrivateLinkage:
1976     GV->setLinkage(GlobalValue::PrivateLinkage);
1977     break;
1978   case LLVMLinkerPrivateWeakLinkage:
1979     GV->setLinkage(GlobalValue::PrivateLinkage);
1980     break;
1981   case LLVMDLLImportLinkage:
1982     LLVM_DEBUG(
1983         errs()
1984         << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported.");
1985     break;
1986   case LLVMDLLExportLinkage:
1987     LLVM_DEBUG(
1988         errs()
1989         << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported.");
1990     break;
1991   case LLVMExternalWeakLinkage:
1992     GV->setLinkage(GlobalValue::ExternalWeakLinkage);
1993     break;
1994   case LLVMGhostLinkage:
1995     LLVM_DEBUG(
1996         errs() << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");
1997     break;
1998   case LLVMCommonLinkage:
1999     GV->setLinkage(GlobalValue::CommonLinkage);
2000     break;
2001   }
2002 }
2003 
2004 const char *LLVMGetSection(LLVMValueRef Global) {
2005   // Using .data() is safe because of how GlobalObject::setSection is
2006   // implemented.
2007   return unwrap<GlobalValue>(Global)->getSection().data();
2008 }
2009 
2010 void LLVMSetSection(LLVMValueRef Global, const char *Section) {
2011   unwrap<GlobalObject>(Global)->setSection(Section);
2012 }
2013 
2014 LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) {
2015   return static_cast<LLVMVisibility>(
2016     unwrap<GlobalValue>(Global)->getVisibility());
2017 }
2018 
2019 void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) {
2020   unwrap<GlobalValue>(Global)
2021     ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz));
2022 }
2023 
2024 LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) {
2025   return static_cast<LLVMDLLStorageClass>(
2026       unwrap<GlobalValue>(Global)->getDLLStorageClass());
2027 }
2028 
2029 void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) {
2030   unwrap<GlobalValue>(Global)->setDLLStorageClass(
2031       static_cast<GlobalValue::DLLStorageClassTypes>(Class));
2032 }
2033 
2034 LLVMUnnamedAddr LLVMGetUnnamedAddress(LLVMValueRef Global) {
2035   switch (unwrap<GlobalValue>(Global)->getUnnamedAddr()) {
2036   case GlobalVariable::UnnamedAddr::None:
2037     return LLVMNoUnnamedAddr;
2038   case GlobalVariable::UnnamedAddr::Local:
2039     return LLVMLocalUnnamedAddr;
2040   case GlobalVariable::UnnamedAddr::Global:
2041     return LLVMGlobalUnnamedAddr;
2042   }
2043   llvm_unreachable("Unknown UnnamedAddr kind!");
2044 }
2045 
2046 void LLVMSetUnnamedAddress(LLVMValueRef Global, LLVMUnnamedAddr UnnamedAddr) {
2047   GlobalValue *GV = unwrap<GlobalValue>(Global);
2048 
2049   switch (UnnamedAddr) {
2050   case LLVMNoUnnamedAddr:
2051     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::None);
2052   case LLVMLocalUnnamedAddr:
2053     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Local);
2054   case LLVMGlobalUnnamedAddr:
2055     return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Global);
2056   }
2057 }
2058 
2059 LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) {
2060   return unwrap<GlobalValue>(Global)->hasGlobalUnnamedAddr();
2061 }
2062 
2063 void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) {
2064   unwrap<GlobalValue>(Global)->setUnnamedAddr(
2065       HasUnnamedAddr ? GlobalValue::UnnamedAddr::Global
2066                      : GlobalValue::UnnamedAddr::None);
2067 }
2068 
2069 LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef Global) {
2070   return wrap(unwrap<GlobalValue>(Global)->getValueType());
2071 }
2072 
2073 /*--.. Operations on global variables, load and store instructions .........--*/
2074 
2075 unsigned LLVMGetAlignment(LLVMValueRef V) {
2076   Value *P = unwrap<Value>(V);
2077   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
2078     return GV->getAlignment();
2079   if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
2080     return AI->getAlignment();
2081   if (LoadInst *LI = dyn_cast<LoadInst>(P))
2082     return LI->getAlignment();
2083   if (StoreInst *SI = dyn_cast<StoreInst>(P))
2084     return SI->getAlignment();
2085   if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))
2086     return RMWI->getAlign().value();
2087   if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))
2088     return CXI->getAlign().value();
2089 
2090   llvm_unreachable(
2091       "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, "
2092       "and AtomicCmpXchgInst have alignment");
2093 }
2094 
2095 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) {
2096   Value *P = unwrap<Value>(V);
2097   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
2098     GV->setAlignment(MaybeAlign(Bytes));
2099   else if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
2100     AI->setAlignment(Align(Bytes));
2101   else if (LoadInst *LI = dyn_cast<LoadInst>(P))
2102     LI->setAlignment(Align(Bytes));
2103   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
2104     SI->setAlignment(Align(Bytes));
2105   else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))
2106     RMWI->setAlignment(Align(Bytes));
2107   else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))
2108     CXI->setAlignment(Align(Bytes));
2109   else
2110     llvm_unreachable(
2111         "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, and "
2112         "and AtomicCmpXchgInst have alignment");
2113 }
2114 
2115 LLVMValueMetadataEntry *LLVMGlobalCopyAllMetadata(LLVMValueRef Value,
2116                                                   size_t *NumEntries) {
2117   return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {
2118     Entries.clear();
2119     if (Instruction *Instr = dyn_cast<Instruction>(unwrap(Value))) {
2120       Instr->getAllMetadata(Entries);
2121     } else {
2122       unwrap<GlobalObject>(Value)->getAllMetadata(Entries);
2123     }
2124   });
2125 }
2126 
2127 unsigned LLVMValueMetadataEntriesGetKind(LLVMValueMetadataEntry *Entries,
2128                                          unsigned Index) {
2129   LLVMOpaqueValueMetadataEntry MVE =
2130       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2131   return MVE.Kind;
2132 }
2133 
2134 LLVMMetadataRef
2135 LLVMValueMetadataEntriesGetMetadata(LLVMValueMetadataEntry *Entries,
2136                                     unsigned Index) {
2137   LLVMOpaqueValueMetadataEntry MVE =
2138       static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);
2139   return MVE.Metadata;
2140 }
2141 
2142 void LLVMDisposeValueMetadataEntries(LLVMValueMetadataEntry *Entries) {
2143   free(Entries);
2144 }
2145 
2146 void LLVMGlobalSetMetadata(LLVMValueRef Global, unsigned Kind,
2147                            LLVMMetadataRef MD) {
2148   unwrap<GlobalObject>(Global)->setMetadata(Kind, unwrap<MDNode>(MD));
2149 }
2150 
2151 void LLVMGlobalEraseMetadata(LLVMValueRef Global, unsigned Kind) {
2152   unwrap<GlobalObject>(Global)->eraseMetadata(Kind);
2153 }
2154 
2155 void LLVMGlobalClearMetadata(LLVMValueRef Global) {
2156   unwrap<GlobalObject>(Global)->clearMetadata();
2157 }
2158 
2159 /*--.. Operations on global variables ......................................--*/
2160 
2161 LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) {
2162   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2163                                  GlobalValue::ExternalLinkage, nullptr, Name));
2164 }
2165 
2166 LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
2167                                          const char *Name,
2168                                          unsigned AddressSpace) {
2169   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
2170                                  GlobalValue::ExternalLinkage, nullptr, Name,
2171                                  nullptr, GlobalVariable::NotThreadLocal,
2172                                  AddressSpace));
2173 }
2174 
2175 LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) {
2176   return wrap(unwrap(M)->getNamedGlobal(Name));
2177 }
2178 
2179 LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) {
2180   Module *Mod = unwrap(M);
2181   Module::global_iterator I = Mod->global_begin();
2182   if (I == Mod->global_end())
2183     return nullptr;
2184   return wrap(&*I);
2185 }
2186 
2187 LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
2188   Module *Mod = unwrap(M);
2189   Module::global_iterator I = Mod->global_end();
2190   if (I == Mod->global_begin())
2191     return nullptr;
2192   return wrap(&*--I);
2193 }
2194 
2195 LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
2196   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2197   Module::global_iterator I(GV);
2198   if (++I == GV->getParent()->global_end())
2199     return nullptr;
2200   return wrap(&*I);
2201 }
2202 
2203 LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
2204   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2205   Module::global_iterator I(GV);
2206   if (I == GV->getParent()->global_begin())
2207     return nullptr;
2208   return wrap(&*--I);
2209 }
2210 
2211 void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
2212   unwrap<GlobalVariable>(GlobalVar)->eraseFromParent();
2213 }
2214 
2215 LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
2216   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
2217   if ( !GV->hasInitializer() )
2218     return nullptr;
2219   return wrap(GV->getInitializer());
2220 }
2221 
2222 void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) {
2223   unwrap<GlobalVariable>(GlobalVar)
2224     ->setInitializer(unwrap<Constant>(ConstantVal));
2225 }
2226 
2227 LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) {
2228   return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal();
2229 }
2230 
2231 void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) {
2232   unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0);
2233 }
2234 
2235 LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) {
2236   return unwrap<GlobalVariable>(GlobalVar)->isConstant();
2237 }
2238 
2239 void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) {
2240   unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0);
2241 }
2242 
2243 LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) {
2244   switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) {
2245   case GlobalVariable::NotThreadLocal:
2246     return LLVMNotThreadLocal;
2247   case GlobalVariable::GeneralDynamicTLSModel:
2248     return LLVMGeneralDynamicTLSModel;
2249   case GlobalVariable::LocalDynamicTLSModel:
2250     return LLVMLocalDynamicTLSModel;
2251   case GlobalVariable::InitialExecTLSModel:
2252     return LLVMInitialExecTLSModel;
2253   case GlobalVariable::LocalExecTLSModel:
2254     return LLVMLocalExecTLSModel;
2255   }
2256 
2257   llvm_unreachable("Invalid GlobalVariable thread local mode");
2258 }
2259 
2260 void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) {
2261   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
2262 
2263   switch (Mode) {
2264   case LLVMNotThreadLocal:
2265     GV->setThreadLocalMode(GlobalVariable::NotThreadLocal);
2266     break;
2267   case LLVMGeneralDynamicTLSModel:
2268     GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel);
2269     break;
2270   case LLVMLocalDynamicTLSModel:
2271     GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel);
2272     break;
2273   case LLVMInitialExecTLSModel:
2274     GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
2275     break;
2276   case LLVMLocalExecTLSModel:
2277     GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel);
2278     break;
2279   }
2280 }
2281 
2282 LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) {
2283   return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized();
2284 }
2285 
2286 void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) {
2287   unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit);
2288 }
2289 
2290 /*--.. Operations on aliases ......................................--*/
2291 
2292 LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
2293                           const char *Name) {
2294   auto *PTy = cast<PointerType>(unwrap(Ty));
2295   return wrap(GlobalAlias::create(PTy->getNonOpaquePointerElementType(),
2296                                   PTy->getAddressSpace(),
2297                                   GlobalValue::ExternalLinkage, Name,
2298                                   unwrap<Constant>(Aliasee), unwrap(M)));
2299 }
2300 
2301 LLVMValueRef LLVMAddAlias2(LLVMModuleRef M, LLVMTypeRef ValueTy,
2302                            unsigned AddrSpace, LLVMValueRef Aliasee,
2303                            const char *Name) {
2304   return wrap(GlobalAlias::create(unwrap(ValueTy), AddrSpace,
2305                                   GlobalValue::ExternalLinkage, Name,
2306                                   unwrap<Constant>(Aliasee), unwrap(M)));
2307 }
2308 
2309 LLVMValueRef LLVMGetNamedGlobalAlias(LLVMModuleRef M,
2310                                      const char *Name, size_t NameLen) {
2311   return wrap(unwrap(M)->getNamedAlias(StringRef(Name, NameLen)));
2312 }
2313 
2314 LLVMValueRef LLVMGetFirstGlobalAlias(LLVMModuleRef M) {
2315   Module *Mod = unwrap(M);
2316   Module::alias_iterator I = Mod->alias_begin();
2317   if (I == Mod->alias_end())
2318     return nullptr;
2319   return wrap(&*I);
2320 }
2321 
2322 LLVMValueRef LLVMGetLastGlobalAlias(LLVMModuleRef M) {
2323   Module *Mod = unwrap(M);
2324   Module::alias_iterator I = Mod->alias_end();
2325   if (I == Mod->alias_begin())
2326     return nullptr;
2327   return wrap(&*--I);
2328 }
2329 
2330 LLVMValueRef LLVMGetNextGlobalAlias(LLVMValueRef GA) {
2331   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2332   Module::alias_iterator I(Alias);
2333   if (++I == Alias->getParent()->alias_end())
2334     return nullptr;
2335   return wrap(&*I);
2336 }
2337 
2338 LLVMValueRef LLVMGetPreviousGlobalAlias(LLVMValueRef GA) {
2339   GlobalAlias *Alias = unwrap<GlobalAlias>(GA);
2340   Module::alias_iterator I(Alias);
2341   if (I == Alias->getParent()->alias_begin())
2342     return nullptr;
2343   return wrap(&*--I);
2344 }
2345 
2346 LLVMValueRef LLVMAliasGetAliasee(LLVMValueRef Alias) {
2347   return wrap(unwrap<GlobalAlias>(Alias)->getAliasee());
2348 }
2349 
2350 void LLVMAliasSetAliasee(LLVMValueRef Alias, LLVMValueRef Aliasee) {
2351   unwrap<GlobalAlias>(Alias)->setAliasee(unwrap<Constant>(Aliasee));
2352 }
2353 
2354 /*--.. Operations on functions .............................................--*/
2355 
2356 LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
2357                              LLVMTypeRef FunctionTy) {
2358   return wrap(Function::Create(unwrap<FunctionType>(FunctionTy),
2359                                GlobalValue::ExternalLinkage, Name, unwrap(M)));
2360 }
2361 
2362 LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) {
2363   return wrap(unwrap(M)->getFunction(Name));
2364 }
2365 
2366 LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) {
2367   Module *Mod = unwrap(M);
2368   Module::iterator I = Mod->begin();
2369   if (I == Mod->end())
2370     return nullptr;
2371   return wrap(&*I);
2372 }
2373 
2374 LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
2375   Module *Mod = unwrap(M);
2376   Module::iterator I = Mod->end();
2377   if (I == Mod->begin())
2378     return nullptr;
2379   return wrap(&*--I);
2380 }
2381 
2382 LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
2383   Function *Func = unwrap<Function>(Fn);
2384   Module::iterator I(Func);
2385   if (++I == Func->getParent()->end())
2386     return nullptr;
2387   return wrap(&*I);
2388 }
2389 
2390 LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
2391   Function *Func = unwrap<Function>(Fn);
2392   Module::iterator I(Func);
2393   if (I == Func->getParent()->begin())
2394     return nullptr;
2395   return wrap(&*--I);
2396 }
2397 
2398 void LLVMDeleteFunction(LLVMValueRef Fn) {
2399   unwrap<Function>(Fn)->eraseFromParent();
2400 }
2401 
2402 LLVMBool LLVMHasPersonalityFn(LLVMValueRef Fn) {
2403   return unwrap<Function>(Fn)->hasPersonalityFn();
2404 }
2405 
2406 LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn) {
2407   return wrap(unwrap<Function>(Fn)->getPersonalityFn());
2408 }
2409 
2410 void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn) {
2411   unwrap<Function>(Fn)->setPersonalityFn(unwrap<Constant>(PersonalityFn));
2412 }
2413 
2414 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
2415   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
2416     return F->getIntrinsicID();
2417   return 0;
2418 }
2419 
2420 static Intrinsic::ID llvm_map_to_intrinsic_id(unsigned ID) {
2421   assert(ID < llvm::Intrinsic::num_intrinsics && "Intrinsic ID out of range");
2422   return llvm::Intrinsic::ID(ID);
2423 }
2424 
2425 LLVMValueRef LLVMGetIntrinsicDeclaration(LLVMModuleRef Mod,
2426                                          unsigned ID,
2427                                          LLVMTypeRef *ParamTypes,
2428                                          size_t ParamCount) {
2429   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2430   auto IID = llvm_map_to_intrinsic_id(ID);
2431   return wrap(llvm::Intrinsic::getDeclaration(unwrap(Mod), IID, Tys));
2432 }
2433 
2434 const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength) {
2435   auto IID = llvm_map_to_intrinsic_id(ID);
2436   auto Str = llvm::Intrinsic::getName(IID);
2437   *NameLength = Str.size();
2438   return Str.data();
2439 }
2440 
2441 LLVMTypeRef LLVMIntrinsicGetType(LLVMContextRef Ctx, unsigned ID,
2442                                  LLVMTypeRef *ParamTypes, size_t ParamCount) {
2443   auto IID = llvm_map_to_intrinsic_id(ID);
2444   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2445   return wrap(llvm::Intrinsic::getType(*unwrap(Ctx), IID, Tys));
2446 }
2447 
2448 const char *LLVMIntrinsicCopyOverloadedName(unsigned ID,
2449                                             LLVMTypeRef *ParamTypes,
2450                                             size_t ParamCount,
2451                                             size_t *NameLength) {
2452   auto IID = llvm_map_to_intrinsic_id(ID);
2453   ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);
2454   auto Str = llvm::Intrinsic::getNameNoUnnamedTypes(IID, Tys);
2455   *NameLength = Str.length();
2456   return strdup(Str.c_str());
2457 }
2458 
2459 const char *LLVMIntrinsicCopyOverloadedName2(LLVMModuleRef Mod, unsigned ID,
2460                                              LLVMTypeRef *ParamTypes,
2461                                              size_t ParamCount,
2462                                              size_t *NameLength) {
2463   auto IID = llvm_map_to_intrinsic_id(ID);
2464   ArrayRef<Type *> Tys(unwrap(ParamTypes), ParamCount);
2465   auto Str = llvm::Intrinsic::getName(IID, Tys, unwrap(Mod));
2466   *NameLength = Str.length();
2467   return strdup(Str.c_str());
2468 }
2469 
2470 unsigned LLVMLookupIntrinsicID(const char *Name, size_t NameLen) {
2471   return Function::lookupIntrinsicID({Name, NameLen});
2472 }
2473 
2474 LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID) {
2475   auto IID = llvm_map_to_intrinsic_id(ID);
2476   return llvm::Intrinsic::isOverloaded(IID);
2477 }
2478 
2479 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {
2480   return unwrap<Function>(Fn)->getCallingConv();
2481 }
2482 
2483 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) {
2484   return unwrap<Function>(Fn)->setCallingConv(
2485     static_cast<CallingConv::ID>(CC));
2486 }
2487 
2488 const char *LLVMGetGC(LLVMValueRef Fn) {
2489   Function *F = unwrap<Function>(Fn);
2490   return F->hasGC()? F->getGC().c_str() : nullptr;
2491 }
2492 
2493 void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
2494   Function *F = unwrap<Function>(Fn);
2495   if (GC)
2496     F->setGC(GC);
2497   else
2498     F->clearGC();
2499 }
2500 
2501 void LLVMAddAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2502                              LLVMAttributeRef A) {
2503   unwrap<Function>(F)->addAttributeAtIndex(Idx, unwrap(A));
2504 }
2505 
2506 unsigned LLVMGetAttributeCountAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx) {
2507   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2508   return AS.getNumAttributes();
2509 }
2510 
2511 void LLVMGetAttributesAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2512                               LLVMAttributeRef *Attrs) {
2513   auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);
2514   for (auto A : AS)
2515     *Attrs++ = wrap(A);
2516 }
2517 
2518 LLVMAttributeRef LLVMGetEnumAttributeAtIndex(LLVMValueRef F,
2519                                              LLVMAttributeIndex Idx,
2520                                              unsigned KindID) {
2521   return wrap(unwrap<Function>(F)->getAttributeAtIndex(
2522       Idx, (Attribute::AttrKind)KindID));
2523 }
2524 
2525 LLVMAttributeRef LLVMGetStringAttributeAtIndex(LLVMValueRef F,
2526                                                LLVMAttributeIndex Idx,
2527                                                const char *K, unsigned KLen) {
2528   return wrap(
2529       unwrap<Function>(F)->getAttributeAtIndex(Idx, StringRef(K, KLen)));
2530 }
2531 
2532 void LLVMRemoveEnumAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2533                                     unsigned KindID) {
2534   unwrap<Function>(F)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);
2535 }
2536 
2537 void LLVMRemoveStringAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,
2538                                       const char *K, unsigned KLen) {
2539   unwrap<Function>(F)->removeAttributeAtIndex(Idx, StringRef(K, KLen));
2540 }
2541 
2542 void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A,
2543                                         const char *V) {
2544   Function *Func = unwrap<Function>(Fn);
2545   Attribute Attr = Attribute::get(Func->getContext(), A, V);
2546   Func->addFnAttr(Attr);
2547 }
2548 
2549 /*--.. Operations on parameters ............................................--*/
2550 
2551 unsigned LLVMCountParams(LLVMValueRef FnRef) {
2552   // This function is strictly redundant to
2553   //   LLVMCountParamTypes(LLVMGetElementType(LLVMTypeOf(FnRef)))
2554   return unwrap<Function>(FnRef)->arg_size();
2555 }
2556 
2557 void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) {
2558   Function *Fn = unwrap<Function>(FnRef);
2559   for (Argument &A : Fn->args())
2560     *ParamRefs++ = wrap(&A);
2561 }
2562 
2563 LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
2564   Function *Fn = unwrap<Function>(FnRef);
2565   return wrap(&Fn->arg_begin()[index]);
2566 }
2567 
2568 LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
2569   return wrap(unwrap<Argument>(V)->getParent());
2570 }
2571 
2572 LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) {
2573   Function *Func = unwrap<Function>(Fn);
2574   Function::arg_iterator I = Func->arg_begin();
2575   if (I == Func->arg_end())
2576     return nullptr;
2577   return wrap(&*I);
2578 }
2579 
2580 LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
2581   Function *Func = unwrap<Function>(Fn);
2582   Function::arg_iterator I = Func->arg_end();
2583   if (I == Func->arg_begin())
2584     return nullptr;
2585   return wrap(&*--I);
2586 }
2587 
2588 LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
2589   Argument *A = unwrap<Argument>(Arg);
2590   Function *Fn = A->getParent();
2591   if (A->getArgNo() + 1 >= Fn->arg_size())
2592     return nullptr;
2593   return wrap(&Fn->arg_begin()[A->getArgNo() + 1]);
2594 }
2595 
2596 LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
2597   Argument *A = unwrap<Argument>(Arg);
2598   if (A->getArgNo() == 0)
2599     return nullptr;
2600   return wrap(&A->getParent()->arg_begin()[A->getArgNo() - 1]);
2601 }
2602 
2603 void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) {
2604   Argument *A = unwrap<Argument>(Arg);
2605   A->addAttr(Attribute::getWithAlignment(A->getContext(), Align(align)));
2606 }
2607 
2608 /*--.. Operations on ifuncs ................................................--*/
2609 
2610 LLVMValueRef LLVMAddGlobalIFunc(LLVMModuleRef M,
2611                                 const char *Name, size_t NameLen,
2612                                 LLVMTypeRef Ty, unsigned AddrSpace,
2613                                 LLVMValueRef Resolver) {
2614   return wrap(GlobalIFunc::create(unwrap(Ty), AddrSpace,
2615                                   GlobalValue::ExternalLinkage,
2616                                   StringRef(Name, NameLen),
2617                                   unwrap<Constant>(Resolver), unwrap(M)));
2618 }
2619 
2620 LLVMValueRef LLVMGetNamedGlobalIFunc(LLVMModuleRef M,
2621                                      const char *Name, size_t NameLen) {
2622   return wrap(unwrap(M)->getNamedIFunc(StringRef(Name, NameLen)));
2623 }
2624 
2625 LLVMValueRef LLVMGetFirstGlobalIFunc(LLVMModuleRef M) {
2626   Module *Mod = unwrap(M);
2627   Module::ifunc_iterator I = Mod->ifunc_begin();
2628   if (I == Mod->ifunc_end())
2629     return nullptr;
2630   return wrap(&*I);
2631 }
2632 
2633 LLVMValueRef LLVMGetLastGlobalIFunc(LLVMModuleRef M) {
2634   Module *Mod = unwrap(M);
2635   Module::ifunc_iterator I = Mod->ifunc_end();
2636   if (I == Mod->ifunc_begin())
2637     return nullptr;
2638   return wrap(&*--I);
2639 }
2640 
2641 LLVMValueRef LLVMGetNextGlobalIFunc(LLVMValueRef IFunc) {
2642   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2643   Module::ifunc_iterator I(GIF);
2644   if (++I == GIF->getParent()->ifunc_end())
2645     return nullptr;
2646   return wrap(&*I);
2647 }
2648 
2649 LLVMValueRef LLVMGetPreviousGlobalIFunc(LLVMValueRef IFunc) {
2650   GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);
2651   Module::ifunc_iterator I(GIF);
2652   if (I == GIF->getParent()->ifunc_begin())
2653     return nullptr;
2654   return wrap(&*--I);
2655 }
2656 
2657 LLVMValueRef LLVMGetGlobalIFuncResolver(LLVMValueRef IFunc) {
2658   return wrap(unwrap<GlobalIFunc>(IFunc)->getResolver());
2659 }
2660 
2661 void LLVMSetGlobalIFuncResolver(LLVMValueRef IFunc, LLVMValueRef Resolver) {
2662   unwrap<GlobalIFunc>(IFunc)->setResolver(unwrap<Constant>(Resolver));
2663 }
2664 
2665 void LLVMEraseGlobalIFunc(LLVMValueRef IFunc) {
2666   unwrap<GlobalIFunc>(IFunc)->eraseFromParent();
2667 }
2668 
2669 void LLVMRemoveGlobalIFunc(LLVMValueRef IFunc) {
2670   unwrap<GlobalIFunc>(IFunc)->removeFromParent();
2671 }
2672 
2673 /*--.. Operations on basic blocks ..........................................--*/
2674 
2675 LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) {
2676   return wrap(static_cast<Value*>(unwrap(BB)));
2677 }
2678 
2679 LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) {
2680   return isa<BasicBlock>(unwrap(Val));
2681 }
2682 
2683 LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) {
2684   return wrap(unwrap<BasicBlock>(Val));
2685 }
2686 
2687 const char *LLVMGetBasicBlockName(LLVMBasicBlockRef BB) {
2688   return unwrap(BB)->getName().data();
2689 }
2690 
2691 LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) {
2692   return wrap(unwrap(BB)->getParent());
2693 }
2694 
2695 LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) {
2696   return wrap(unwrap(BB)->getTerminator());
2697 }
2698 
2699 unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) {
2700   return unwrap<Function>(FnRef)->size();
2701 }
2702 
2703 void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
2704   Function *Fn = unwrap<Function>(FnRef);
2705   for (BasicBlock &BB : *Fn)
2706     *BasicBlocksRefs++ = wrap(&BB);
2707 }
2708 
2709 LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
2710   return wrap(&unwrap<Function>(Fn)->getEntryBlock());
2711 }
2712 
2713 LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) {
2714   Function *Func = unwrap<Function>(Fn);
2715   Function::iterator I = Func->begin();
2716   if (I == Func->end())
2717     return nullptr;
2718   return wrap(&*I);
2719 }
2720 
2721 LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
2722   Function *Func = unwrap<Function>(Fn);
2723   Function::iterator I = Func->end();
2724   if (I == Func->begin())
2725     return nullptr;
2726   return wrap(&*--I);
2727 }
2728 
2729 LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
2730   BasicBlock *Block = unwrap(BB);
2731   Function::iterator I(Block);
2732   if (++I == Block->getParent()->end())
2733     return nullptr;
2734   return wrap(&*I);
2735 }
2736 
2737 LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
2738   BasicBlock *Block = unwrap(BB);
2739   Function::iterator I(Block);
2740   if (I == Block->getParent()->begin())
2741     return nullptr;
2742   return wrap(&*--I);
2743 }
2744 
2745 LLVMBasicBlockRef LLVMCreateBasicBlockInContext(LLVMContextRef C,
2746                                                 const char *Name) {
2747   return wrap(llvm::BasicBlock::Create(*unwrap(C), Name));
2748 }
2749 
2750 void LLVMInsertExistingBasicBlockAfterInsertBlock(LLVMBuilderRef Builder,
2751                                                   LLVMBasicBlockRef BB) {
2752   BasicBlock *ToInsert = unwrap(BB);
2753   BasicBlock *CurBB = unwrap(Builder)->GetInsertBlock();
2754   assert(CurBB && "current insertion point is invalid!");
2755   CurBB->getParent()->getBasicBlockList().insertAfter(CurBB->getIterator(),
2756                                                       ToInsert);
2757 }
2758 
2759 void LLVMAppendExistingBasicBlock(LLVMValueRef Fn,
2760                                   LLVMBasicBlockRef BB) {
2761   unwrap<Function>(Fn)->getBasicBlockList().push_back(unwrap(BB));
2762 }
2763 
2764 LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
2765                                                 LLVMValueRef FnRef,
2766                                                 const char *Name) {
2767   return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef)));
2768 }
2769 
2770 LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) {
2771   return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name);
2772 }
2773 
2774 LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
2775                                                 LLVMBasicBlockRef BBRef,
2776                                                 const char *Name) {
2777   BasicBlock *BB = unwrap(BBRef);
2778   return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB));
2779 }
2780 
2781 LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef,
2782                                        const char *Name) {
2783   return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name);
2784 }
2785 
2786 void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) {
2787   unwrap(BBRef)->eraseFromParent();
2788 }
2789 
2790 void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) {
2791   unwrap(BBRef)->removeFromParent();
2792 }
2793 
2794 void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2795   unwrap(BB)->moveBefore(unwrap(MovePos));
2796 }
2797 
2798 void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
2799   unwrap(BB)->moveAfter(unwrap(MovePos));
2800 }
2801 
2802 /*--.. Operations on instructions ..........................................--*/
2803 
2804 LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) {
2805   return wrap(unwrap<Instruction>(Inst)->getParent());
2806 }
2807 
2808 LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) {
2809   BasicBlock *Block = unwrap(BB);
2810   BasicBlock::iterator I = Block->begin();
2811   if (I == Block->end())
2812     return nullptr;
2813   return wrap(&*I);
2814 }
2815 
2816 LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
2817   BasicBlock *Block = unwrap(BB);
2818   BasicBlock::iterator I = Block->end();
2819   if (I == Block->begin())
2820     return nullptr;
2821   return wrap(&*--I);
2822 }
2823 
2824 LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
2825   Instruction *Instr = unwrap<Instruction>(Inst);
2826   BasicBlock::iterator I(Instr);
2827   if (++I == Instr->getParent()->end())
2828     return nullptr;
2829   return wrap(&*I);
2830 }
2831 
2832 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
2833   Instruction *Instr = unwrap<Instruction>(Inst);
2834   BasicBlock::iterator I(Instr);
2835   if (I == Instr->getParent()->begin())
2836     return nullptr;
2837   return wrap(&*--I);
2838 }
2839 
2840 void LLVMInstructionRemoveFromParent(LLVMValueRef Inst) {
2841   unwrap<Instruction>(Inst)->removeFromParent();
2842 }
2843 
2844 void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
2845   unwrap<Instruction>(Inst)->eraseFromParent();
2846 }
2847 
2848 LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) {
2849   if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst)))
2850     return (LLVMIntPredicate)I->getPredicate();
2851   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2852     if (CE->getOpcode() == Instruction::ICmp)
2853       return (LLVMIntPredicate)CE->getPredicate();
2854   return (LLVMIntPredicate)0;
2855 }
2856 
2857 LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) {
2858   if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst)))
2859     return (LLVMRealPredicate)I->getPredicate();
2860   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
2861     if (CE->getOpcode() == Instruction::FCmp)
2862       return (LLVMRealPredicate)CE->getPredicate();
2863   return (LLVMRealPredicate)0;
2864 }
2865 
2866 LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) {
2867   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2868     return map_to_llvmopcode(C->getOpcode());
2869   return (LLVMOpcode)0;
2870 }
2871 
2872 LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) {
2873   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2874     return wrap(C->clone());
2875   return nullptr;
2876 }
2877 
2878 LLVMValueRef LLVMIsATerminatorInst(LLVMValueRef Inst) {
2879   Instruction *I = dyn_cast<Instruction>(unwrap(Inst));
2880   return (I && I->isTerminator()) ? wrap(I) : nullptr;
2881 }
2882 
2883 unsigned LLVMGetNumArgOperands(LLVMValueRef Instr) {
2884   if (FuncletPadInst *FPI = dyn_cast<FuncletPadInst>(unwrap(Instr))) {
2885     return FPI->getNumArgOperands();
2886   }
2887   return unwrap<CallBase>(Instr)->arg_size();
2888 }
2889 
2890 /*--.. Call and invoke instructions ........................................--*/
2891 
2892 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) {
2893   return unwrap<CallBase>(Instr)->getCallingConv();
2894 }
2895 
2896 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {
2897   return unwrap<CallBase>(Instr)->setCallingConv(
2898       static_cast<CallingConv::ID>(CC));
2899 }
2900 
2901 void LLVMSetInstrParamAlignment(LLVMValueRef Instr, LLVMAttributeIndex Idx,
2902                                 unsigned align) {
2903   auto *Call = unwrap<CallBase>(Instr);
2904   Attribute AlignAttr =
2905       Attribute::getWithAlignment(Call->getContext(), Align(align));
2906   Call->addAttributeAtIndex(Idx, AlignAttr);
2907 }
2908 
2909 void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2910                               LLVMAttributeRef A) {
2911   unwrap<CallBase>(C)->addAttributeAtIndex(Idx, unwrap(A));
2912 }
2913 
2914 unsigned LLVMGetCallSiteAttributeCount(LLVMValueRef C,
2915                                        LLVMAttributeIndex Idx) {
2916   auto *Call = unwrap<CallBase>(C);
2917   auto AS = Call->getAttributes().getAttributes(Idx);
2918   return AS.getNumAttributes();
2919 }
2920 
2921 void LLVMGetCallSiteAttributes(LLVMValueRef C, LLVMAttributeIndex Idx,
2922                                LLVMAttributeRef *Attrs) {
2923   auto *Call = unwrap<CallBase>(C);
2924   auto AS = Call->getAttributes().getAttributes(Idx);
2925   for (auto A : AS)
2926     *Attrs++ = wrap(A);
2927 }
2928 
2929 LLVMAttributeRef LLVMGetCallSiteEnumAttribute(LLVMValueRef C,
2930                                               LLVMAttributeIndex Idx,
2931                                               unsigned KindID) {
2932   return wrap(unwrap<CallBase>(C)->getAttributeAtIndex(
2933       Idx, (Attribute::AttrKind)KindID));
2934 }
2935 
2936 LLVMAttributeRef LLVMGetCallSiteStringAttribute(LLVMValueRef C,
2937                                                 LLVMAttributeIndex Idx,
2938                                                 const char *K, unsigned KLen) {
2939   return wrap(
2940       unwrap<CallBase>(C)->getAttributeAtIndex(Idx, StringRef(K, KLen)));
2941 }
2942 
2943 void LLVMRemoveCallSiteEnumAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2944                                      unsigned KindID) {
2945   unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);
2946 }
2947 
2948 void LLVMRemoveCallSiteStringAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
2949                                        const char *K, unsigned KLen) {
2950   unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, StringRef(K, KLen));
2951 }
2952 
2953 LLVMValueRef LLVMGetCalledValue(LLVMValueRef Instr) {
2954   return wrap(unwrap<CallBase>(Instr)->getCalledOperand());
2955 }
2956 
2957 LLVMTypeRef LLVMGetCalledFunctionType(LLVMValueRef Instr) {
2958   return wrap(unwrap<CallBase>(Instr)->getFunctionType());
2959 }
2960 
2961 /*--.. Operations on call instructions (only) ..............................--*/
2962 
2963 LLVMBool LLVMIsTailCall(LLVMValueRef Call) {
2964   return unwrap<CallInst>(Call)->isTailCall();
2965 }
2966 
2967 void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) {
2968   unwrap<CallInst>(Call)->setTailCall(isTailCall);
2969 }
2970 
2971 /*--.. Operations on invoke instructions (only) ............................--*/
2972 
2973 LLVMBasicBlockRef LLVMGetNormalDest(LLVMValueRef Invoke) {
2974   return wrap(unwrap<InvokeInst>(Invoke)->getNormalDest());
2975 }
2976 
2977 LLVMBasicBlockRef LLVMGetUnwindDest(LLVMValueRef Invoke) {
2978   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2979     return wrap(CRI->getUnwindDest());
2980   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2981     return wrap(CSI->getUnwindDest());
2982   }
2983   return wrap(unwrap<InvokeInst>(Invoke)->getUnwindDest());
2984 }
2985 
2986 void LLVMSetNormalDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2987   unwrap<InvokeInst>(Invoke)->setNormalDest(unwrap(B));
2988 }
2989 
2990 void LLVMSetUnwindDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {
2991   if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {
2992     return CRI->setUnwindDest(unwrap(B));
2993   } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {
2994     return CSI->setUnwindDest(unwrap(B));
2995   }
2996   unwrap<InvokeInst>(Invoke)->setUnwindDest(unwrap(B));
2997 }
2998 
2999 /*--.. Operations on terminators ...........................................--*/
3000 
3001 unsigned LLVMGetNumSuccessors(LLVMValueRef Term) {
3002   return unwrap<Instruction>(Term)->getNumSuccessors();
3003 }
3004 
3005 LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) {
3006   return wrap(unwrap<Instruction>(Term)->getSuccessor(i));
3007 }
3008 
3009 void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) {
3010   return unwrap<Instruction>(Term)->setSuccessor(i, unwrap(block));
3011 }
3012 
3013 /*--.. Operations on branch instructions (only) ............................--*/
3014 
3015 LLVMBool LLVMIsConditional(LLVMValueRef Branch) {
3016   return unwrap<BranchInst>(Branch)->isConditional();
3017 }
3018 
3019 LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) {
3020   return wrap(unwrap<BranchInst>(Branch)->getCondition());
3021 }
3022 
3023 void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) {
3024   return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond));
3025 }
3026 
3027 /*--.. Operations on switch instructions (only) ............................--*/
3028 
3029 LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) {
3030   return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest());
3031 }
3032 
3033 /*--.. Operations on alloca instructions (only) ............................--*/
3034 
3035 LLVMTypeRef LLVMGetAllocatedType(LLVMValueRef Alloca) {
3036   return wrap(unwrap<AllocaInst>(Alloca)->getAllocatedType());
3037 }
3038 
3039 /*--.. Operations on gep instructions (only) ...............................--*/
3040 
3041 LLVMBool LLVMIsInBounds(LLVMValueRef GEP) {
3042   return unwrap<GEPOperator>(GEP)->isInBounds();
3043 }
3044 
3045 void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds) {
3046   return unwrap<GetElementPtrInst>(GEP)->setIsInBounds(InBounds);
3047 }
3048 
3049 LLVMTypeRef LLVMGetGEPSourceElementType(LLVMValueRef GEP) {
3050   return wrap(unwrap<GEPOperator>(GEP)->getSourceElementType());
3051 }
3052 
3053 /*--.. Operations on phi nodes .............................................--*/
3054 
3055 void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
3056                      LLVMBasicBlockRef *IncomingBlocks, unsigned Count) {
3057   PHINode *PhiVal = unwrap<PHINode>(PhiNode);
3058   for (unsigned I = 0; I != Count; ++I)
3059     PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I]));
3060 }
3061 
3062 unsigned LLVMCountIncoming(LLVMValueRef PhiNode) {
3063   return unwrap<PHINode>(PhiNode)->getNumIncomingValues();
3064 }
3065 
3066 LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) {
3067   return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index));
3068 }
3069 
3070 LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) {
3071   return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index));
3072 }
3073 
3074 /*--.. Operations on extractvalue and insertvalue nodes ....................--*/
3075 
3076 unsigned LLVMGetNumIndices(LLVMValueRef Inst) {
3077   auto *I = unwrap(Inst);
3078   if (auto *GEP = dyn_cast<GEPOperator>(I))
3079     return GEP->getNumIndices();
3080   if (auto *EV = dyn_cast<ExtractValueInst>(I))
3081     return EV->getNumIndices();
3082   if (auto *IV = dyn_cast<InsertValueInst>(I))
3083     return IV->getNumIndices();
3084   if (auto *CE = dyn_cast<ConstantExpr>(I))
3085     return CE->getIndices().size();
3086   llvm_unreachable(
3087     "LLVMGetNumIndices applies only to extractvalue and insertvalue!");
3088 }
3089 
3090 const unsigned *LLVMGetIndices(LLVMValueRef Inst) {
3091   auto *I = unwrap(Inst);
3092   if (auto *EV = dyn_cast<ExtractValueInst>(I))
3093     return EV->getIndices().data();
3094   if (auto *IV = dyn_cast<InsertValueInst>(I))
3095     return IV->getIndices().data();
3096   if (auto *CE = dyn_cast<ConstantExpr>(I))
3097     return CE->getIndices().data();
3098   llvm_unreachable(
3099     "LLVMGetIndices applies only to extractvalue and insertvalue!");
3100 }
3101 
3102 
3103 /*===-- Instruction builders ----------------------------------------------===*/
3104 
3105 LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C) {
3106   return wrap(new IRBuilder<>(*unwrap(C)));
3107 }
3108 
3109 LLVMBuilderRef LLVMCreateBuilder(void) {
3110   return LLVMCreateBuilderInContext(LLVMGetGlobalContext());
3111 }
3112 
3113 void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block,
3114                          LLVMValueRef Instr) {
3115   BasicBlock *BB = unwrap(Block);
3116   auto I = Instr ? unwrap<Instruction>(Instr)->getIterator() : BB->end();
3117   unwrap(Builder)->SetInsertPoint(BB, I);
3118 }
3119 
3120 void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
3121   Instruction *I = unwrap<Instruction>(Instr);
3122   unwrap(Builder)->SetInsertPoint(I->getParent(), I->getIterator());
3123 }
3124 
3125 void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
3126   BasicBlock *BB = unwrap(Block);
3127   unwrap(Builder)->SetInsertPoint(BB);
3128 }
3129 
3130 LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder) {
3131    return wrap(unwrap(Builder)->GetInsertBlock());
3132 }
3133 
3134 void LLVMClearInsertionPosition(LLVMBuilderRef Builder) {
3135   unwrap(Builder)->ClearInsertionPoint();
3136 }
3137 
3138 void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr) {
3139   unwrap(Builder)->Insert(unwrap<Instruction>(Instr));
3140 }
3141 
3142 void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr,
3143                                    const char *Name) {
3144   unwrap(Builder)->Insert(unwrap<Instruction>(Instr), Name);
3145 }
3146 
3147 void LLVMDisposeBuilder(LLVMBuilderRef Builder) {
3148   delete unwrap(Builder);
3149 }
3150 
3151 /*--.. Metadata builders ...................................................--*/
3152 
3153 LLVMMetadataRef LLVMGetCurrentDebugLocation2(LLVMBuilderRef Builder) {
3154   return wrap(unwrap(Builder)->getCurrentDebugLocation().getAsMDNode());
3155 }
3156 
3157 void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Builder, LLVMMetadataRef Loc) {
3158   if (Loc)
3159     unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(unwrap<MDNode>(Loc)));
3160   else
3161     unwrap(Builder)->SetCurrentDebugLocation(DebugLoc());
3162 }
3163 
3164 void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L) {
3165   MDNode *Loc =
3166       L ? cast<MDNode>(unwrap<MetadataAsValue>(L)->getMetadata()) : nullptr;
3167   unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(Loc));
3168 }
3169 
3170 LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder) {
3171   LLVMContext &Context = unwrap(Builder)->getContext();
3172   return wrap(MetadataAsValue::get(
3173       Context, unwrap(Builder)->getCurrentDebugLocation().getAsMDNode()));
3174 }
3175 
3176 void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) {
3177   unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst));
3178 }
3179 
3180 void LLVMAddMetadataToInst(LLVMBuilderRef Builder, LLVMValueRef Inst) {
3181   unwrap(Builder)->AddMetadataToInst(unwrap<Instruction>(Inst));
3182 }
3183 
3184 void LLVMBuilderSetDefaultFPMathTag(LLVMBuilderRef Builder,
3185                                     LLVMMetadataRef FPMathTag) {
3186 
3187   unwrap(Builder)->setDefaultFPMathTag(FPMathTag
3188                                        ? unwrap<MDNode>(FPMathTag)
3189                                        : nullptr);
3190 }
3191 
3192 LLVMMetadataRef LLVMBuilderGetDefaultFPMathTag(LLVMBuilderRef Builder) {
3193   return wrap(unwrap(Builder)->getDefaultFPMathTag());
3194 }
3195 
3196 /*--.. Instruction builders ................................................--*/
3197 
3198 LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef B) {
3199   return wrap(unwrap(B)->CreateRetVoid());
3200 }
3201 
3202 LLVMValueRef LLVMBuildRet(LLVMBuilderRef B, LLVMValueRef V) {
3203   return wrap(unwrap(B)->CreateRet(unwrap(V)));
3204 }
3205 
3206 LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef B, LLVMValueRef *RetVals,
3207                                    unsigned N) {
3208   return wrap(unwrap(B)->CreateAggregateRet(unwrap(RetVals), N));
3209 }
3210 
3211 LLVMValueRef LLVMBuildBr(LLVMBuilderRef B, LLVMBasicBlockRef Dest) {
3212   return wrap(unwrap(B)->CreateBr(unwrap(Dest)));
3213 }
3214 
3215 LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef B, LLVMValueRef If,
3216                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Else) {
3217   return wrap(unwrap(B)->CreateCondBr(unwrap(If), unwrap(Then), unwrap(Else)));
3218 }
3219 
3220 LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef B, LLVMValueRef V,
3221                              LLVMBasicBlockRef Else, unsigned NumCases) {
3222   return wrap(unwrap(B)->CreateSwitch(unwrap(V), unwrap(Else), NumCases));
3223 }
3224 
3225 LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
3226                                  unsigned NumDests) {
3227   return wrap(unwrap(B)->CreateIndirectBr(unwrap(Addr), NumDests));
3228 }
3229 
3230 LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn,
3231                              LLVMValueRef *Args, unsigned NumArgs,
3232                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
3233                              const char *Name) {
3234   Value *V = unwrap(Fn);
3235   FunctionType *FnT =
3236       cast<FunctionType>(V->getType()->getNonOpaquePointerElementType());
3237 
3238   return wrap(
3239       unwrap(B)->CreateInvoke(FnT, unwrap(Fn), unwrap(Then), unwrap(Catch),
3240                               makeArrayRef(unwrap(Args), NumArgs), Name));
3241 }
3242 
3243 LLVMValueRef LLVMBuildInvoke2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
3244                               LLVMValueRef *Args, unsigned NumArgs,
3245                               LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
3246                               const char *Name) {
3247   return wrap(unwrap(B)->CreateInvoke(
3248       unwrap<FunctionType>(Ty), unwrap(Fn), unwrap(Then), unwrap(Catch),
3249       makeArrayRef(unwrap(Args), NumArgs), Name));
3250 }
3251 
3252 LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
3253                                  LLVMValueRef PersFn, unsigned NumClauses,
3254                                  const char *Name) {
3255   // The personality used to live on the landingpad instruction, but now it
3256   // lives on the parent function. For compatibility, take the provided
3257   // personality and put it on the parent function.
3258   if (PersFn)
3259     unwrap(B)->GetInsertBlock()->getParent()->setPersonalityFn(
3260         cast<Function>(unwrap(PersFn)));
3261   return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty), NumClauses, Name));
3262 }
3263 
3264 LLVMValueRef LLVMBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
3265                                LLVMValueRef *Args, unsigned NumArgs,
3266                                const char *Name) {
3267   return wrap(unwrap(B)->CreateCatchPad(unwrap(ParentPad),
3268                                         makeArrayRef(unwrap(Args), NumArgs),
3269                                         Name));
3270 }
3271 
3272 LLVMValueRef LLVMBuildCleanupPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
3273                                  LLVMValueRef *Args, unsigned NumArgs,
3274                                  const char *Name) {
3275   if (ParentPad == nullptr) {
3276     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
3277     ParentPad = wrap(Constant::getNullValue(Ty));
3278   }
3279   return wrap(unwrap(B)->CreateCleanupPad(unwrap(ParentPad),
3280                                           makeArrayRef(unwrap(Args), NumArgs),
3281                                           Name));
3282 }
3283 
3284 LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn) {
3285   return wrap(unwrap(B)->CreateResume(unwrap(Exn)));
3286 }
3287 
3288 LLVMValueRef LLVMBuildCatchSwitch(LLVMBuilderRef B, LLVMValueRef ParentPad,
3289                                   LLVMBasicBlockRef UnwindBB,
3290                                   unsigned NumHandlers, const char *Name) {
3291   if (ParentPad == nullptr) {
3292     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
3293     ParentPad = wrap(Constant::getNullValue(Ty));
3294   }
3295   return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(UnwindBB),
3296                                            NumHandlers, Name));
3297 }
3298 
3299 LLVMValueRef LLVMBuildCatchRet(LLVMBuilderRef B, LLVMValueRef CatchPad,
3300                                LLVMBasicBlockRef BB) {
3301   return wrap(unwrap(B)->CreateCatchRet(unwrap<CatchPadInst>(CatchPad),
3302                                         unwrap(BB)));
3303 }
3304 
3305 LLVMValueRef LLVMBuildCleanupRet(LLVMBuilderRef B, LLVMValueRef CatchPad,
3306                                  LLVMBasicBlockRef BB) {
3307   return wrap(unwrap(B)->CreateCleanupRet(unwrap<CleanupPadInst>(CatchPad),
3308                                           unwrap(BB)));
3309 }
3310 
3311 LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef B) {
3312   return wrap(unwrap(B)->CreateUnreachable());
3313 }
3314 
3315 void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal,
3316                  LLVMBasicBlockRef Dest) {
3317   unwrap<SwitchInst>(Switch)->addCase(unwrap<ConstantInt>(OnVal), unwrap(Dest));
3318 }
3319 
3320 void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) {
3321   unwrap<IndirectBrInst>(IndirectBr)->addDestination(unwrap(Dest));
3322 }
3323 
3324 unsigned LLVMGetNumClauses(LLVMValueRef LandingPad) {
3325   return unwrap<LandingPadInst>(LandingPad)->getNumClauses();
3326 }
3327 
3328 LLVMValueRef LLVMGetClause(LLVMValueRef LandingPad, unsigned Idx) {
3329   return wrap(unwrap<LandingPadInst>(LandingPad)->getClause(Idx));
3330 }
3331 
3332 void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal) {
3333   unwrap<LandingPadInst>(LandingPad)->
3334     addClause(cast<Constant>(unwrap(ClauseVal)));
3335 }
3336 
3337 LLVMBool LLVMIsCleanup(LLVMValueRef LandingPad) {
3338   return unwrap<LandingPadInst>(LandingPad)->isCleanup();
3339 }
3340 
3341 void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val) {
3342   unwrap<LandingPadInst>(LandingPad)->setCleanup(Val);
3343 }
3344 
3345 void LLVMAddHandler(LLVMValueRef CatchSwitch, LLVMBasicBlockRef Dest) {
3346   unwrap<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Dest));
3347 }
3348 
3349 unsigned LLVMGetNumHandlers(LLVMValueRef CatchSwitch) {
3350   return unwrap<CatchSwitchInst>(CatchSwitch)->getNumHandlers();
3351 }
3352 
3353 void LLVMGetHandlers(LLVMValueRef CatchSwitch, LLVMBasicBlockRef *Handlers) {
3354   CatchSwitchInst *CSI = unwrap<CatchSwitchInst>(CatchSwitch);
3355   for (const BasicBlock *H : CSI->handlers())
3356     *Handlers++ = wrap(H);
3357 }
3358 
3359 LLVMValueRef LLVMGetParentCatchSwitch(LLVMValueRef CatchPad) {
3360   return wrap(unwrap<CatchPadInst>(CatchPad)->getCatchSwitch());
3361 }
3362 
3363 void LLVMSetParentCatchSwitch(LLVMValueRef CatchPad, LLVMValueRef CatchSwitch) {
3364   unwrap<CatchPadInst>(CatchPad)
3365     ->setCatchSwitch(unwrap<CatchSwitchInst>(CatchSwitch));
3366 }
3367 
3368 /*--.. Funclets ...........................................................--*/
3369 
3370 LLVMValueRef LLVMGetArgOperand(LLVMValueRef Funclet, unsigned i) {
3371   return wrap(unwrap<FuncletPadInst>(Funclet)->getArgOperand(i));
3372 }
3373 
3374 void LLVMSetArgOperand(LLVMValueRef Funclet, unsigned i, LLVMValueRef value) {
3375   unwrap<FuncletPadInst>(Funclet)->setArgOperand(i, unwrap(value));
3376 }
3377 
3378 /*--.. Arithmetic ..........................................................--*/
3379 
3380 LLVMValueRef LLVMBuildAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3381                           const char *Name) {
3382   return wrap(unwrap(B)->CreateAdd(unwrap(LHS), unwrap(RHS), Name));
3383 }
3384 
3385 LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3386                           const char *Name) {
3387   return wrap(unwrap(B)->CreateNSWAdd(unwrap(LHS), unwrap(RHS), Name));
3388 }
3389 
3390 LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3391                           const char *Name) {
3392   return wrap(unwrap(B)->CreateNUWAdd(unwrap(LHS), unwrap(RHS), Name));
3393 }
3394 
3395 LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3396                           const char *Name) {
3397   return wrap(unwrap(B)->CreateFAdd(unwrap(LHS), unwrap(RHS), Name));
3398 }
3399 
3400 LLVMValueRef LLVMBuildSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3401                           const char *Name) {
3402   return wrap(unwrap(B)->CreateSub(unwrap(LHS), unwrap(RHS), Name));
3403 }
3404 
3405 LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3406                           const char *Name) {
3407   return wrap(unwrap(B)->CreateNSWSub(unwrap(LHS), unwrap(RHS), Name));
3408 }
3409 
3410 LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3411                           const char *Name) {
3412   return wrap(unwrap(B)->CreateNUWSub(unwrap(LHS), unwrap(RHS), Name));
3413 }
3414 
3415 LLVMValueRef LLVMBuildFSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3416                           const char *Name) {
3417   return wrap(unwrap(B)->CreateFSub(unwrap(LHS), unwrap(RHS), Name));
3418 }
3419 
3420 LLVMValueRef LLVMBuildMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3421                           const char *Name) {
3422   return wrap(unwrap(B)->CreateMul(unwrap(LHS), unwrap(RHS), Name));
3423 }
3424 
3425 LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3426                           const char *Name) {
3427   return wrap(unwrap(B)->CreateNSWMul(unwrap(LHS), unwrap(RHS), Name));
3428 }
3429 
3430 LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3431                           const char *Name) {
3432   return wrap(unwrap(B)->CreateNUWMul(unwrap(LHS), unwrap(RHS), Name));
3433 }
3434 
3435 LLVMValueRef LLVMBuildFMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3436                           const char *Name) {
3437   return wrap(unwrap(B)->CreateFMul(unwrap(LHS), unwrap(RHS), Name));
3438 }
3439 
3440 LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3441                            const char *Name) {
3442   return wrap(unwrap(B)->CreateUDiv(unwrap(LHS), unwrap(RHS), Name));
3443 }
3444 
3445 LLVMValueRef LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,
3446                                 LLVMValueRef RHS, const char *Name) {
3447   return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));
3448 }
3449 
3450 LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3451                            const char *Name) {
3452   return wrap(unwrap(B)->CreateSDiv(unwrap(LHS), unwrap(RHS), Name));
3453 }
3454 
3455 LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef B, LLVMValueRef LHS,
3456                                 LLVMValueRef RHS, const char *Name) {
3457   return wrap(unwrap(B)->CreateExactSDiv(unwrap(LHS), unwrap(RHS), Name));
3458 }
3459 
3460 LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3461                            const char *Name) {
3462   return wrap(unwrap(B)->CreateFDiv(unwrap(LHS), unwrap(RHS), Name));
3463 }
3464 
3465 LLVMValueRef LLVMBuildURem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3466                            const char *Name) {
3467   return wrap(unwrap(B)->CreateURem(unwrap(LHS), unwrap(RHS), Name));
3468 }
3469 
3470 LLVMValueRef LLVMBuildSRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3471                            const char *Name) {
3472   return wrap(unwrap(B)->CreateSRem(unwrap(LHS), unwrap(RHS), Name));
3473 }
3474 
3475 LLVMValueRef LLVMBuildFRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3476                            const char *Name) {
3477   return wrap(unwrap(B)->CreateFRem(unwrap(LHS), unwrap(RHS), Name));
3478 }
3479 
3480 LLVMValueRef LLVMBuildShl(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3481                           const char *Name) {
3482   return wrap(unwrap(B)->CreateShl(unwrap(LHS), unwrap(RHS), Name));
3483 }
3484 
3485 LLVMValueRef LLVMBuildLShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3486                            const char *Name) {
3487   return wrap(unwrap(B)->CreateLShr(unwrap(LHS), unwrap(RHS), Name));
3488 }
3489 
3490 LLVMValueRef LLVMBuildAShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3491                            const char *Name) {
3492   return wrap(unwrap(B)->CreateAShr(unwrap(LHS), unwrap(RHS), Name));
3493 }
3494 
3495 LLVMValueRef LLVMBuildAnd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3496                           const char *Name) {
3497   return wrap(unwrap(B)->CreateAnd(unwrap(LHS), unwrap(RHS), Name));
3498 }
3499 
3500 LLVMValueRef LLVMBuildOr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3501                          const char *Name) {
3502   return wrap(unwrap(B)->CreateOr(unwrap(LHS), unwrap(RHS), Name));
3503 }
3504 
3505 LLVMValueRef LLVMBuildXor(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
3506                           const char *Name) {
3507   return wrap(unwrap(B)->CreateXor(unwrap(LHS), unwrap(RHS), Name));
3508 }
3509 
3510 LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op,
3511                             LLVMValueRef LHS, LLVMValueRef RHS,
3512                             const char *Name) {
3513   return wrap(unwrap(B)->CreateBinOp(Instruction::BinaryOps(map_from_llvmopcode(Op)), unwrap(LHS),
3514                                      unwrap(RHS), Name));
3515 }
3516 
3517 LLVMValueRef LLVMBuildNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3518   return wrap(unwrap(B)->CreateNeg(unwrap(V), Name));
3519 }
3520 
3521 LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V,
3522                              const char *Name) {
3523   return wrap(unwrap(B)->CreateNSWNeg(unwrap(V), Name));
3524 }
3525 
3526 LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,
3527                              const char *Name) {
3528   return wrap(unwrap(B)->CreateNUWNeg(unwrap(V), Name));
3529 }
3530 
3531 LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3532   return wrap(unwrap(B)->CreateFNeg(unwrap(V), Name));
3533 }
3534 
3535 LLVMValueRef LLVMBuildNot(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
3536   return wrap(unwrap(B)->CreateNot(unwrap(V), Name));
3537 }
3538 
3539 /*--.. Memory ..............................................................--*/
3540 
3541 LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
3542                              const char *Name) {
3543   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
3544   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
3545   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
3546   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
3547                                                ITy, unwrap(Ty), AllocSize,
3548                                                nullptr, nullptr, "");
3549   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
3550 }
3551 
3552 LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
3553                                   LLVMValueRef Val, const char *Name) {
3554   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
3555   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
3556   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
3557   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
3558                                                ITy, unwrap(Ty), AllocSize,
3559                                                unwrap(Val), nullptr, "");
3560   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
3561 }
3562 
3563 LLVMValueRef LLVMBuildMemSet(LLVMBuilderRef B, LLVMValueRef Ptr,
3564                              LLVMValueRef Val, LLVMValueRef Len,
3565                              unsigned Align) {
3566   return wrap(unwrap(B)->CreateMemSet(unwrap(Ptr), unwrap(Val), unwrap(Len),
3567                                       MaybeAlign(Align)));
3568 }
3569 
3570 LLVMValueRef LLVMBuildMemCpy(LLVMBuilderRef B,
3571                              LLVMValueRef Dst, unsigned DstAlign,
3572                              LLVMValueRef Src, unsigned SrcAlign,
3573                              LLVMValueRef Size) {
3574   return wrap(unwrap(B)->CreateMemCpy(unwrap(Dst), MaybeAlign(DstAlign),
3575                                       unwrap(Src), MaybeAlign(SrcAlign),
3576                                       unwrap(Size)));
3577 }
3578 
3579 LLVMValueRef LLVMBuildMemMove(LLVMBuilderRef B,
3580                               LLVMValueRef Dst, unsigned DstAlign,
3581                               LLVMValueRef Src, unsigned SrcAlign,
3582                               LLVMValueRef Size) {
3583   return wrap(unwrap(B)->CreateMemMove(unwrap(Dst), MaybeAlign(DstAlign),
3584                                        unwrap(Src), MaybeAlign(SrcAlign),
3585                                        unwrap(Size)));
3586 }
3587 
3588 LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
3589                              const char *Name) {
3590   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), nullptr, Name));
3591 }
3592 
3593 LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
3594                                   LLVMValueRef Val, const char *Name) {
3595   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), unwrap(Val), Name));
3596 }
3597 
3598 LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) {
3599   return wrap(unwrap(B)->Insert(
3600      CallInst::CreateFree(unwrap(PointerVal), unwrap(B)->GetInsertBlock())));
3601 }
3602 
3603 LLVMValueRef LLVMBuildLoad(LLVMBuilderRef B, LLVMValueRef PointerVal,
3604                            const char *Name) {
3605   Value *V = unwrap(PointerVal);
3606   PointerType *Ty = cast<PointerType>(V->getType());
3607 
3608   return wrap(
3609       unwrap(B)->CreateLoad(Ty->getNonOpaquePointerElementType(), V, Name));
3610 }
3611 
3612 LLVMValueRef LLVMBuildLoad2(LLVMBuilderRef B, LLVMTypeRef Ty,
3613                             LLVMValueRef PointerVal, const char *Name) {
3614   return wrap(unwrap(B)->CreateLoad(unwrap(Ty), unwrap(PointerVal), Name));
3615 }
3616 
3617 LLVMValueRef LLVMBuildStore(LLVMBuilderRef B, LLVMValueRef Val,
3618                             LLVMValueRef PointerVal) {
3619   return wrap(unwrap(B)->CreateStore(unwrap(Val), unwrap(PointerVal)));
3620 }
3621 
3622 static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) {
3623   switch (Ordering) {
3624     case LLVMAtomicOrderingNotAtomic: return AtomicOrdering::NotAtomic;
3625     case LLVMAtomicOrderingUnordered: return AtomicOrdering::Unordered;
3626     case LLVMAtomicOrderingMonotonic: return AtomicOrdering::Monotonic;
3627     case LLVMAtomicOrderingAcquire: return AtomicOrdering::Acquire;
3628     case LLVMAtomicOrderingRelease: return AtomicOrdering::Release;
3629     case LLVMAtomicOrderingAcquireRelease:
3630       return AtomicOrdering::AcquireRelease;
3631     case LLVMAtomicOrderingSequentiallyConsistent:
3632       return AtomicOrdering::SequentiallyConsistent;
3633   }
3634 
3635   llvm_unreachable("Invalid LLVMAtomicOrdering value!");
3636 }
3637 
3638 static LLVMAtomicOrdering mapToLLVMOrdering(AtomicOrdering Ordering) {
3639   switch (Ordering) {
3640     case AtomicOrdering::NotAtomic: return LLVMAtomicOrderingNotAtomic;
3641     case AtomicOrdering::Unordered: return LLVMAtomicOrderingUnordered;
3642     case AtomicOrdering::Monotonic: return LLVMAtomicOrderingMonotonic;
3643     case AtomicOrdering::Acquire: return LLVMAtomicOrderingAcquire;
3644     case AtomicOrdering::Release: return LLVMAtomicOrderingRelease;
3645     case AtomicOrdering::AcquireRelease:
3646       return LLVMAtomicOrderingAcquireRelease;
3647     case AtomicOrdering::SequentiallyConsistent:
3648       return LLVMAtomicOrderingSequentiallyConsistent;
3649   }
3650 
3651   llvm_unreachable("Invalid AtomicOrdering value!");
3652 }
3653 
3654 static AtomicRMWInst::BinOp mapFromLLVMRMWBinOp(LLVMAtomicRMWBinOp BinOp) {
3655   switch (BinOp) {
3656     case LLVMAtomicRMWBinOpXchg: return AtomicRMWInst::Xchg;
3657     case LLVMAtomicRMWBinOpAdd: return AtomicRMWInst::Add;
3658     case LLVMAtomicRMWBinOpSub: return AtomicRMWInst::Sub;
3659     case LLVMAtomicRMWBinOpAnd: return AtomicRMWInst::And;
3660     case LLVMAtomicRMWBinOpNand: return AtomicRMWInst::Nand;
3661     case LLVMAtomicRMWBinOpOr: return AtomicRMWInst::Or;
3662     case LLVMAtomicRMWBinOpXor: return AtomicRMWInst::Xor;
3663     case LLVMAtomicRMWBinOpMax: return AtomicRMWInst::Max;
3664     case LLVMAtomicRMWBinOpMin: return AtomicRMWInst::Min;
3665     case LLVMAtomicRMWBinOpUMax: return AtomicRMWInst::UMax;
3666     case LLVMAtomicRMWBinOpUMin: return AtomicRMWInst::UMin;
3667     case LLVMAtomicRMWBinOpFAdd: return AtomicRMWInst::FAdd;
3668     case LLVMAtomicRMWBinOpFSub: return AtomicRMWInst::FSub;
3669   }
3670 
3671   llvm_unreachable("Invalid LLVMAtomicRMWBinOp value!");
3672 }
3673 
3674 static LLVMAtomicRMWBinOp mapToLLVMRMWBinOp(AtomicRMWInst::BinOp BinOp) {
3675   switch (BinOp) {
3676     case AtomicRMWInst::Xchg: return LLVMAtomicRMWBinOpXchg;
3677     case AtomicRMWInst::Add: return LLVMAtomicRMWBinOpAdd;
3678     case AtomicRMWInst::Sub: return LLVMAtomicRMWBinOpSub;
3679     case AtomicRMWInst::And: return LLVMAtomicRMWBinOpAnd;
3680     case AtomicRMWInst::Nand: return LLVMAtomicRMWBinOpNand;
3681     case AtomicRMWInst::Or: return LLVMAtomicRMWBinOpOr;
3682     case AtomicRMWInst::Xor: return LLVMAtomicRMWBinOpXor;
3683     case AtomicRMWInst::Max: return LLVMAtomicRMWBinOpMax;
3684     case AtomicRMWInst::Min: return LLVMAtomicRMWBinOpMin;
3685     case AtomicRMWInst::UMax: return LLVMAtomicRMWBinOpUMax;
3686     case AtomicRMWInst::UMin: return LLVMAtomicRMWBinOpUMin;
3687     case AtomicRMWInst::FAdd: return LLVMAtomicRMWBinOpFAdd;
3688     case AtomicRMWInst::FSub: return LLVMAtomicRMWBinOpFSub;
3689     default: break;
3690   }
3691 
3692   llvm_unreachable("Invalid AtomicRMWBinOp value!");
3693 }
3694 
3695 // TODO: Should this and other atomic instructions support building with
3696 // "syncscope"?
3697 LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering Ordering,
3698                             LLVMBool isSingleThread, const char *Name) {
3699   return wrap(
3700     unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering),
3701                            isSingleThread ? SyncScope::SingleThread
3702                                           : SyncScope::System,
3703                            Name));
3704 }
3705 
3706 LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3707                           LLVMValueRef *Indices, unsigned NumIndices,
3708                           const char *Name) {
3709   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3710   Value *Val = unwrap(Pointer);
3711   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
3712   return wrap(unwrap(B)->CreateGEP(Ty, Val, IdxList, Name));
3713 }
3714 
3715 LLVMValueRef LLVMBuildGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3716                            LLVMValueRef Pointer, LLVMValueRef *Indices,
3717                            unsigned NumIndices, const char *Name) {
3718   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3719   return wrap(unwrap(B)->CreateGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));
3720 }
3721 
3722 LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3723                                   LLVMValueRef *Indices, unsigned NumIndices,
3724                                   const char *Name) {
3725   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3726   Value *Val = unwrap(Pointer);
3727   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
3728   return wrap(unwrap(B)->CreateInBoundsGEP(Ty, Val, IdxList, Name));
3729 }
3730 
3731 LLVMValueRef LLVMBuildInBoundsGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3732                                    LLVMValueRef Pointer, LLVMValueRef *Indices,
3733                                    unsigned NumIndices, const char *Name) {
3734   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
3735   return wrap(
3736       unwrap(B)->CreateInBoundsGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));
3737 }
3738 
3739 LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
3740                                 unsigned Idx, const char *Name) {
3741   Value *Val = unwrap(Pointer);
3742   Type *Ty = Val->getType()->getScalarType()->getNonOpaquePointerElementType();
3743   return wrap(unwrap(B)->CreateStructGEP(Ty, Val, Idx, Name));
3744 }
3745 
3746 LLVMValueRef LLVMBuildStructGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
3747                                  LLVMValueRef Pointer, unsigned Idx,
3748                                  const char *Name) {
3749   return wrap(
3750       unwrap(B)->CreateStructGEP(unwrap(Ty), unwrap(Pointer), Idx, Name));
3751 }
3752 
3753 LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str,
3754                                    const char *Name) {
3755   return wrap(unwrap(B)->CreateGlobalString(Str, Name));
3756 }
3757 
3758 LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,
3759                                       const char *Name) {
3760   return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name));
3761 }
3762 
3763 LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) {
3764   Value *P = unwrap<Value>(MemAccessInst);
3765   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3766     return LI->isVolatile();
3767   if (StoreInst *SI = dyn_cast<StoreInst>(P))
3768     return SI->isVolatile();
3769   if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(P))
3770     return AI->isVolatile();
3771   return cast<AtomicCmpXchgInst>(P)->isVolatile();
3772 }
3773 
3774 void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) {
3775   Value *P = unwrap<Value>(MemAccessInst);
3776   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3777     return LI->setVolatile(isVolatile);
3778   if (StoreInst *SI = dyn_cast<StoreInst>(P))
3779     return SI->setVolatile(isVolatile);
3780   if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(P))
3781     return AI->setVolatile(isVolatile);
3782   return cast<AtomicCmpXchgInst>(P)->setVolatile(isVolatile);
3783 }
3784 
3785 LLVMBool LLVMGetWeak(LLVMValueRef CmpXchgInst) {
3786   return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->isWeak();
3787 }
3788 
3789 void LLVMSetWeak(LLVMValueRef CmpXchgInst, LLVMBool isWeak) {
3790   return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->setWeak(isWeak);
3791 }
3792 
3793 LLVMAtomicOrdering LLVMGetOrdering(LLVMValueRef MemAccessInst) {
3794   Value *P = unwrap<Value>(MemAccessInst);
3795   AtomicOrdering O;
3796   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3797     O = LI->getOrdering();
3798   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
3799     O = SI->getOrdering();
3800   else
3801     O = cast<AtomicRMWInst>(P)->getOrdering();
3802   return mapToLLVMOrdering(O);
3803 }
3804 
3805 void LLVMSetOrdering(LLVMValueRef MemAccessInst, LLVMAtomicOrdering Ordering) {
3806   Value *P = unwrap<Value>(MemAccessInst);
3807   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
3808 
3809   if (LoadInst *LI = dyn_cast<LoadInst>(P))
3810     return LI->setOrdering(O);
3811   return cast<StoreInst>(P)->setOrdering(O);
3812 }
3813 
3814 LLVMAtomicRMWBinOp LLVMGetAtomicRMWBinOp(LLVMValueRef Inst) {
3815   return mapToLLVMRMWBinOp(unwrap<AtomicRMWInst>(Inst)->getOperation());
3816 }
3817 
3818 void LLVMSetAtomicRMWBinOp(LLVMValueRef Inst, LLVMAtomicRMWBinOp BinOp) {
3819   unwrap<AtomicRMWInst>(Inst)->setOperation(mapFromLLVMRMWBinOp(BinOp));
3820 }
3821 
3822 /*--.. Casts ...............................................................--*/
3823 
3824 LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val,
3825                             LLVMTypeRef DestTy, const char *Name) {
3826   return wrap(unwrap(B)->CreateTrunc(unwrap(Val), unwrap(DestTy), Name));
3827 }
3828 
3829 LLVMValueRef LLVMBuildZExt(LLVMBuilderRef B, LLVMValueRef Val,
3830                            LLVMTypeRef DestTy, const char *Name) {
3831   return wrap(unwrap(B)->CreateZExt(unwrap(Val), unwrap(DestTy), Name));
3832 }
3833 
3834 LLVMValueRef LLVMBuildSExt(LLVMBuilderRef B, LLVMValueRef Val,
3835                            LLVMTypeRef DestTy, const char *Name) {
3836   return wrap(unwrap(B)->CreateSExt(unwrap(Val), unwrap(DestTy), Name));
3837 }
3838 
3839 LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef B, LLVMValueRef Val,
3840                              LLVMTypeRef DestTy, const char *Name) {
3841   return wrap(unwrap(B)->CreateFPToUI(unwrap(Val), unwrap(DestTy), Name));
3842 }
3843 
3844 LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef B, LLVMValueRef Val,
3845                              LLVMTypeRef DestTy, const char *Name) {
3846   return wrap(unwrap(B)->CreateFPToSI(unwrap(Val), unwrap(DestTy), Name));
3847 }
3848 
3849 LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef B, LLVMValueRef Val,
3850                              LLVMTypeRef DestTy, const char *Name) {
3851   return wrap(unwrap(B)->CreateUIToFP(unwrap(Val), unwrap(DestTy), Name));
3852 }
3853 
3854 LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef B, LLVMValueRef Val,
3855                              LLVMTypeRef DestTy, const char *Name) {
3856   return wrap(unwrap(B)->CreateSIToFP(unwrap(Val), unwrap(DestTy), Name));
3857 }
3858 
3859 LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef B, LLVMValueRef Val,
3860                               LLVMTypeRef DestTy, const char *Name) {
3861   return wrap(unwrap(B)->CreateFPTrunc(unwrap(Val), unwrap(DestTy), Name));
3862 }
3863 
3864 LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef B, LLVMValueRef Val,
3865                             LLVMTypeRef DestTy, const char *Name) {
3866   return wrap(unwrap(B)->CreateFPExt(unwrap(Val), unwrap(DestTy), Name));
3867 }
3868 
3869 LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef B, LLVMValueRef Val,
3870                                LLVMTypeRef DestTy, const char *Name) {
3871   return wrap(unwrap(B)->CreatePtrToInt(unwrap(Val), unwrap(DestTy), Name));
3872 }
3873 
3874 LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef B, LLVMValueRef Val,
3875                                LLVMTypeRef DestTy, const char *Name) {
3876   return wrap(unwrap(B)->CreateIntToPtr(unwrap(Val), unwrap(DestTy), Name));
3877 }
3878 
3879 LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3880                               LLVMTypeRef DestTy, const char *Name) {
3881   return wrap(unwrap(B)->CreateBitCast(unwrap(Val), unwrap(DestTy), Name));
3882 }
3883 
3884 LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef B, LLVMValueRef Val,
3885                                     LLVMTypeRef DestTy, const char *Name) {
3886   return wrap(unwrap(B)->CreateAddrSpaceCast(unwrap(Val), unwrap(DestTy), Name));
3887 }
3888 
3889 LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3890                                     LLVMTypeRef DestTy, const char *Name) {
3891   return wrap(unwrap(B)->CreateZExtOrBitCast(unwrap(Val), unwrap(DestTy),
3892                                              Name));
3893 }
3894 
3895 LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3896                                     LLVMTypeRef DestTy, const char *Name) {
3897   return wrap(unwrap(B)->CreateSExtOrBitCast(unwrap(Val), unwrap(DestTy),
3898                                              Name));
3899 }
3900 
3901 LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
3902                                      LLVMTypeRef DestTy, const char *Name) {
3903   return wrap(unwrap(B)->CreateTruncOrBitCast(unwrap(Val), unwrap(DestTy),
3904                                               Name));
3905 }
3906 
3907 LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val,
3908                            LLVMTypeRef DestTy, const char *Name) {
3909   return wrap(unwrap(B)->CreateCast(Instruction::CastOps(map_from_llvmopcode(Op)), unwrap(Val),
3910                                     unwrap(DestTy), Name));
3911 }
3912 
3913 LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef B, LLVMValueRef Val,
3914                                   LLVMTypeRef DestTy, const char *Name) {
3915   return wrap(unwrap(B)->CreatePointerCast(unwrap(Val), unwrap(DestTy), Name));
3916 }
3917 
3918 LLVMValueRef LLVMBuildIntCast2(LLVMBuilderRef B, LLVMValueRef Val,
3919                                LLVMTypeRef DestTy, LLVMBool IsSigned,
3920                                const char *Name) {
3921   return wrap(
3922       unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), IsSigned, Name));
3923 }
3924 
3925 LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
3926                               LLVMTypeRef DestTy, const char *Name) {
3927   return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy),
3928                                        /*isSigned*/true, Name));
3929 }
3930 
3931 LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef B, LLVMValueRef Val,
3932                              LLVMTypeRef DestTy, const char *Name) {
3933   return wrap(unwrap(B)->CreateFPCast(unwrap(Val), unwrap(DestTy), Name));
3934 }
3935 
3936 LLVMOpcode LLVMGetCastOpcode(LLVMValueRef Src, LLVMBool SrcIsSigned,
3937                              LLVMTypeRef DestTy, LLVMBool DestIsSigned) {
3938   return map_to_llvmopcode(CastInst::getCastOpcode(
3939       unwrap(Src), SrcIsSigned, unwrap(DestTy), DestIsSigned));
3940 }
3941 
3942 /*--.. Comparisons .........................................................--*/
3943 
3944 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op,
3945                            LLVMValueRef LHS, LLVMValueRef RHS,
3946                            const char *Name) {
3947   return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op),
3948                                     unwrap(LHS), unwrap(RHS), Name));
3949 }
3950 
3951 LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op,
3952                            LLVMValueRef LHS, LLVMValueRef RHS,
3953                            const char *Name) {
3954   return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op),
3955                                     unwrap(LHS), unwrap(RHS), Name));
3956 }
3957 
3958 /*--.. Miscellaneous instructions ..........................................--*/
3959 
3960 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) {
3961   return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name));
3962 }
3963 
3964 LLVMValueRef LLVMBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
3965                            LLVMValueRef *Args, unsigned NumArgs,
3966                            const char *Name) {
3967   Value *V = unwrap(Fn);
3968   FunctionType *FnT =
3969       cast<FunctionType>(V->getType()->getNonOpaquePointerElementType());
3970 
3971   return wrap(unwrap(B)->CreateCall(FnT, unwrap(Fn),
3972                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3973 }
3974 
3975 LLVMValueRef LLVMBuildCall2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
3976                             LLVMValueRef *Args, unsigned NumArgs,
3977                             const char *Name) {
3978   FunctionType *FTy = unwrap<FunctionType>(Ty);
3979   return wrap(unwrap(B)->CreateCall(FTy, unwrap(Fn),
3980                                     makeArrayRef(unwrap(Args), NumArgs), Name));
3981 }
3982 
3983 LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If,
3984                              LLVMValueRef Then, LLVMValueRef Else,
3985                              const char *Name) {
3986   return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else),
3987                                       Name));
3988 }
3989 
3990 LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List,
3991                             LLVMTypeRef Ty, const char *Name) {
3992   return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name));
3993 }
3994 
3995 LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal,
3996                                       LLVMValueRef Index, const char *Name) {
3997   return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index),
3998                                               Name));
3999 }
4000 
4001 LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal,
4002                                     LLVMValueRef EltVal, LLVMValueRef Index,
4003                                     const char *Name) {
4004   return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal),
4005                                              unwrap(Index), Name));
4006 }
4007 
4008 LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1,
4009                                     LLVMValueRef V2, LLVMValueRef Mask,
4010                                     const char *Name) {
4011   return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2),
4012                                              unwrap(Mask), Name));
4013 }
4014 
4015 LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal,
4016                                    unsigned Index, const char *Name) {
4017   return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name));
4018 }
4019 
4020 LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal,
4021                                   LLVMValueRef EltVal, unsigned Index,
4022                                   const char *Name) {
4023   return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal),
4024                                            Index, Name));
4025 }
4026 
4027 LLVMValueRef LLVMBuildFreeze(LLVMBuilderRef B, LLVMValueRef Val,
4028                              const char *Name) {
4029   return wrap(unwrap(B)->CreateFreeze(unwrap(Val), Name));
4030 }
4031 
4032 LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val,
4033                              const char *Name) {
4034   return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name));
4035 }
4036 
4037 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val,
4038                                 const char *Name) {
4039   return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name));
4040 }
4041 
4042 LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef B, LLVMValueRef LHS,
4043                               LLVMValueRef RHS, const char *Name) {
4044   Value *L = unwrap(LHS);
4045   Type *ElemTy = L->getType()->getNonOpaquePointerElementType();
4046   return wrap(unwrap(B)->CreatePtrDiff(ElemTy, L, unwrap(RHS), Name));
4047 }
4048 
4049 LLVMValueRef LLVMBuildPtrDiff2(LLVMBuilderRef B, LLVMTypeRef ElemTy,
4050                                LLVMValueRef LHS, LLVMValueRef RHS,
4051                                const char *Name) {
4052   return wrap(unwrap(B)->CreatePtrDiff(unwrap(ElemTy), unwrap(LHS),
4053                                        unwrap(RHS), Name));
4054 }
4055 
4056 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op,
4057                                LLVMValueRef PTR, LLVMValueRef Val,
4058                                LLVMAtomicOrdering ordering,
4059                                LLVMBool singleThread) {
4060   AtomicRMWInst::BinOp intop = mapFromLLVMRMWBinOp(op);
4061   return wrap(unwrap(B)->CreateAtomicRMW(
4062       intop, unwrap(PTR), unwrap(Val), MaybeAlign(),
4063       mapFromLLVMOrdering(ordering),
4064       singleThread ? SyncScope::SingleThread : SyncScope::System));
4065 }
4066 
4067 LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Ptr,
4068                                     LLVMValueRef Cmp, LLVMValueRef New,
4069                                     LLVMAtomicOrdering SuccessOrdering,
4070                                     LLVMAtomicOrdering FailureOrdering,
4071                                     LLVMBool singleThread) {
4072 
4073   return wrap(unwrap(B)->CreateAtomicCmpXchg(
4074       unwrap(Ptr), unwrap(Cmp), unwrap(New), MaybeAlign(),
4075       mapFromLLVMOrdering(SuccessOrdering),
4076       mapFromLLVMOrdering(FailureOrdering),
4077       singleThread ? SyncScope::SingleThread : SyncScope::System));
4078 }
4079 
4080 unsigned LLVMGetNumMaskElements(LLVMValueRef SVInst) {
4081   Value *P = unwrap<Value>(SVInst);
4082   ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);
4083   return I->getShuffleMask().size();
4084 }
4085 
4086 int LLVMGetMaskValue(LLVMValueRef SVInst, unsigned Elt) {
4087   Value *P = unwrap<Value>(SVInst);
4088   ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);
4089   return I->getMaskValue(Elt);
4090 }
4091 
4092 int LLVMGetUndefMaskElem(void) { return UndefMaskElem; }
4093 
4094 LLVMBool LLVMIsAtomicSingleThread(LLVMValueRef AtomicInst) {
4095   Value *P = unwrap<Value>(AtomicInst);
4096 
4097   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
4098     return I->getSyncScopeID() == SyncScope::SingleThread;
4099   return cast<AtomicCmpXchgInst>(P)->getSyncScopeID() ==
4100              SyncScope::SingleThread;
4101 }
4102 
4103 void LLVMSetAtomicSingleThread(LLVMValueRef AtomicInst, LLVMBool NewValue) {
4104   Value *P = unwrap<Value>(AtomicInst);
4105   SyncScope::ID SSID = NewValue ? SyncScope::SingleThread : SyncScope::System;
4106 
4107   if (AtomicRMWInst *I = dyn_cast<AtomicRMWInst>(P))
4108     return I->setSyncScopeID(SSID);
4109   return cast<AtomicCmpXchgInst>(P)->setSyncScopeID(SSID);
4110 }
4111 
4112 LLVMAtomicOrdering LLVMGetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst)  {
4113   Value *P = unwrap<Value>(CmpXchgInst);
4114   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getSuccessOrdering());
4115 }
4116 
4117 void LLVMSetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst,
4118                                    LLVMAtomicOrdering Ordering) {
4119   Value *P = unwrap<Value>(CmpXchgInst);
4120   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
4121 
4122   return cast<AtomicCmpXchgInst>(P)->setSuccessOrdering(O);
4123 }
4124 
4125 LLVMAtomicOrdering LLVMGetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst)  {
4126   Value *P = unwrap<Value>(CmpXchgInst);
4127   return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getFailureOrdering());
4128 }
4129 
4130 void LLVMSetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst,
4131                                    LLVMAtomicOrdering Ordering) {
4132   Value *P = unwrap<Value>(CmpXchgInst);
4133   AtomicOrdering O = mapFromLLVMOrdering(Ordering);
4134 
4135   return cast<AtomicCmpXchgInst>(P)->setFailureOrdering(O);
4136 }
4137 
4138 /*===-- Module providers --------------------------------------------------===*/
4139 
4140 LLVMModuleProviderRef
4141 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {
4142   return reinterpret_cast<LLVMModuleProviderRef>(M);
4143 }
4144 
4145 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {
4146   delete unwrap(MP);
4147 }
4148 
4149 
4150 /*===-- Memory buffers ----------------------------------------------------===*/
4151 
4152 LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(
4153     const char *Path,
4154     LLVMMemoryBufferRef *OutMemBuf,
4155     char **OutMessage) {
4156 
4157   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
4158   if (std::error_code EC = MBOrErr.getError()) {
4159     *OutMessage = strdup(EC.message().c_str());
4160     return 1;
4161   }
4162   *OutMemBuf = wrap(MBOrErr.get().release());
4163   return 0;
4164 }
4165 
4166 LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
4167                                          char **OutMessage) {
4168   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();
4169   if (std::error_code EC = MBOrErr.getError()) {
4170     *OutMessage = strdup(EC.message().c_str());
4171     return 1;
4172   }
4173   *OutMemBuf = wrap(MBOrErr.get().release());
4174   return 0;
4175 }
4176 
4177 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
4178     const char *InputData,
4179     size_t InputDataLength,
4180     const char *BufferName,
4181     LLVMBool RequiresNullTerminator) {
4182 
4183   return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength),
4184                                          StringRef(BufferName),
4185                                          RequiresNullTerminator).release());
4186 }
4187 
4188 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(
4189     const char *InputData,
4190     size_t InputDataLength,
4191     const char *BufferName) {
4192 
4193   return wrap(
4194       MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength),
4195                                      StringRef(BufferName)).release());
4196 }
4197 
4198 const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) {
4199   return unwrap(MemBuf)->getBufferStart();
4200 }
4201 
4202 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) {
4203   return unwrap(MemBuf)->getBufferSize();
4204 }
4205 
4206 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) {
4207   delete unwrap(MemBuf);
4208 }
4209 
4210 /*===-- Pass Registry -----------------------------------------------------===*/
4211 
4212 LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void) {
4213   return wrap(PassRegistry::getPassRegistry());
4214 }
4215 
4216 /*===-- Pass Manager ------------------------------------------------------===*/
4217 
4218 LLVMPassManagerRef LLVMCreatePassManager() {
4219   return wrap(new legacy::PassManager());
4220 }
4221 
4222 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
4223   return wrap(new legacy::FunctionPassManager(unwrap(M)));
4224 }
4225 
4226 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
4227   return LLVMCreateFunctionPassManagerForModule(
4228                                             reinterpret_cast<LLVMModuleRef>(P));
4229 }
4230 
4231 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
4232   return unwrap<legacy::PassManager>(PM)->run(*unwrap(M));
4233 }
4234 
4235 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
4236   return unwrap<legacy::FunctionPassManager>(FPM)->doInitialization();
4237 }
4238 
4239 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
4240   return unwrap<legacy::FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
4241 }
4242 
4243 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
4244   return unwrap<legacy::FunctionPassManager>(FPM)->doFinalization();
4245 }
4246 
4247 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
4248   delete unwrap(PM);
4249 }
4250 
4251 /*===-- Threading ------------------------------------------------------===*/
4252 
4253 LLVMBool LLVMStartMultithreaded() {
4254   return LLVMIsMultithreaded();
4255 }
4256 
4257 void LLVMStopMultithreaded() {
4258 }
4259 
4260 LLVMBool LLVMIsMultithreaded() {
4261   return llvm_is_multithreaded();
4262 }
4263