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