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