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