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