753d9c229eca19fbc026300be21c10a96e708f03
[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 // MetadataAsValue uses a canonical format which strips the actual MDNode for
567 // MDNode with just a single constant value, storing just a ConstantAsMetadata
568 // This undoes this canonicalization, reconstructing the MDNode.
569 static MDNode *extractMDNode(MetadataAsValue *MAV) {
570   Metadata *MD = MAV->getMetadata();
571   assert((isa<MDNode>(MD) || isa<ConstantAsMetadata>(MD)) &&
572       "Expected a metadata node or a canonicalized constant");
573
574   if (MDNode *N = dyn_cast<MDNode>(MD))
575     return N;
576
577   return MDNode::get(MAV->getContext(), MD);
578 }
579
580 void LLVMSetMetadata(LLVMValueRef Inst, unsigned KindID, LLVMValueRef Val) {
581   MDNode *N = Val ? extractMDNode(unwrap<MetadataAsValue>(Val)) : nullptr;
582
583   unwrap<Instruction>(Inst)->setMetadata(KindID, N);
584 }
585
586 /*--.. Conversion functions ................................................--*/
587
588 #define LLVM_DEFINE_VALUE_CAST(name)                                       \
589   LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                           \
590     return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \
591   }
592
593 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)
594
595 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {
596   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
597     if (isa<MDNode>(MD->getMetadata()) ||
598         isa<ValueAsMetadata>(MD->getMetadata()))
599       return Val;
600   return nullptr;
601 }
602
603 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) {
604   if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
605     if (isa<MDString>(MD->getMetadata()))
606       return Val;
607   return nullptr;
608 }
609
610 /*--.. Operations on Uses ..................................................--*/
611 LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val) {
612   Value *V = unwrap(Val);
613   Value::use_iterator I = V->use_begin();
614   if (I == V->use_end())
615     return nullptr;
616   return wrap(&*I);
617 }
618
619 LLVMUseRef LLVMGetNextUse(LLVMUseRef U) {
620   Use *Next = unwrap(U)->getNext();
621   if (Next)
622     return wrap(Next);
623   return nullptr;
624 }
625
626 LLVMValueRef LLVMGetUser(LLVMUseRef U) {
627   return wrap(unwrap(U)->getUser());
628 }
629
630 LLVMValueRef LLVMGetUsedValue(LLVMUseRef U) {
631   return wrap(unwrap(U)->get());
632 }
633
634 /*--.. Operations on Users .................................................--*/
635
636 static LLVMValueRef getMDNodeOperandImpl(LLVMContext &Context, const MDNode *N,
637                                          unsigned Index) {
638   Metadata *Op = N->getOperand(Index);
639   if (!Op)
640     return nullptr;
641   if (auto *C = dyn_cast<ConstantAsMetadata>(Op))
642     return wrap(C->getValue());
643   return wrap(MetadataAsValue::get(Context, Op));
644 }
645
646 LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index) {
647   Value *V = unwrap(Val);
648   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
649     if (auto *L = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
650       assert(Index == 0 && "Function-local metadata can only have one operand");
651       return wrap(L->getValue());
652     }
653     return getMDNodeOperandImpl(V->getContext(),
654                                 cast<MDNode>(MD->getMetadata()), Index);
655   }
656
657   return wrap(cast<User>(V)->getOperand(Index));
658 }
659
660 LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index) {
661   Value *V = unwrap(Val);
662   return wrap(&cast<User>(V)->getOperandUse(Index));
663 }
664
665 void LLVMSetOperand(LLVMValueRef Val, unsigned Index, LLVMValueRef Op) {
666   unwrap<User>(Val)->setOperand(Index, unwrap(Op));
667 }
668
669 int LLVMGetNumOperands(LLVMValueRef Val) {
670   Value *V = unwrap(Val);
671   if (isa<MetadataAsValue>(V))
672     return LLVMGetMDNodeNumOperands(Val);
673
674   return cast<User>(V)->getNumOperands();
675 }
676
677 /*--.. Operations on constants of any type .................................--*/
678
679 LLVMValueRef LLVMConstNull(LLVMTypeRef Ty) {
680   return wrap(Constant::getNullValue(unwrap(Ty)));
681 }
682
683 LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty) {
684   return wrap(Constant::getAllOnesValue(unwrap(Ty)));
685 }
686
687 LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty) {
688   return wrap(UndefValue::get(unwrap(Ty)));
689 }
690
691 LLVMBool LLVMIsConstant(LLVMValueRef Ty) {
692   return isa<Constant>(unwrap(Ty));
693 }
694
695 LLVMBool LLVMIsNull(LLVMValueRef Val) {
696   if (Constant *C = dyn_cast<Constant>(unwrap(Val)))
697     return C->isNullValue();
698   return false;
699 }
700
701 LLVMBool LLVMIsUndef(LLVMValueRef Val) {
702   return isa<UndefValue>(unwrap(Val));
703 }
704
705 LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty) {
706   return
707       wrap(ConstantPointerNull::get(unwrap<PointerType>(Ty)));
708 }
709
710 /*--.. Operations on metadata nodes ........................................--*/
711
712 LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
713                                    unsigned SLen) {
714   LLVMContext &Context = *unwrap(C);
715   return wrap(MetadataAsValue::get(
716       Context, MDString::get(Context, StringRef(Str, SLen))));
717 }
718
719 LLVMValueRef LLVMMDString(const char *Str, unsigned SLen) {
720   return LLVMMDStringInContext(LLVMGetGlobalContext(), Str, SLen);
721 }
722
723 LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
724                                  unsigned Count) {
725   LLVMContext &Context = *unwrap(C);
726   SmallVector<Metadata *, 8> MDs;
727   for (auto *OV : makeArrayRef(Vals, Count)) {
728     Value *V = unwrap(OV);
729     Metadata *MD;
730     if (!V)
731       MD = nullptr;
732     else if (auto *C = dyn_cast<Constant>(V))
733       MD = ConstantAsMetadata::get(C);
734     else if (auto *MDV = dyn_cast<MetadataAsValue>(V)) {
735       MD = MDV->getMetadata();
736       assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata "
737                                           "outside of direct argument to call");
738     } else {
739       // This is function-local metadata.  Pretend to make an MDNode.
740       assert(Count == 1 &&
741              "Expected only one operand to function-local metadata");
742       return wrap(MetadataAsValue::get(Context, LocalAsMetadata::get(V)));
743     }
744
745     MDs.push_back(MD);
746   }
747   return wrap(MetadataAsValue::get(Context, MDNode::get(Context, MDs)));
748 }
749
750 LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count) {
751   return LLVMMDNodeInContext(LLVMGetGlobalContext(), Vals, Count);
752 }
753
754 const char *LLVMGetMDString(LLVMValueRef V, unsigned* Len) {
755   if (const auto *MD = dyn_cast<MetadataAsValue>(unwrap(V)))
756     if (const MDString *S = dyn_cast<MDString>(MD->getMetadata())) {
757       *Len = S->getString().size();
758       return S->getString().data();
759     }
760   *Len = 0;
761   return nullptr;
762 }
763
764 unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V)
765 {
766   auto *MD = cast<MetadataAsValue>(unwrap(V));
767   if (isa<ValueAsMetadata>(MD->getMetadata()))
768     return 1;
769   return cast<MDNode>(MD->getMetadata())->getNumOperands();
770 }
771
772 void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest)
773 {
774   auto *MD = cast<MetadataAsValue>(unwrap(V));
775   if (auto *MDV = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {
776     *Dest = wrap(MDV->getValue());
777     return;
778   }
779   const auto *N = cast<MDNode>(MD->getMetadata());
780   const unsigned numOperands = N->getNumOperands();
781   LLVMContext &Context = unwrap(V)->getContext();
782   for (unsigned i = 0; i < numOperands; i++)
783     Dest[i] = getMDNodeOperandImpl(Context, N, i);
784 }
785
786 unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name)
787 {
788   if (NamedMDNode *N = unwrap(M)->getNamedMetadata(name)) {
789     return N->getNumOperands();
790   }
791   return 0;
792 }
793
794 void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMValueRef *Dest)
795 {
796   NamedMDNode *N = unwrap(M)->getNamedMetadata(name);
797   if (!N)
798     return;
799   LLVMContext &Context = unwrap(M)->getContext();
800   for (unsigned i=0;i<N->getNumOperands();i++)
801     Dest[i] = wrap(MetadataAsValue::get(Context, N->getOperand(i)));
802 }
803
804 void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name,
805                                  LLVMValueRef Val)
806 {
807   NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name);
808   if (!N)
809     return;
810   if (!Val)
811     return;
812   N->addOperand(extractMDNode(unwrap<MetadataAsValue>(Val)));
813 }
814
815 /*--.. Operations on scalar constants ......................................--*/
816
817 LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
818                           LLVMBool SignExtend) {
819   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), N, SignExtend != 0));
820 }
821
822 LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,
823                                               unsigned NumWords,
824                                               const uint64_t Words[]) {
825     IntegerType *Ty = unwrap<IntegerType>(IntTy);
826     return wrap(ConstantInt::get(Ty->getContext(),
827                                  APInt(Ty->getBitWidth(),
828                                        makeArrayRef(Words, NumWords))));
829 }
830
831 LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char Str[],
832                                   uint8_t Radix) {
833   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str),
834                                Radix));
835 }
836
837 LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char Str[],
838                                          unsigned SLen, uint8_t Radix) {
839   return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str, SLen),
840                                Radix));
841 }
842
843 LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N) {
844   return wrap(ConstantFP::get(unwrap(RealTy), N));
845 }
846
847 LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text) {
848   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Text)));
849 }
850
851 LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char Str[],
852                                           unsigned SLen) {
853   return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Str, SLen)));
854 }
855
856 unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal) {
857   return unwrap<ConstantInt>(ConstantVal)->getZExtValue();
858 }
859
860 long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal) {
861   return unwrap<ConstantInt>(ConstantVal)->getSExtValue();
862 }
863
864 double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *LosesInfo) {
865   ConstantFP *cFP = unwrap<ConstantFP>(ConstantVal) ;
866   Type *Ty = cFP->getType();
867
868   if (Ty->isFloatTy()) {
869     *LosesInfo = false;
870     return cFP->getValueAPF().convertToFloat();
871   }
872
873   if (Ty->isDoubleTy()) {
874     *LosesInfo = false;
875     return cFP->getValueAPF().convertToDouble();
876   }
877
878   bool APFLosesInfo;
879   APFloat APF = cFP->getValueAPF();
880   APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &APFLosesInfo);
881   *LosesInfo = APFLosesInfo;
882   return APF.convertToDouble();
883 }
884
885 /*--.. Operations on composite constants ...................................--*/
886
887 LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,
888                                       unsigned Length,
889                                       LLVMBool DontNullTerminate) {
890   /* Inverted the sense of AddNull because ', 0)' is a
891      better mnemonic for null termination than ', 1)'. */
892   return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),
893                                            DontNullTerminate == 0));
894 }
895 LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
896                                       LLVMValueRef *ConstantVals,
897                                       unsigned Count, LLVMBool Packed) {
898   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
899   return wrap(ConstantStruct::getAnon(*unwrap(C), makeArrayRef(Elements, Count),
900                                       Packed != 0));
901 }
902
903 LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
904                              LLVMBool DontNullTerminate) {
905   return LLVMConstStringInContext(LLVMGetGlobalContext(), Str, Length,
906                                   DontNullTerminate);
907 }
908
909 LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef c, unsigned idx) {
910   return wrap(static_cast<ConstantDataSequential*>(unwrap(c))->getElementAsConstant(idx));
911 }
912
913 LLVMBool LLVMIsConstantString(LLVMValueRef c) {
914   return static_cast<ConstantDataSequential*>(unwrap(c))->isString();
915 }
916
917 const char *LLVMGetAsString(LLVMValueRef c, size_t* Length) {
918   StringRef str = static_cast<ConstantDataSequential*>(unwrap(c))->getAsString();
919   *Length = str.size();
920   return str.data();
921 }
922
923 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
924                             LLVMValueRef *ConstantVals, unsigned Length) {
925   ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length);
926   return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));
927 }
928
929 LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
930                              LLVMBool Packed) {
931   return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count,
932                                   Packed);
933 }
934
935 LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
936                                   LLVMValueRef *ConstantVals,
937                                   unsigned Count) {
938   Constant **Elements = unwrap<Constant>(ConstantVals, Count);
939   StructType *Ty = cast<StructType>(unwrap(StructTy));
940
941   return wrap(ConstantStruct::get(Ty, makeArrayRef(Elements, Count)));
942 }
943
944 LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) {
945   return wrap(ConstantVector::get(makeArrayRef(
946                             unwrap<Constant>(ScalarConstantVals, Size), Size)));
947 }
948
949 /*-- Opcode mapping */
950
951 static LLVMOpcode map_to_llvmopcode(int opcode)
952 {
953     switch (opcode) {
954       default: llvm_unreachable("Unhandled Opcode.");
955 #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;
956 #include "llvm/IR/Instruction.def"
957 #undef HANDLE_INST
958     }
959 }
960
961 static int map_from_llvmopcode(LLVMOpcode code)
962 {
963     switch (code) {
964 #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;
965 #include "llvm/IR/Instruction.def"
966 #undef HANDLE_INST
967     }
968     llvm_unreachable("Unhandled Opcode.");
969 }
970
971 /*--.. Constant expressions ................................................--*/
972
973 LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) {
974   return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode());
975 }
976
977 LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) {
978   return wrap(ConstantExpr::getAlignOf(unwrap(Ty)));
979 }
980
981 LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) {
982   return wrap(ConstantExpr::getSizeOf(unwrap(Ty)));
983 }
984
985 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) {
986   return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));
987 }
988
989 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) {
990   return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal)));
991 }
992
993 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) {
994   return wrap(ConstantExpr::getNUWNeg(unwrap<Constant>(ConstantVal)));
995 }
996
997
998 LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal) {
999   return wrap(ConstantExpr::getFNeg(unwrap<Constant>(ConstantVal)));
1000 }
1001
1002 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) {
1003   return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal)));
1004 }
1005
1006 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1007   return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant),
1008                                    unwrap<Constant>(RHSConstant)));
1009 }
1010
1011 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant,
1012                              LLVMValueRef RHSConstant) {
1013   return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant),
1014                                       unwrap<Constant>(RHSConstant)));
1015 }
1016
1017 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant,
1018                              LLVMValueRef RHSConstant) {
1019   return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant),
1020                                       unwrap<Constant>(RHSConstant)));
1021 }
1022
1023 LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1024   return wrap(ConstantExpr::getFAdd(unwrap<Constant>(LHSConstant),
1025                                     unwrap<Constant>(RHSConstant)));
1026 }
1027
1028 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1029   return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant),
1030                                    unwrap<Constant>(RHSConstant)));
1031 }
1032
1033 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant,
1034                              LLVMValueRef RHSConstant) {
1035   return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant),
1036                                       unwrap<Constant>(RHSConstant)));
1037 }
1038
1039 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant,
1040                              LLVMValueRef RHSConstant) {
1041   return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant),
1042                                       unwrap<Constant>(RHSConstant)));
1043 }
1044
1045 LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1046   return wrap(ConstantExpr::getFSub(unwrap<Constant>(LHSConstant),
1047                                     unwrap<Constant>(RHSConstant)));
1048 }
1049
1050 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1051   return wrap(ConstantExpr::getMul(unwrap<Constant>(LHSConstant),
1052                                    unwrap<Constant>(RHSConstant)));
1053 }
1054
1055 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant,
1056                              LLVMValueRef RHSConstant) {
1057   return wrap(ConstantExpr::getNSWMul(unwrap<Constant>(LHSConstant),
1058                                       unwrap<Constant>(RHSConstant)));
1059 }
1060
1061 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant,
1062                              LLVMValueRef RHSConstant) {
1063   return wrap(ConstantExpr::getNUWMul(unwrap<Constant>(LHSConstant),
1064                                       unwrap<Constant>(RHSConstant)));
1065 }
1066
1067 LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1068   return wrap(ConstantExpr::getFMul(unwrap<Constant>(LHSConstant),
1069                                     unwrap<Constant>(RHSConstant)));
1070 }
1071
1072 LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1073   return wrap(ConstantExpr::getUDiv(unwrap<Constant>(LHSConstant),
1074                                     unwrap<Constant>(RHSConstant)));
1075 }
1076
1077 LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1078   return wrap(ConstantExpr::getSDiv(unwrap<Constant>(LHSConstant),
1079                                     unwrap<Constant>(RHSConstant)));
1080 }
1081
1082 LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant,
1083                                 LLVMValueRef RHSConstant) {
1084   return wrap(ConstantExpr::getExactSDiv(unwrap<Constant>(LHSConstant),
1085                                          unwrap<Constant>(RHSConstant)));
1086 }
1087
1088 LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1089   return wrap(ConstantExpr::getFDiv(unwrap<Constant>(LHSConstant),
1090                                     unwrap<Constant>(RHSConstant)));
1091 }
1092
1093 LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1094   return wrap(ConstantExpr::getURem(unwrap<Constant>(LHSConstant),
1095                                     unwrap<Constant>(RHSConstant)));
1096 }
1097
1098 LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1099   return wrap(ConstantExpr::getSRem(unwrap<Constant>(LHSConstant),
1100                                     unwrap<Constant>(RHSConstant)));
1101 }
1102
1103 LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1104   return wrap(ConstantExpr::getFRem(unwrap<Constant>(LHSConstant),
1105                                     unwrap<Constant>(RHSConstant)));
1106 }
1107
1108 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1109   return wrap(ConstantExpr::getAnd(unwrap<Constant>(LHSConstant),
1110                                    unwrap<Constant>(RHSConstant)));
1111 }
1112
1113 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1114   return wrap(ConstantExpr::getOr(unwrap<Constant>(LHSConstant),
1115                                   unwrap<Constant>(RHSConstant)));
1116 }
1117
1118 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1119   return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant),
1120                                    unwrap<Constant>(RHSConstant)));
1121 }
1122
1123 LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate,
1124                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1125   return wrap(ConstantExpr::getICmp(Predicate,
1126                                     unwrap<Constant>(LHSConstant),
1127                                     unwrap<Constant>(RHSConstant)));
1128 }
1129
1130 LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
1131                            LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1132   return wrap(ConstantExpr::getFCmp(Predicate,
1133                                     unwrap<Constant>(LHSConstant),
1134                                     unwrap<Constant>(RHSConstant)));
1135 }
1136
1137 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1138   return wrap(ConstantExpr::getShl(unwrap<Constant>(LHSConstant),
1139                                    unwrap<Constant>(RHSConstant)));
1140 }
1141
1142 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1143   return wrap(ConstantExpr::getLShr(unwrap<Constant>(LHSConstant),
1144                                     unwrap<Constant>(RHSConstant)));
1145 }
1146
1147 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {
1148   return wrap(ConstantExpr::getAShr(unwrap<Constant>(LHSConstant),
1149                                     unwrap<Constant>(RHSConstant)));
1150 }
1151
1152 LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
1153                           LLVMValueRef *ConstantIndices, unsigned NumIndices) {
1154   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1155                                NumIndices);
1156   return wrap(ConstantExpr::getGetElementPtr(unwrap<Constant>(ConstantVal),
1157                                              IdxList));
1158 }
1159
1160 LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
1161                                   LLVMValueRef *ConstantIndices,
1162                                   unsigned NumIndices) {
1163   Constant* Val = unwrap<Constant>(ConstantVal);
1164   ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),
1165                                NumIndices);
1166   return wrap(ConstantExpr::getInBoundsGetElementPtr(Val, IdxList));
1167 }
1168
1169 LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1170   return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal),
1171                                      unwrap(ToType)));
1172 }
1173
1174 LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1175   return wrap(ConstantExpr::getSExt(unwrap<Constant>(ConstantVal),
1176                                     unwrap(ToType)));
1177 }
1178
1179 LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1180   return wrap(ConstantExpr::getZExt(unwrap<Constant>(ConstantVal),
1181                                     unwrap(ToType)));
1182 }
1183
1184 LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1185   return wrap(ConstantExpr::getFPTrunc(unwrap<Constant>(ConstantVal),
1186                                        unwrap(ToType)));
1187 }
1188
1189 LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1190   return wrap(ConstantExpr::getFPExtend(unwrap<Constant>(ConstantVal),
1191                                         unwrap(ToType)));
1192 }
1193
1194 LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1195   return wrap(ConstantExpr::getUIToFP(unwrap<Constant>(ConstantVal),
1196                                       unwrap(ToType)));
1197 }
1198
1199 LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1200   return wrap(ConstantExpr::getSIToFP(unwrap<Constant>(ConstantVal),
1201                                       unwrap(ToType)));
1202 }
1203
1204 LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1205   return wrap(ConstantExpr::getFPToUI(unwrap<Constant>(ConstantVal),
1206                                       unwrap(ToType)));
1207 }
1208
1209 LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1210   return wrap(ConstantExpr::getFPToSI(unwrap<Constant>(ConstantVal),
1211                                       unwrap(ToType)));
1212 }
1213
1214 LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1215   return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal),
1216                                         unwrap(ToType)));
1217 }
1218
1219 LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1220   return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal),
1221                                         unwrap(ToType)));
1222 }
1223
1224 LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1225   return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal),
1226                                        unwrap(ToType)));
1227 }
1228
1229 LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal,
1230                                     LLVMTypeRef ToType) {
1231   return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal),
1232                                              unwrap(ToType)));
1233 }
1234
1235 LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal,
1236                                     LLVMTypeRef ToType) {
1237   return wrap(ConstantExpr::getZExtOrBitCast(unwrap<Constant>(ConstantVal),
1238                                              unwrap(ToType)));
1239 }
1240
1241 LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal,
1242                                     LLVMTypeRef ToType) {
1243   return wrap(ConstantExpr::getSExtOrBitCast(unwrap<Constant>(ConstantVal),
1244                                              unwrap(ToType)));
1245 }
1246
1247 LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,
1248                                      LLVMTypeRef ToType) {
1249   return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal),
1250                                               unwrap(ToType)));
1251 }
1252
1253 LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
1254                                   LLVMTypeRef ToType) {
1255   return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal),
1256                                            unwrap(ToType)));
1257 }
1258
1259 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
1260                               LLVMBool isSigned) {
1261   return wrap(ConstantExpr::getIntegerCast(unwrap<Constant>(ConstantVal),
1262                                            unwrap(ToType), isSigned));
1263 }
1264
1265 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {
1266   return wrap(ConstantExpr::getFPCast(unwrap<Constant>(ConstantVal),
1267                                       unwrap(ToType)));
1268 }
1269
1270 LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
1271                              LLVMValueRef ConstantIfTrue,
1272                              LLVMValueRef ConstantIfFalse) {
1273   return wrap(ConstantExpr::getSelect(unwrap<Constant>(ConstantCondition),
1274                                       unwrap<Constant>(ConstantIfTrue),
1275                                       unwrap<Constant>(ConstantIfFalse)));
1276 }
1277
1278 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
1279                                      LLVMValueRef IndexConstant) {
1280   return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant),
1281                                               unwrap<Constant>(IndexConstant)));
1282 }
1283
1284 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
1285                                     LLVMValueRef ElementValueConstant,
1286                                     LLVMValueRef IndexConstant) {
1287   return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant),
1288                                          unwrap<Constant>(ElementValueConstant),
1289                                              unwrap<Constant>(IndexConstant)));
1290 }
1291
1292 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
1293                                     LLVMValueRef VectorBConstant,
1294                                     LLVMValueRef MaskConstant) {
1295   return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant),
1296                                              unwrap<Constant>(VectorBConstant),
1297                                              unwrap<Constant>(MaskConstant)));
1298 }
1299
1300 LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList,
1301                                    unsigned NumIdx) {
1302   return wrap(ConstantExpr::getExtractValue(unwrap<Constant>(AggConstant),
1303                                             makeArrayRef(IdxList, NumIdx)));
1304 }
1305
1306 LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant,
1307                                   LLVMValueRef ElementValueConstant,
1308                                   unsigned *IdxList, unsigned NumIdx) {
1309   return wrap(ConstantExpr::getInsertValue(unwrap<Constant>(AggConstant),
1310                                          unwrap<Constant>(ElementValueConstant),
1311                                            makeArrayRef(IdxList, NumIdx)));
1312 }
1313
1314 LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString,
1315                                 const char *Constraints,
1316                                 LLVMBool HasSideEffects,
1317                                 LLVMBool IsAlignStack) {
1318   return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString,
1319                              Constraints, HasSideEffects, IsAlignStack));
1320 }
1321
1322 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) {
1323   return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB)));
1324 }
1325
1326 /*--.. Operations on global variables, functions, and aliases (globals) ....--*/
1327
1328 LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) {
1329   return wrap(unwrap<GlobalValue>(Global)->getParent());
1330 }
1331
1332 LLVMBool LLVMIsDeclaration(LLVMValueRef Global) {
1333   return unwrap<GlobalValue>(Global)->isDeclaration();
1334 }
1335
1336 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {
1337   switch (unwrap<GlobalValue>(Global)->getLinkage()) {
1338   case GlobalValue::ExternalLinkage:
1339     return LLVMExternalLinkage;
1340   case GlobalValue::AvailableExternallyLinkage:
1341     return LLVMAvailableExternallyLinkage;
1342   case GlobalValue::LinkOnceAnyLinkage:
1343     return LLVMLinkOnceAnyLinkage;
1344   case GlobalValue::LinkOnceODRLinkage:
1345     return LLVMLinkOnceODRLinkage;
1346   case GlobalValue::WeakAnyLinkage:
1347     return LLVMWeakAnyLinkage;
1348   case GlobalValue::WeakODRLinkage:
1349     return LLVMWeakODRLinkage;
1350   case GlobalValue::AppendingLinkage:
1351     return LLVMAppendingLinkage;
1352   case GlobalValue::InternalLinkage:
1353     return LLVMInternalLinkage;
1354   case GlobalValue::PrivateLinkage:
1355     return LLVMPrivateLinkage;
1356   case GlobalValue::ExternalWeakLinkage:
1357     return LLVMExternalWeakLinkage;
1358   case GlobalValue::CommonLinkage:
1359     return LLVMCommonLinkage;
1360   }
1361
1362   llvm_unreachable("Invalid GlobalValue linkage!");
1363 }
1364
1365 void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {
1366   GlobalValue *GV = unwrap<GlobalValue>(Global);
1367
1368   switch (Linkage) {
1369   case LLVMExternalLinkage:
1370     GV->setLinkage(GlobalValue::ExternalLinkage);
1371     break;
1372   case LLVMAvailableExternallyLinkage:
1373     GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1374     break;
1375   case LLVMLinkOnceAnyLinkage:
1376     GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
1377     break;
1378   case LLVMLinkOnceODRLinkage:
1379     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
1380     break;
1381   case LLVMLinkOnceODRAutoHideLinkage:
1382     DEBUG(errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no "
1383                     "longer supported.");
1384     break;
1385   case LLVMWeakAnyLinkage:
1386     GV->setLinkage(GlobalValue::WeakAnyLinkage);
1387     break;
1388   case LLVMWeakODRLinkage:
1389     GV->setLinkage(GlobalValue::WeakODRLinkage);
1390     break;
1391   case LLVMAppendingLinkage:
1392     GV->setLinkage(GlobalValue::AppendingLinkage);
1393     break;
1394   case LLVMInternalLinkage:
1395     GV->setLinkage(GlobalValue::InternalLinkage);
1396     break;
1397   case LLVMPrivateLinkage:
1398     GV->setLinkage(GlobalValue::PrivateLinkage);
1399     break;
1400   case LLVMLinkerPrivateLinkage:
1401     GV->setLinkage(GlobalValue::PrivateLinkage);
1402     break;
1403   case LLVMLinkerPrivateWeakLinkage:
1404     GV->setLinkage(GlobalValue::PrivateLinkage);
1405     break;
1406   case LLVMDLLImportLinkage:
1407     DEBUG(errs()
1408           << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported.");
1409     break;
1410   case LLVMDLLExportLinkage:
1411     DEBUG(errs()
1412           << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported.");
1413     break;
1414   case LLVMExternalWeakLinkage:
1415     GV->setLinkage(GlobalValue::ExternalWeakLinkage);
1416     break;
1417   case LLVMGhostLinkage:
1418     DEBUG(errs()
1419           << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");
1420     break;
1421   case LLVMCommonLinkage:
1422     GV->setLinkage(GlobalValue::CommonLinkage);
1423     break;
1424   }
1425 }
1426
1427 const char *LLVMGetSection(LLVMValueRef Global) {
1428   return unwrap<GlobalValue>(Global)->getSection();
1429 }
1430
1431 void LLVMSetSection(LLVMValueRef Global, const char *Section) {
1432   unwrap<GlobalObject>(Global)->setSection(Section);
1433 }
1434
1435 LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) {
1436   return static_cast<LLVMVisibility>(
1437     unwrap<GlobalValue>(Global)->getVisibility());
1438 }
1439
1440 void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) {
1441   unwrap<GlobalValue>(Global)
1442     ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz));
1443 }
1444
1445 LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) {
1446   return static_cast<LLVMDLLStorageClass>(
1447       unwrap<GlobalValue>(Global)->getDLLStorageClass());
1448 }
1449
1450 void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) {
1451   unwrap<GlobalValue>(Global)->setDLLStorageClass(
1452       static_cast<GlobalValue::DLLStorageClassTypes>(Class));
1453 }
1454
1455 LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) {
1456   return unwrap<GlobalValue>(Global)->hasUnnamedAddr();
1457 }
1458
1459 void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) {
1460   unwrap<GlobalValue>(Global)->setUnnamedAddr(HasUnnamedAddr);
1461 }
1462
1463 /*--.. Operations on global variables, load and store instructions .........--*/
1464
1465 unsigned LLVMGetAlignment(LLVMValueRef V) {
1466   Value *P = unwrap<Value>(V);
1467   if (GlobalValue *GV = dyn_cast<GlobalValue>(P))
1468     return GV->getAlignment();
1469   if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
1470     return AI->getAlignment();
1471   if (LoadInst *LI = dyn_cast<LoadInst>(P))
1472     return LI->getAlignment();
1473   if (StoreInst *SI = dyn_cast<StoreInst>(P))
1474     return SI->getAlignment();
1475
1476   llvm_unreachable(
1477       "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment");
1478 }
1479
1480 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) {
1481   Value *P = unwrap<Value>(V);
1482   if (GlobalObject *GV = dyn_cast<GlobalObject>(P))
1483     GV->setAlignment(Bytes);
1484   else if (AllocaInst *AI = dyn_cast<AllocaInst>(P))
1485     AI->setAlignment(Bytes);
1486   else if (LoadInst *LI = dyn_cast<LoadInst>(P))
1487     LI->setAlignment(Bytes);
1488   else if (StoreInst *SI = dyn_cast<StoreInst>(P))
1489     SI->setAlignment(Bytes);
1490   else
1491     llvm_unreachable(
1492         "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment");
1493 }
1494
1495 /*--.. Operations on global variables ......................................--*/
1496
1497 LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) {
1498   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
1499                                  GlobalValue::ExternalLinkage, nullptr, Name));
1500 }
1501
1502 LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
1503                                          const char *Name,
1504                                          unsigned AddressSpace) {
1505   return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
1506                                  GlobalValue::ExternalLinkage, nullptr, Name,
1507                                  nullptr, GlobalVariable::NotThreadLocal,
1508                                  AddressSpace));
1509 }
1510
1511 LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) {
1512   return wrap(unwrap(M)->getNamedGlobal(Name));
1513 }
1514
1515 LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) {
1516   Module *Mod = unwrap(M);
1517   Module::global_iterator I = Mod->global_begin();
1518   if (I == Mod->global_end())
1519     return nullptr;
1520   return wrap(I);
1521 }
1522
1523 LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
1524   Module *Mod = unwrap(M);
1525   Module::global_iterator I = Mod->global_end();
1526   if (I == Mod->global_begin())
1527     return nullptr;
1528   return wrap(--I);
1529 }
1530
1531 LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
1532   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
1533   Module::global_iterator I = GV;
1534   if (++I == GV->getParent()->global_end())
1535     return nullptr;
1536   return wrap(I);
1537 }
1538
1539 LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
1540   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
1541   Module::global_iterator I = GV;
1542   if (I == GV->getParent()->global_begin())
1543     return nullptr;
1544   return wrap(--I);
1545 }
1546
1547 void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
1548   unwrap<GlobalVariable>(GlobalVar)->eraseFromParent();
1549 }
1550
1551 LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
1552   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
1553   if ( !GV->hasInitializer() )
1554     return nullptr;
1555   return wrap(GV->getInitializer());
1556 }
1557
1558 void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) {
1559   unwrap<GlobalVariable>(GlobalVar)
1560     ->setInitializer(unwrap<Constant>(ConstantVal));
1561 }
1562
1563 LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) {
1564   return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal();
1565 }
1566
1567 void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) {
1568   unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0);
1569 }
1570
1571 LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) {
1572   return unwrap<GlobalVariable>(GlobalVar)->isConstant();
1573 }
1574
1575 void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) {
1576   unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0);
1577 }
1578
1579 LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) {
1580   switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) {
1581   case GlobalVariable::NotThreadLocal:
1582     return LLVMNotThreadLocal;
1583   case GlobalVariable::GeneralDynamicTLSModel:
1584     return LLVMGeneralDynamicTLSModel;
1585   case GlobalVariable::LocalDynamicTLSModel:
1586     return LLVMLocalDynamicTLSModel;
1587   case GlobalVariable::InitialExecTLSModel:
1588     return LLVMInitialExecTLSModel;
1589   case GlobalVariable::LocalExecTLSModel:
1590     return LLVMLocalExecTLSModel;
1591   }
1592
1593   llvm_unreachable("Invalid GlobalVariable thread local mode");
1594 }
1595
1596 void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) {
1597   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
1598
1599   switch (Mode) {
1600   case LLVMNotThreadLocal:
1601     GV->setThreadLocalMode(GlobalVariable::NotThreadLocal);
1602     break;
1603   case LLVMGeneralDynamicTLSModel:
1604     GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel);
1605     break;
1606   case LLVMLocalDynamicTLSModel:
1607     GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel);
1608     break;
1609   case LLVMInitialExecTLSModel:
1610     GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1611     break;
1612   case LLVMLocalExecTLSModel:
1613     GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel);
1614     break;
1615   }
1616 }
1617
1618 LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) {
1619   return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized();
1620 }
1621
1622 void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) {
1623   unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit);
1624 }
1625
1626 /*--.. Operations on aliases ......................................--*/
1627
1628 LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
1629                           const char *Name) {
1630   auto *PTy = cast<PointerType>(unwrap(Ty));
1631   return wrap(GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1632                                   GlobalValue::ExternalLinkage, Name,
1633                                   unwrap<GlobalObject>(Aliasee), unwrap(M)));
1634 }
1635
1636 /*--.. Operations on functions .............................................--*/
1637
1638 LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
1639                              LLVMTypeRef FunctionTy) {
1640   return wrap(Function::Create(unwrap<FunctionType>(FunctionTy),
1641                                GlobalValue::ExternalLinkage, Name, unwrap(M)));
1642 }
1643
1644 LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) {
1645   return wrap(unwrap(M)->getFunction(Name));
1646 }
1647
1648 LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) {
1649   Module *Mod = unwrap(M);
1650   Module::iterator I = Mod->begin();
1651   if (I == Mod->end())
1652     return nullptr;
1653   return wrap(I);
1654 }
1655
1656 LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
1657   Module *Mod = unwrap(M);
1658   Module::iterator I = Mod->end();
1659   if (I == Mod->begin())
1660     return nullptr;
1661   return wrap(--I);
1662 }
1663
1664 LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
1665   Function *Func = unwrap<Function>(Fn);
1666   Module::iterator I = Func;
1667   if (++I == Func->getParent()->end())
1668     return nullptr;
1669   return wrap(I);
1670 }
1671
1672 LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
1673   Function *Func = unwrap<Function>(Fn);
1674   Module::iterator I = Func;
1675   if (I == Func->getParent()->begin())
1676     return nullptr;
1677   return wrap(--I);
1678 }
1679
1680 void LLVMDeleteFunction(LLVMValueRef Fn) {
1681   unwrap<Function>(Fn)->eraseFromParent();
1682 }
1683
1684 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
1685   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
1686     return F->getIntrinsicID();
1687   return 0;
1688 }
1689
1690 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {
1691   return unwrap<Function>(Fn)->getCallingConv();
1692 }
1693
1694 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) {
1695   return unwrap<Function>(Fn)->setCallingConv(
1696     static_cast<CallingConv::ID>(CC));
1697 }
1698
1699 const char *LLVMGetGC(LLVMValueRef Fn) {
1700   Function *F = unwrap<Function>(Fn);
1701   return F->hasGC()? F->getGC() : nullptr;
1702 }
1703
1704 void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
1705   Function *F = unwrap<Function>(Fn);
1706   if (GC)
1707     F->setGC(GC);
1708   else
1709     F->clearGC();
1710 }
1711
1712 void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) {
1713   Function *Func = unwrap<Function>(Fn);
1714   const AttributeSet PAL = Func->getAttributes();
1715   AttrBuilder B(PA);
1716   const AttributeSet PALnew =
1717     PAL.addAttributes(Func->getContext(), AttributeSet::FunctionIndex,
1718                       AttributeSet::get(Func->getContext(),
1719                                         AttributeSet::FunctionIndex, B));
1720   Func->setAttributes(PALnew);
1721 }
1722
1723 void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A,
1724                                         const char *V) {
1725   Function *Func = unwrap<Function>(Fn);
1726   AttributeSet::AttrIndex Idx =
1727     AttributeSet::AttrIndex(AttributeSet::FunctionIndex);
1728   AttrBuilder B;
1729
1730   B.addAttribute(A, V);
1731   AttributeSet Set = AttributeSet::get(Func->getContext(), Idx, B);
1732   Func->addAttributes(Idx, Set);
1733 }
1734
1735 void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) {
1736   Function *Func = unwrap<Function>(Fn);
1737   const AttributeSet PAL = Func->getAttributes();
1738   AttrBuilder B(PA);
1739   const AttributeSet PALnew =
1740     PAL.removeAttributes(Func->getContext(), AttributeSet::FunctionIndex,
1741                          AttributeSet::get(Func->getContext(),
1742                                            AttributeSet::FunctionIndex, B));
1743   Func->setAttributes(PALnew);
1744 }
1745
1746 LLVMAttribute LLVMGetFunctionAttr(LLVMValueRef Fn) {
1747   Function *Func = unwrap<Function>(Fn);
1748   const AttributeSet PAL = Func->getAttributes();
1749   return (LLVMAttribute)PAL.Raw(AttributeSet::FunctionIndex);
1750 }
1751
1752 /*--.. Operations on parameters ............................................--*/
1753
1754 unsigned LLVMCountParams(LLVMValueRef FnRef) {
1755   // This function is strictly redundant to
1756   //   LLVMCountParamTypes(LLVMGetElementType(LLVMTypeOf(FnRef)))
1757   return unwrap<Function>(FnRef)->arg_size();
1758 }
1759
1760 void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) {
1761   Function *Fn = unwrap<Function>(FnRef);
1762   for (Function::arg_iterator I = Fn->arg_begin(),
1763                               E = Fn->arg_end(); I != E; I++)
1764     *ParamRefs++ = wrap(I);
1765 }
1766
1767 LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
1768   Function::arg_iterator AI = unwrap<Function>(FnRef)->arg_begin();
1769   while (index --> 0)
1770     AI++;
1771   return wrap(AI);
1772 }
1773
1774 LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
1775   return wrap(unwrap<Argument>(V)->getParent());
1776 }
1777
1778 LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) {
1779   Function *Func = unwrap<Function>(Fn);
1780   Function::arg_iterator I = Func->arg_begin();
1781   if (I == Func->arg_end())
1782     return nullptr;
1783   return wrap(I);
1784 }
1785
1786 LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
1787   Function *Func = unwrap<Function>(Fn);
1788   Function::arg_iterator I = Func->arg_end();
1789   if (I == Func->arg_begin())
1790     return nullptr;
1791   return wrap(--I);
1792 }
1793
1794 LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
1795   Argument *A = unwrap<Argument>(Arg);
1796   Function::arg_iterator I = A;
1797   if (++I == A->getParent()->arg_end())
1798     return nullptr;
1799   return wrap(I);
1800 }
1801
1802 LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
1803   Argument *A = unwrap<Argument>(Arg);
1804   Function::arg_iterator I = A;
1805   if (I == A->getParent()->arg_begin())
1806     return nullptr;
1807   return wrap(--I);
1808 }
1809
1810 void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
1811   Argument *A = unwrap<Argument>(Arg);
1812   AttrBuilder B(PA);
1813   A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1,  B));
1814 }
1815
1816 void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
1817   Argument *A = unwrap<Argument>(Arg);
1818   AttrBuilder B(PA);
1819   A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1,  B));
1820 }
1821
1822 LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg) {
1823   Argument *A = unwrap<Argument>(Arg);
1824   return (LLVMAttribute)A->getParent()->getAttributes().
1825     Raw(A->getArgNo()+1);
1826 }
1827
1828
1829 void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) {
1830   Argument *A = unwrap<Argument>(Arg);
1831   AttrBuilder B;
1832   B.addAlignmentAttr(align);
1833   A->addAttr(AttributeSet::get(A->getContext(),A->getArgNo() + 1, B));
1834 }
1835
1836 /*--.. Operations on basic blocks ..........................................--*/
1837
1838 LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) {
1839   return wrap(static_cast<Value*>(unwrap(BB)));
1840 }
1841
1842 LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) {
1843   return isa<BasicBlock>(unwrap(Val));
1844 }
1845
1846 LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) {
1847   return wrap(unwrap<BasicBlock>(Val));
1848 }
1849
1850 LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) {
1851   return wrap(unwrap(BB)->getParent());
1852 }
1853
1854 LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) {
1855   return wrap(unwrap(BB)->getTerminator());
1856 }
1857
1858 unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) {
1859   return unwrap<Function>(FnRef)->size();
1860 }
1861
1862 void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
1863   Function *Fn = unwrap<Function>(FnRef);
1864   for (Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++)
1865     *BasicBlocksRefs++ = wrap(I);
1866 }
1867
1868 LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
1869   return wrap(&unwrap<Function>(Fn)->getEntryBlock());
1870 }
1871
1872 LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) {
1873   Function *Func = unwrap<Function>(Fn);
1874   Function::iterator I = Func->begin();
1875   if (I == Func->end())
1876     return nullptr;
1877   return wrap(I);
1878 }
1879
1880 LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
1881   Function *Func = unwrap<Function>(Fn);
1882   Function::iterator I = Func->end();
1883   if (I == Func->begin())
1884     return nullptr;
1885   return wrap(--I);
1886 }
1887
1888 LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
1889   BasicBlock *Block = unwrap(BB);
1890   Function::iterator I = Block;
1891   if (++I == Block->getParent()->end())
1892     return nullptr;
1893   return wrap(I);
1894 }
1895
1896 LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
1897   BasicBlock *Block = unwrap(BB);
1898   Function::iterator I = Block;
1899   if (I == Block->getParent()->begin())
1900     return nullptr;
1901   return wrap(--I);
1902 }
1903
1904 LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
1905                                                 LLVMValueRef FnRef,
1906                                                 const char *Name) {
1907   return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef)));
1908 }
1909
1910 LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) {
1911   return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name);
1912 }
1913
1914 LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
1915                                                 LLVMBasicBlockRef BBRef,
1916                                                 const char *Name) {
1917   BasicBlock *BB = unwrap(BBRef);
1918   return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB));
1919 }
1920
1921 LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef,
1922                                        const char *Name) {
1923   return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name);
1924 }
1925
1926 void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) {
1927   unwrap(BBRef)->eraseFromParent();
1928 }
1929
1930 void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) {
1931   unwrap(BBRef)->removeFromParent();
1932 }
1933
1934 void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
1935   unwrap(BB)->moveBefore(unwrap(MovePos));
1936 }
1937
1938 void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {
1939   unwrap(BB)->moveAfter(unwrap(MovePos));
1940 }
1941
1942 /*--.. Operations on instructions ..........................................--*/
1943
1944 LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) {
1945   return wrap(unwrap<Instruction>(Inst)->getParent());
1946 }
1947
1948 LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) {
1949   BasicBlock *Block = unwrap(BB);
1950   BasicBlock::iterator I = Block->begin();
1951   if (I == Block->end())
1952     return nullptr;
1953   return wrap(I);
1954 }
1955
1956 LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
1957   BasicBlock *Block = unwrap(BB);
1958   BasicBlock::iterator I = Block->end();
1959   if (I == Block->begin())
1960     return nullptr;
1961   return wrap(--I);
1962 }
1963
1964 LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
1965   Instruction *Instr = unwrap<Instruction>(Inst);
1966   BasicBlock::iterator I = Instr;
1967   if (++I == Instr->getParent()->end())
1968     return nullptr;
1969   return wrap(I);
1970 }
1971
1972 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
1973   Instruction *Instr = unwrap<Instruction>(Inst);
1974   BasicBlock::iterator I = Instr;
1975   if (I == Instr->getParent()->begin())
1976     return nullptr;
1977   return wrap(--I);
1978 }
1979
1980 void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
1981   unwrap<Instruction>(Inst)->eraseFromParent();
1982 }
1983
1984 LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) {
1985   if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst)))
1986     return (LLVMIntPredicate)I->getPredicate();
1987   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
1988     if (CE->getOpcode() == Instruction::ICmp)
1989       return (LLVMIntPredicate)CE->getPredicate();
1990   return (LLVMIntPredicate)0;
1991 }
1992
1993 LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) {
1994   if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst)))
1995     return (LLVMRealPredicate)I->getPredicate();
1996   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst)))
1997     if (CE->getOpcode() == Instruction::FCmp)
1998       return (LLVMRealPredicate)CE->getPredicate();
1999   return (LLVMRealPredicate)0;
2000 }
2001
2002 LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) {
2003   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2004     return map_to_llvmopcode(C->getOpcode());
2005   return (LLVMOpcode)0;
2006 }
2007
2008 LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) {
2009   if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))
2010     return wrap(C->clone());
2011   return nullptr;
2012 }
2013
2014 /*--.. Call and invoke instructions ........................................--*/
2015
2016 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) {
2017   Value *V = unwrap(Instr);
2018   if (CallInst *CI = dyn_cast<CallInst>(V))
2019     return CI->getCallingConv();
2020   if (InvokeInst *II = dyn_cast<InvokeInst>(V))
2021     return II->getCallingConv();
2022   llvm_unreachable("LLVMGetInstructionCallConv applies only to call and invoke!");
2023 }
2024
2025 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {
2026   Value *V = unwrap(Instr);
2027   if (CallInst *CI = dyn_cast<CallInst>(V))
2028     return CI->setCallingConv(static_cast<CallingConv::ID>(CC));
2029   else if (InvokeInst *II = dyn_cast<InvokeInst>(V))
2030     return II->setCallingConv(static_cast<CallingConv::ID>(CC));
2031   llvm_unreachable("LLVMSetInstructionCallConv applies only to call and invoke!");
2032 }
2033
2034 void LLVMAddInstrAttribute(LLVMValueRef Instr, unsigned index,
2035                            LLVMAttribute PA) {
2036   CallSite Call = CallSite(unwrap<Instruction>(Instr));
2037   AttrBuilder B(PA);
2038   Call.setAttributes(
2039     Call.getAttributes().addAttributes(Call->getContext(), index,
2040                                        AttributeSet::get(Call->getContext(),
2041                                                          index, B)));
2042 }
2043
2044 void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index,
2045                               LLVMAttribute PA) {
2046   CallSite Call = CallSite(unwrap<Instruction>(Instr));
2047   AttrBuilder B(PA);
2048   Call.setAttributes(Call.getAttributes()
2049                        .removeAttributes(Call->getContext(), index,
2050                                          AttributeSet::get(Call->getContext(),
2051                                                            index, B)));
2052 }
2053
2054 void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,
2055                                 unsigned align) {
2056   CallSite Call = CallSite(unwrap<Instruction>(Instr));
2057   AttrBuilder B;
2058   B.addAlignmentAttr(align);
2059   Call.setAttributes(Call.getAttributes()
2060                        .addAttributes(Call->getContext(), index,
2061                                       AttributeSet::get(Call->getContext(),
2062                                                         index, B)));
2063 }
2064
2065 /*--.. Operations on call instructions (only) ..............................--*/
2066
2067 LLVMBool LLVMIsTailCall(LLVMValueRef Call) {
2068   return unwrap<CallInst>(Call)->isTailCall();
2069 }
2070
2071 void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) {
2072   unwrap<CallInst>(Call)->setTailCall(isTailCall);
2073 }
2074
2075 /*--.. Operations on terminators ...........................................--*/
2076
2077 unsigned LLVMGetNumSuccessors(LLVMValueRef Term) {
2078   return unwrap<TerminatorInst>(Term)->getNumSuccessors();
2079 }
2080
2081 LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) {
2082   return wrap(unwrap<TerminatorInst>(Term)->getSuccessor(i));
2083 }
2084
2085 void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) {
2086   return unwrap<TerminatorInst>(Term)->setSuccessor(i,unwrap(block));
2087 }
2088
2089 /*--.. Operations on branch instructions (only) ............................--*/
2090
2091 LLVMBool LLVMIsConditional(LLVMValueRef Branch) {
2092   return unwrap<BranchInst>(Branch)->isConditional();
2093 }
2094
2095 LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) {
2096   return wrap(unwrap<BranchInst>(Branch)->getCondition());
2097 }
2098
2099 void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) {
2100   return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond));
2101 }
2102
2103 /*--.. Operations on switch instructions (only) ............................--*/
2104
2105 LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) {
2106   return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest());
2107 }
2108
2109 /*--.. Operations on phi nodes .............................................--*/
2110
2111 void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
2112                      LLVMBasicBlockRef *IncomingBlocks, unsigned Count) {
2113   PHINode *PhiVal = unwrap<PHINode>(PhiNode);
2114   for (unsigned I = 0; I != Count; ++I)
2115     PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I]));
2116 }
2117
2118 unsigned LLVMCountIncoming(LLVMValueRef PhiNode) {
2119   return unwrap<PHINode>(PhiNode)->getNumIncomingValues();
2120 }
2121
2122 LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) {
2123   return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index));
2124 }
2125
2126 LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) {
2127   return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index));
2128 }
2129
2130
2131 /*===-- Instruction builders ----------------------------------------------===*/
2132
2133 LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C) {
2134   return wrap(new IRBuilder<>(*unwrap(C)));
2135 }
2136
2137 LLVMBuilderRef LLVMCreateBuilder(void) {
2138   return LLVMCreateBuilderInContext(LLVMGetGlobalContext());
2139 }
2140
2141 void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block,
2142                          LLVMValueRef Instr) {
2143   BasicBlock *BB = unwrap(Block);
2144   Instruction *I = Instr? unwrap<Instruction>(Instr) : (Instruction*) BB->end();
2145   unwrap(Builder)->SetInsertPoint(BB, I);
2146 }
2147
2148 void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
2149   Instruction *I = unwrap<Instruction>(Instr);
2150   unwrap(Builder)->SetInsertPoint(I->getParent(), I);
2151 }
2152
2153 void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
2154   BasicBlock *BB = unwrap(Block);
2155   unwrap(Builder)->SetInsertPoint(BB);
2156 }
2157
2158 LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder) {
2159    return wrap(unwrap(Builder)->GetInsertBlock());
2160 }
2161
2162 void LLVMClearInsertionPosition(LLVMBuilderRef Builder) {
2163   unwrap(Builder)->ClearInsertionPoint();
2164 }
2165
2166 void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr) {
2167   unwrap(Builder)->Insert(unwrap<Instruction>(Instr));
2168 }
2169
2170 void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr,
2171                                    const char *Name) {
2172   unwrap(Builder)->Insert(unwrap<Instruction>(Instr), Name);
2173 }
2174
2175 void LLVMDisposeBuilder(LLVMBuilderRef Builder) {
2176   delete unwrap(Builder);
2177 }
2178
2179 /*--.. Metadata builders ...................................................--*/
2180
2181 void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L) {
2182   MDNode *Loc =
2183       L ? cast<MDNode>(unwrap<MetadataAsValue>(L)->getMetadata()) : nullptr;
2184   unwrap(Builder)->SetCurrentDebugLocation(DebugLoc::getFromDILocation(Loc));
2185 }
2186
2187 LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder) {
2188   LLVMContext &Context = unwrap(Builder)->getContext();
2189   return wrap(MetadataAsValue::get(
2190       Context,
2191       unwrap(Builder)->getCurrentDebugLocation().getAsMDNode(Context)));
2192 }
2193
2194 void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) {
2195   unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst));
2196 }
2197
2198
2199 /*--.. Instruction builders ................................................--*/
2200
2201 LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef B) {
2202   return wrap(unwrap(B)->CreateRetVoid());
2203 }
2204
2205 LLVMValueRef LLVMBuildRet(LLVMBuilderRef B, LLVMValueRef V) {
2206   return wrap(unwrap(B)->CreateRet(unwrap(V)));
2207 }
2208
2209 LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef B, LLVMValueRef *RetVals,
2210                                    unsigned N) {
2211   return wrap(unwrap(B)->CreateAggregateRet(unwrap(RetVals), N));
2212 }
2213
2214 LLVMValueRef LLVMBuildBr(LLVMBuilderRef B, LLVMBasicBlockRef Dest) {
2215   return wrap(unwrap(B)->CreateBr(unwrap(Dest)));
2216 }
2217
2218 LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef B, LLVMValueRef If,
2219                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Else) {
2220   return wrap(unwrap(B)->CreateCondBr(unwrap(If), unwrap(Then), unwrap(Else)));
2221 }
2222
2223 LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef B, LLVMValueRef V,
2224                              LLVMBasicBlockRef Else, unsigned NumCases) {
2225   return wrap(unwrap(B)->CreateSwitch(unwrap(V), unwrap(Else), NumCases));
2226 }
2227
2228 LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
2229                                  unsigned NumDests) {
2230   return wrap(unwrap(B)->CreateIndirectBr(unwrap(Addr), NumDests));
2231 }
2232
2233 LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn,
2234                              LLVMValueRef *Args, unsigned NumArgs,
2235                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
2236                              const char *Name) {
2237   return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
2238                                       makeArrayRef(unwrap(Args), NumArgs),
2239                                       Name));
2240 }
2241
2242 LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
2243                                  LLVMValueRef PersFn, unsigned NumClauses,
2244                                  const char *Name) {
2245   return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty),
2246                                           cast<Function>(unwrap(PersFn)),
2247                                           NumClauses, Name));
2248 }
2249
2250 LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn) {
2251   return wrap(unwrap(B)->CreateResume(unwrap(Exn)));
2252 }
2253
2254 LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef B) {
2255   return wrap(unwrap(B)->CreateUnreachable());
2256 }
2257
2258 void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal,
2259                  LLVMBasicBlockRef Dest) {
2260   unwrap<SwitchInst>(Switch)->addCase(unwrap<ConstantInt>(OnVal), unwrap(Dest));
2261 }
2262
2263 void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) {
2264   unwrap<IndirectBrInst>(IndirectBr)->addDestination(unwrap(Dest));
2265 }
2266
2267 void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal) {
2268   unwrap<LandingPadInst>(LandingPad)->
2269     addClause(cast<Constant>(unwrap(ClauseVal)));
2270 }
2271
2272 void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val) {
2273   unwrap<LandingPadInst>(LandingPad)->setCleanup(Val);
2274 }
2275
2276 /*--.. Arithmetic ..........................................................--*/
2277
2278 LLVMValueRef LLVMBuildAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2279                           const char *Name) {
2280   return wrap(unwrap(B)->CreateAdd(unwrap(LHS), unwrap(RHS), Name));
2281 }
2282
2283 LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2284                           const char *Name) {
2285   return wrap(unwrap(B)->CreateNSWAdd(unwrap(LHS), unwrap(RHS), Name));
2286 }
2287
2288 LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2289                           const char *Name) {
2290   return wrap(unwrap(B)->CreateNUWAdd(unwrap(LHS), unwrap(RHS), Name));
2291 }
2292
2293 LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2294                           const char *Name) {
2295   return wrap(unwrap(B)->CreateFAdd(unwrap(LHS), unwrap(RHS), Name));
2296 }
2297
2298 LLVMValueRef LLVMBuildSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2299                           const char *Name) {
2300   return wrap(unwrap(B)->CreateSub(unwrap(LHS), unwrap(RHS), Name));
2301 }
2302
2303 LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2304                           const char *Name) {
2305   return wrap(unwrap(B)->CreateNSWSub(unwrap(LHS), unwrap(RHS), Name));
2306 }
2307
2308 LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2309                           const char *Name) {
2310   return wrap(unwrap(B)->CreateNUWSub(unwrap(LHS), unwrap(RHS), Name));
2311 }
2312
2313 LLVMValueRef LLVMBuildFSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2314                           const char *Name) {
2315   return wrap(unwrap(B)->CreateFSub(unwrap(LHS), unwrap(RHS), Name));
2316 }
2317
2318 LLVMValueRef LLVMBuildMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2319                           const char *Name) {
2320   return wrap(unwrap(B)->CreateMul(unwrap(LHS), unwrap(RHS), Name));
2321 }
2322
2323 LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2324                           const char *Name) {
2325   return wrap(unwrap(B)->CreateNSWMul(unwrap(LHS), unwrap(RHS), Name));
2326 }
2327
2328 LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2329                           const char *Name) {
2330   return wrap(unwrap(B)->CreateNUWMul(unwrap(LHS), unwrap(RHS), Name));
2331 }
2332
2333 LLVMValueRef LLVMBuildFMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2334                           const char *Name) {
2335   return wrap(unwrap(B)->CreateFMul(unwrap(LHS), unwrap(RHS), Name));
2336 }
2337
2338 LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2339                            const char *Name) {
2340   return wrap(unwrap(B)->CreateUDiv(unwrap(LHS), unwrap(RHS), Name));
2341 }
2342
2343 LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2344                            const char *Name) {
2345   return wrap(unwrap(B)->CreateSDiv(unwrap(LHS), unwrap(RHS), Name));
2346 }
2347
2348 LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef B, LLVMValueRef LHS,
2349                                 LLVMValueRef RHS, const char *Name) {
2350   return wrap(unwrap(B)->CreateExactSDiv(unwrap(LHS), unwrap(RHS), Name));
2351 }
2352
2353 LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2354                            const char *Name) {
2355   return wrap(unwrap(B)->CreateFDiv(unwrap(LHS), unwrap(RHS), Name));
2356 }
2357
2358 LLVMValueRef LLVMBuildURem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2359                            const char *Name) {
2360   return wrap(unwrap(B)->CreateURem(unwrap(LHS), unwrap(RHS), Name));
2361 }
2362
2363 LLVMValueRef LLVMBuildSRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2364                            const char *Name) {
2365   return wrap(unwrap(B)->CreateSRem(unwrap(LHS), unwrap(RHS), Name));
2366 }
2367
2368 LLVMValueRef LLVMBuildFRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2369                            const char *Name) {
2370   return wrap(unwrap(B)->CreateFRem(unwrap(LHS), unwrap(RHS), Name));
2371 }
2372
2373 LLVMValueRef LLVMBuildShl(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2374                           const char *Name) {
2375   return wrap(unwrap(B)->CreateShl(unwrap(LHS), unwrap(RHS), Name));
2376 }
2377
2378 LLVMValueRef LLVMBuildLShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2379                            const char *Name) {
2380   return wrap(unwrap(B)->CreateLShr(unwrap(LHS), unwrap(RHS), Name));
2381 }
2382
2383 LLVMValueRef LLVMBuildAShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2384                            const char *Name) {
2385   return wrap(unwrap(B)->CreateAShr(unwrap(LHS), unwrap(RHS), Name));
2386 }
2387
2388 LLVMValueRef LLVMBuildAnd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2389                           const char *Name) {
2390   return wrap(unwrap(B)->CreateAnd(unwrap(LHS), unwrap(RHS), Name));
2391 }
2392
2393 LLVMValueRef LLVMBuildOr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2394                          const char *Name) {
2395   return wrap(unwrap(B)->CreateOr(unwrap(LHS), unwrap(RHS), Name));
2396 }
2397
2398 LLVMValueRef LLVMBuildXor(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,
2399                           const char *Name) {
2400   return wrap(unwrap(B)->CreateXor(unwrap(LHS), unwrap(RHS), Name));
2401 }
2402
2403 LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op,
2404                             LLVMValueRef LHS, LLVMValueRef RHS,
2405                             const char *Name) {
2406   return wrap(unwrap(B)->CreateBinOp(Instruction::BinaryOps(map_from_llvmopcode(Op)), unwrap(LHS),
2407                                      unwrap(RHS), Name));
2408 }
2409
2410 LLVMValueRef LLVMBuildNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
2411   return wrap(unwrap(B)->CreateNeg(unwrap(V), Name));
2412 }
2413
2414 LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V,
2415                              const char *Name) {
2416   return wrap(unwrap(B)->CreateNSWNeg(unwrap(V), Name));
2417 }
2418
2419 LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,
2420                              const char *Name) {
2421   return wrap(unwrap(B)->CreateNUWNeg(unwrap(V), Name));
2422 }
2423
2424 LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
2425   return wrap(unwrap(B)->CreateFNeg(unwrap(V), Name));
2426 }
2427
2428 LLVMValueRef LLVMBuildNot(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {
2429   return wrap(unwrap(B)->CreateNot(unwrap(V), Name));
2430 }
2431
2432 /*--.. Memory ..............................................................--*/
2433
2434 LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
2435                              const char *Name) {
2436   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
2437   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
2438   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
2439   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
2440                                                ITy, unwrap(Ty), AllocSize,
2441                                                nullptr, nullptr, "");
2442   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
2443 }
2444
2445 LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,
2446                                   LLVMValueRef Val, const char *Name) {
2447   Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());
2448   Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));
2449   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
2450   Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(),
2451                                                ITy, unwrap(Ty), AllocSize,
2452                                                unwrap(Val), nullptr, "");
2453   return wrap(unwrap(B)->Insert(Malloc, Twine(Name)));
2454 }
2455
2456 LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
2457                              const char *Name) {
2458   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), nullptr, Name));
2459 }
2460
2461 LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,
2462                                   LLVMValueRef Val, const char *Name) {
2463   return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), unwrap(Val), Name));
2464 }
2465
2466 LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) {
2467   return wrap(unwrap(B)->Insert(
2468      CallInst::CreateFree(unwrap(PointerVal), unwrap(B)->GetInsertBlock())));
2469 }
2470
2471
2472 LLVMValueRef LLVMBuildLoad(LLVMBuilderRef B, LLVMValueRef PointerVal,
2473                            const char *Name) {
2474   return wrap(unwrap(B)->CreateLoad(unwrap(PointerVal), Name));
2475 }
2476
2477 LLVMValueRef LLVMBuildStore(LLVMBuilderRef B, LLVMValueRef Val,
2478                             LLVMValueRef PointerVal) {
2479   return wrap(unwrap(B)->CreateStore(unwrap(Val), unwrap(PointerVal)));
2480 }
2481
2482 static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) {
2483   switch (Ordering) {
2484     case LLVMAtomicOrderingNotAtomic: return NotAtomic;
2485     case LLVMAtomicOrderingUnordered: return Unordered;
2486     case LLVMAtomicOrderingMonotonic: return Monotonic;
2487     case LLVMAtomicOrderingAcquire: return Acquire;
2488     case LLVMAtomicOrderingRelease: return Release;
2489     case LLVMAtomicOrderingAcquireRelease: return AcquireRelease;
2490     case LLVMAtomicOrderingSequentiallyConsistent:
2491       return SequentiallyConsistent;
2492   }
2493
2494   llvm_unreachable("Invalid LLVMAtomicOrdering value!");
2495 }
2496
2497 LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering Ordering,
2498                             LLVMBool isSingleThread, const char *Name) {
2499   return wrap(
2500     unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering),
2501                            isSingleThread ? SingleThread : CrossThread,
2502                            Name));
2503 }
2504
2505 LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
2506                           LLVMValueRef *Indices, unsigned NumIndices,
2507                           const char *Name) {
2508   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
2509   return wrap(unwrap(B)->CreateGEP(unwrap(Pointer), IdxList, Name));
2510 }
2511
2512 LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
2513                                   LLVMValueRef *Indices, unsigned NumIndices,
2514                                   const char *Name) {
2515   ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);
2516   return wrap(unwrap(B)->CreateInBoundsGEP(unwrap(Pointer), IdxList, Name));
2517 }
2518
2519 LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
2520                                 unsigned Idx, const char *Name) {
2521   return wrap(unwrap(B)->CreateStructGEP(unwrap(Pointer), Idx, Name));
2522 }
2523
2524 LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str,
2525                                    const char *Name) {
2526   return wrap(unwrap(B)->CreateGlobalString(Str, Name));
2527 }
2528
2529 LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,
2530                                       const char *Name) {
2531   return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name));
2532 }
2533
2534 LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) {
2535   Value *P = unwrap<Value>(MemAccessInst);
2536   if (LoadInst *LI = dyn_cast<LoadInst>(P))
2537     return LI->isVolatile();
2538   return cast<StoreInst>(P)->isVolatile();
2539 }
2540
2541 void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) {
2542   Value *P = unwrap<Value>(MemAccessInst);
2543   if (LoadInst *LI = dyn_cast<LoadInst>(P))
2544     return LI->setVolatile(isVolatile);
2545   return cast<StoreInst>(P)->setVolatile(isVolatile);
2546 }
2547
2548 /*--.. Casts ...............................................................--*/
2549
2550 LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val,
2551                             LLVMTypeRef DestTy, const char *Name) {
2552   return wrap(unwrap(B)->CreateTrunc(unwrap(Val), unwrap(DestTy), Name));
2553 }
2554
2555 LLVMValueRef LLVMBuildZExt(LLVMBuilderRef B, LLVMValueRef Val,
2556                            LLVMTypeRef DestTy, const char *Name) {
2557   return wrap(unwrap(B)->CreateZExt(unwrap(Val), unwrap(DestTy), Name));
2558 }
2559
2560 LLVMValueRef LLVMBuildSExt(LLVMBuilderRef B, LLVMValueRef Val,
2561                            LLVMTypeRef DestTy, const char *Name) {
2562   return wrap(unwrap(B)->CreateSExt(unwrap(Val), unwrap(DestTy), Name));
2563 }
2564
2565 LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef B, LLVMValueRef Val,
2566                              LLVMTypeRef DestTy, const char *Name) {
2567   return wrap(unwrap(B)->CreateFPToUI(unwrap(Val), unwrap(DestTy), Name));
2568 }
2569
2570 LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef B, LLVMValueRef Val,
2571                              LLVMTypeRef DestTy, const char *Name) {
2572   return wrap(unwrap(B)->CreateFPToSI(unwrap(Val), unwrap(DestTy), Name));
2573 }
2574
2575 LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef B, LLVMValueRef Val,
2576                              LLVMTypeRef DestTy, const char *Name) {
2577   return wrap(unwrap(B)->CreateUIToFP(unwrap(Val), unwrap(DestTy), Name));
2578 }
2579
2580 LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef B, LLVMValueRef Val,
2581                              LLVMTypeRef DestTy, const char *Name) {
2582   return wrap(unwrap(B)->CreateSIToFP(unwrap(Val), unwrap(DestTy), Name));
2583 }
2584
2585 LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef B, LLVMValueRef Val,
2586                               LLVMTypeRef DestTy, const char *Name) {
2587   return wrap(unwrap(B)->CreateFPTrunc(unwrap(Val), unwrap(DestTy), Name));
2588 }
2589
2590 LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef B, LLVMValueRef Val,
2591                             LLVMTypeRef DestTy, const char *Name) {
2592   return wrap(unwrap(B)->CreateFPExt(unwrap(Val), unwrap(DestTy), Name));
2593 }
2594
2595 LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef B, LLVMValueRef Val,
2596                                LLVMTypeRef DestTy, const char *Name) {
2597   return wrap(unwrap(B)->CreatePtrToInt(unwrap(Val), unwrap(DestTy), Name));
2598 }
2599
2600 LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef B, LLVMValueRef Val,
2601                                LLVMTypeRef DestTy, const char *Name) {
2602   return wrap(unwrap(B)->CreateIntToPtr(unwrap(Val), unwrap(DestTy), Name));
2603 }
2604
2605 LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef B, LLVMValueRef Val,
2606                               LLVMTypeRef DestTy, const char *Name) {
2607   return wrap(unwrap(B)->CreateBitCast(unwrap(Val), unwrap(DestTy), Name));
2608 }
2609
2610 LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef B, LLVMValueRef Val,
2611                                     LLVMTypeRef DestTy, const char *Name) {
2612   return wrap(unwrap(B)->CreateAddrSpaceCast(unwrap(Val), unwrap(DestTy), Name));
2613 }
2614
2615 LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
2616                                     LLVMTypeRef DestTy, const char *Name) {
2617   return wrap(unwrap(B)->CreateZExtOrBitCast(unwrap(Val), unwrap(DestTy),
2618                                              Name));
2619 }
2620
2621 LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
2622                                     LLVMTypeRef DestTy, const char *Name) {
2623   return wrap(unwrap(B)->CreateSExtOrBitCast(unwrap(Val), unwrap(DestTy),
2624                                              Name));
2625 }
2626
2627 LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,
2628                                      LLVMTypeRef DestTy, const char *Name) {
2629   return wrap(unwrap(B)->CreateTruncOrBitCast(unwrap(Val), unwrap(DestTy),
2630                                               Name));
2631 }
2632
2633 LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val,
2634                            LLVMTypeRef DestTy, const char *Name) {
2635   return wrap(unwrap(B)->CreateCast(Instruction::CastOps(map_from_llvmopcode(Op)), unwrap(Val),
2636                                     unwrap(DestTy), Name));
2637 }
2638
2639 LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef B, LLVMValueRef Val,
2640                                   LLVMTypeRef DestTy, const char *Name) {
2641   return wrap(unwrap(B)->CreatePointerCast(unwrap(Val), unwrap(DestTy), Name));
2642 }
2643
2644 LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
2645                               LLVMTypeRef DestTy, const char *Name) {
2646   return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy),
2647                                        /*isSigned*/true, Name));
2648 }
2649
2650 LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef B, LLVMValueRef Val,
2651                              LLVMTypeRef DestTy, const char *Name) {
2652   return wrap(unwrap(B)->CreateFPCast(unwrap(Val), unwrap(DestTy), Name));
2653 }
2654
2655 /*--.. Comparisons .........................................................--*/
2656
2657 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op,
2658                            LLVMValueRef LHS, LLVMValueRef RHS,
2659                            const char *Name) {
2660   return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op),
2661                                     unwrap(LHS), unwrap(RHS), Name));
2662 }
2663
2664 LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op,
2665                            LLVMValueRef LHS, LLVMValueRef RHS,
2666                            const char *Name) {
2667   return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op),
2668                                     unwrap(LHS), unwrap(RHS), Name));
2669 }
2670
2671 /*--.. Miscellaneous instructions ..........................................--*/
2672
2673 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) {
2674   return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name));
2675 }
2676
2677 LLVMValueRef LLVMBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
2678                            LLVMValueRef *Args, unsigned NumArgs,
2679                            const char *Name) {
2680   return wrap(unwrap(B)->CreateCall(unwrap(Fn),
2681                                     makeArrayRef(unwrap(Args), NumArgs),
2682                                     Name));
2683 }
2684
2685 LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If,
2686                              LLVMValueRef Then, LLVMValueRef Else,
2687                              const char *Name) {
2688   return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else),
2689                                       Name));
2690 }
2691
2692 LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List,
2693                             LLVMTypeRef Ty, const char *Name) {
2694   return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name));
2695 }
2696
2697 LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal,
2698                                       LLVMValueRef Index, const char *Name) {
2699   return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index),
2700                                               Name));
2701 }
2702
2703 LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal,
2704                                     LLVMValueRef EltVal, LLVMValueRef Index,
2705                                     const char *Name) {
2706   return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal),
2707                                              unwrap(Index), Name));
2708 }
2709
2710 LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1,
2711                                     LLVMValueRef V2, LLVMValueRef Mask,
2712                                     const char *Name) {
2713   return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2),
2714                                              unwrap(Mask), Name));
2715 }
2716
2717 LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal,
2718                                    unsigned Index, const char *Name) {
2719   return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name));
2720 }
2721
2722 LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal,
2723                                   LLVMValueRef EltVal, unsigned Index,
2724                                   const char *Name) {
2725   return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal),
2726                                            Index, Name));
2727 }
2728
2729 LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val,
2730                              const char *Name) {
2731   return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name));
2732 }
2733
2734 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val,
2735                                 const char *Name) {
2736   return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name));
2737 }
2738
2739 LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef B, LLVMValueRef LHS,
2740                               LLVMValueRef RHS, const char *Name) {
2741   return wrap(unwrap(B)->CreatePtrDiff(unwrap(LHS), unwrap(RHS), Name));
2742 }
2743
2744 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op,
2745                                LLVMValueRef PTR, LLVMValueRef Val,
2746                                LLVMAtomicOrdering ordering,
2747                                LLVMBool singleThread) {
2748   AtomicRMWInst::BinOp intop;
2749   switch (op) {
2750     case LLVMAtomicRMWBinOpXchg: intop = AtomicRMWInst::Xchg; break;
2751     case LLVMAtomicRMWBinOpAdd: intop = AtomicRMWInst::Add; break;
2752     case LLVMAtomicRMWBinOpSub: intop = AtomicRMWInst::Sub; break;
2753     case LLVMAtomicRMWBinOpAnd: intop = AtomicRMWInst::And; break;
2754     case LLVMAtomicRMWBinOpNand: intop = AtomicRMWInst::Nand; break;
2755     case LLVMAtomicRMWBinOpOr: intop = AtomicRMWInst::Or; break;
2756     case LLVMAtomicRMWBinOpXor: intop = AtomicRMWInst::Xor; break;
2757     case LLVMAtomicRMWBinOpMax: intop = AtomicRMWInst::Max; break;
2758     case LLVMAtomicRMWBinOpMin: intop = AtomicRMWInst::Min; break;
2759     case LLVMAtomicRMWBinOpUMax: intop = AtomicRMWInst::UMax; break;
2760     case LLVMAtomicRMWBinOpUMin: intop = AtomicRMWInst::UMin; break;
2761   }
2762   return wrap(unwrap(B)->CreateAtomicRMW(intop, unwrap(PTR), unwrap(Val),
2763     mapFromLLVMOrdering(ordering), singleThread ? SingleThread : CrossThread));
2764 }
2765
2766
2767 /*===-- Module providers --------------------------------------------------===*/
2768
2769 LLVMModuleProviderRef
2770 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {
2771   return reinterpret_cast<LLVMModuleProviderRef>(M);
2772 }
2773
2774 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {
2775   delete unwrap(MP);
2776 }
2777
2778
2779 /*===-- Memory buffers ----------------------------------------------------===*/
2780
2781 LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(
2782     const char *Path,
2783     LLVMMemoryBufferRef *OutMemBuf,
2784     char **OutMessage) {
2785
2786   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
2787   if (std::error_code EC = MBOrErr.getError()) {
2788     *OutMessage = strdup(EC.message().c_str());
2789     return 1;
2790   }
2791   *OutMemBuf = wrap(MBOrErr.get().release());
2792   return 0;
2793 }
2794
2795 LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
2796                                          char **OutMessage) {
2797   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();
2798   if (std::error_code EC = MBOrErr.getError()) {
2799     *OutMessage = strdup(EC.message().c_str());
2800     return 1;
2801   }
2802   *OutMemBuf = wrap(MBOrErr.get().release());
2803   return 0;
2804 }
2805
2806 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
2807     const char *InputData,
2808     size_t InputDataLength,
2809     const char *BufferName,
2810     LLVMBool RequiresNullTerminator) {
2811
2812   return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength),
2813                                          StringRef(BufferName),
2814                                          RequiresNullTerminator).release());
2815 }
2816
2817 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(
2818     const char *InputData,
2819     size_t InputDataLength,
2820     const char *BufferName) {
2821
2822   return wrap(
2823       MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength),
2824                                      StringRef(BufferName)).release());
2825 }
2826
2827 const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) {
2828   return unwrap(MemBuf)->getBufferStart();
2829 }
2830
2831 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) {
2832   return unwrap(MemBuf)->getBufferSize();
2833 }
2834
2835 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) {
2836   delete unwrap(MemBuf);
2837 }
2838
2839 /*===-- Pass Registry -----------------------------------------------------===*/
2840
2841 LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void) {
2842   return wrap(PassRegistry::getPassRegistry());
2843 }
2844
2845 /*===-- Pass Manager ------------------------------------------------------===*/
2846
2847 LLVMPassManagerRef LLVMCreatePassManager() {
2848   return wrap(new PassManager());
2849 }
2850
2851 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
2852   return wrap(new FunctionPassManager(unwrap(M)));
2853 }
2854
2855 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
2856   return LLVMCreateFunctionPassManagerForModule(
2857                                             reinterpret_cast<LLVMModuleRef>(P));
2858 }
2859
2860 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
2861   return unwrap<PassManager>(PM)->run(*unwrap(M));
2862 }
2863
2864 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
2865   return unwrap<FunctionPassManager>(FPM)->doInitialization();
2866 }
2867
2868 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
2869   return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
2870 }
2871
2872 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
2873   return unwrap<FunctionPassManager>(FPM)->doFinalization();
2874 }
2875
2876 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
2877   delete unwrap(PM);
2878 }
2879
2880 /*===-- Threading ------------------------------------------------------===*/
2881
2882 LLVMBool LLVMStartMultithreaded() {
2883   return LLVMIsMultithreaded();
2884 }
2885
2886 void LLVMStopMultithreaded() {
2887 }
2888
2889 LLVMBool LLVMIsMultithreaded() {
2890   return llvm_is_multithreaded();
2891 }