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