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