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