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