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