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