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