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