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