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