1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
//! LLVM `Context` functions and wrappers.
use crate::core::types::TypeRef;
use crate::{CInt, CStr, CString, CUint, GetRef, SizeT, UnsafeMutVoidPtr};
use llvm_sys::prelude::{LLVMAttributeRef, LLVMContextRef, LLVMDiagnosticInfoRef};
use llvm_sys::{core, LLVMDiagnosticHandler, LLVMDiagnosticSeverity, LLVMYieldCallback};
use std::ops::Deref;
/// Wrapper for `LLVMDiagnosticSeverity`, representing the severity levels of diagnostics in LLVM.
///
/// The `DiagnosticSeverity` enum maps to the `LLVMDiagnosticSeverity` in the LLVM core library. It categorizes
/// the severity levels of diagnostic messages that can be generated by LLVM during compilation or other processing.
/// This enum helps identify the nature of the diagnostic messages, such as errors, warnings, remarks, and notes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticSeverity {
/// Represents an error diagnostic. Errors indicate critical issues that typically prevent the code from compiling successfully.
DSError,
/// Represents a warning diagnostic. Warnings indicate potential issues that do not stop compilation but could lead to problems.
DSWarning,
/// Represents a remark diagnostic. Remarks provide additional information that might be useful but is not necessarily problematic.
DSRemark,
/// Represents a note diagnostic. Notes usually provide supplementary information related to warnings or errors.
DSNote,
}
impl From<LLVMDiagnosticSeverity> for DiagnosticSeverity {
fn from(severity: LLVMDiagnosticSeverity) -> Self {
match severity {
LLVMDiagnosticSeverity::LLVMDSError => Self::DSError,
LLVMDiagnosticSeverity::LLVMDSWarning => Self::DSWarning,
LLVMDiagnosticSeverity::LLVMDSRemark => Self::DSRemark,
LLVMDiagnosticSeverity::LLVMDSNote => Self::DSNote,
}
}
}
/// LLVM Context wrapper
#[derive(Debug)]
pub struct ContextRef(LLVMContextRef);
impl From<LLVMContextRef> for ContextRef {
fn from(value: LLVMContextRef) -> Self {
Self(value)
}
}
impl ContextRef {
/// Create new LLVM Context
#[must_use]
pub fn new() -> Self {
Self::context_create()
}
}
/// LLVM specific implementations
impl ContextRef {
/// Create a new context.
///
/// ## Safety
/// Every call to this function should be paired with a call to
/// `Self::context_dispose` or the context will leak memory.
#[must_use]
pub fn context_create() -> Self {
unsafe { Self(core::LLVMContextCreate()) }
}
/// Retrieves the global context instance.
///
/// The global context is particularly convenient instance managed by LLVM
/// itself. It is the default context provided for any operations that
/// require it.
///
/// ### Safety
/// Failure to specify the correct context in concurrent
/// environments can lead to data corruption. In general, it is always
/// recommended that each thread of execution attempting to access the LLVM
/// API have its own `Context` instance, rather than rely on this global
/// context.
///
/// # Details
///
/// This function wraps the `LLVMContextSetDiagnosticHandler` function from the LLVM core library. It allows you to set
/// a custom diagnostic handler function (`LLVMDiagnosticHandler`) that will be invoked when diagnostic messages
/// (such as errors, warnings, or remarks) are generated within the context represented by `self`. Additionally,
/// an optional diagnostic context (`UnsafeMutVoidPtr`) can be passed, which can hold user-defined data to be used
/// by the diagnostic handler.
///
/// # Parameters
///
/// - `handler`: The diagnostic handler function (`LLVMDiagnosticHandler`) to be set for the context.
/// - `diagnostic_context`: An opaque pointer (`UnsafeMutVoidPtr`) that can be passed to the diagnostic handler. This
/// context is typically used to store additional data that the handler might need when processing diagnostics.
#[must_use]
pub fn get_global_context() -> Self {
unsafe { Self(core::LLVMGetGlobalContext()) }
}
/// Set debug diagnostic handler for this context.
///
/// ## Safety
/// To provide safe operations wi with diagnostic context should be set:
/// - `handler` - LLVM diagnostic function (handler)
/// - `diagnostic_context` - raw pointer for diagnostic
/// NOTE: it's much safer to use raw pointer in that case than `std::ptr::NonNull` structs.
pub fn set_diagnostic_handler(
&self,
handler: LLVMDiagnosticHandler,
diagnostic_context: UnsafeMutVoidPtr,
) {
unsafe {
core::LLVMContextSetDiagnosticHandler(self.0, handler, *diagnostic_context);
}
}
/// Get the diagnostic handler of this context.
///
/// # Details
///
/// Retrieves the diagnostic handler associated with the current LLVM context.
///
/// This function wraps the `LLVMContextGetDiagnosticHandler` function from the LLVM core library. It returns the
/// diagnostic handler (`LLVMDiagnosticHandler`) associated with the context represented by `self`. The diagnostic handler
/// is a function or callback that is invoked when a diagnostic message (such as an error or warning) is generated during
/// compilation or other LLVM operations.
///
/// # Returns
///
/// Returns an `LLVMDiagnosticHandler` representing the diagnostic handler associated with the current LLVM context.
#[must_use]
pub fn get_diagnostic_handler(&self) -> LLVMDiagnosticHandler {
unsafe { core::LLVMContextGetDiagnosticHandler(self.0) }
}
/// Get the diagnostic context of this context.
///
/// # Details
///
/// Retrieves the diagnostic context associated with the current LLVM context.
///
/// This function wraps the `LLVMContextGetDiagnosticContext` function from the LLVM core library. It returns a raw
/// pointer wrapped in `UnsafeMutVoidPtr` that represents the diagnostic context associated with the context represented
/// by `self`. The diagnostic context can be used to store and retrieve additional information related to diagnostics
/// generated during compilation or other operations.
///
/// # Returns
///
/// Returns an `UnsafeMutVoidPtr` representing the diagnostic context associated with the current LLVM context.
///
/// # Safety
///
/// The returned pointer is unsafe and must be handled with care. Ensure that the pointer is used correctly and that any
/// operations involving the pointer respect the rules of memory safety.
#[must_use]
pub fn get_diagnostic_context(&self) -> UnsafeMutVoidPtr {
unsafe {
let raw_ptr = core::LLVMContextGetDiagnosticContext(self.0);
UnsafeMutVoidPtr(raw_ptr)
}
}
/// Set the yield callback function for this context.
///
/// #Details
///
/// Sets a yield callback for the current LLVM context.
///
/// This function wraps the `LLVMContextSetYieldCallback` function from the LLVM core library. It allows you to set
/// a yield callback function that will be invoked periodically during long-running operations in the context represented
/// by `self`. Yield callbacks can be used to implement cooperative multitasking, allowing other tasks to run or perform
/// actions such as checking for user interruptions.
///
/// # Parameters
///
/// - `callback`: The callback function (`LLVMYieldCallback`) to be invoked periodically during long-running operations.
/// - `opaque_handle`: An opaque pointer (`UnsafeMutVoidPtr`) that can be passed to the callback function. This handle
/// is typically used to maintain state or pass additional data to the callback.
pub fn set_yield_callback(&self, callback: LLVMYieldCallback, opaque_handle: UnsafeMutVoidPtr) {
unsafe { core::LLVMContextSetYieldCallback(self.0, callback, *opaque_handle) }
}
/// Retrieve whether the given context is set to discard all value names.
///
/// # Details
///
/// Checks whether value names should be discarded in the current LLVM context.
///
/// This function wraps the `LLVMContextShouldDiscardValueNames` function from the LLVM core library. It determines
/// whether the context represented by `self` is currently set to discard value names. Discarding value names can reduce
/// memory usage and improve performance, but it removes human-readable names for values, which may impact debugging
/// and analysis.
///
/// # Returns
///
/// Returns `true` if the context is set to discard value names, otherwise returns `false`.
#[must_use]
pub fn should_discard_value_names(&self) -> bool {
unsafe { core::LLVMContextShouldDiscardValueNames(self.0) != 0 }
}
/// Set whether the given context discards all value names.
///
/// If true, only the names of `GlobalValue` objects will be available in the IR.
/// This can be used to save memory and runtime, especially in release mode.
///
/// # Details
///
/// Configures whether value names should be discarded in the current LLVM context.
///
/// This function wraps the `LLVMContextSetDiscardValueNames` function from the LLVM core library. It allows you to
/// enable or disable the discarding of value names within the context represented by `self`. Discarding value names
/// can reduce memory usage and improve performance, but at the cost of losing human-readable names for values.
///
/// # Parameters
///
/// - `discard`: A boolean indicating whether to discard value names (`true` to discard, `false` to keep them).
///
/// # Note
///
/// Disabling value name retention can make debugging and analysis more difficult since values will lose their human-readable names.
pub fn set_discard_value_names(&self, discard: bool) {
unsafe {
core::LLVMContextSetDiscardValueNames(self.0, *CInt::from(discard));
}
}
/// Deinitialize this value and dispose of its resources.
///
/// Destroy a context instance.
/// This should be called for every call to `self::context_create` (`LLVMContextCreate()`) or memory
/// will be leaked.
///
/// # Details
///
/// Disposes of the current LLVM context, freeing associated resources.
///
/// This function wraps the `LLVMContextDispose` function from the LLVM core library. It releases the resources
/// associated with the LLVM context represented by `self`. After calling this function, the context should no longer
/// be used, as it will be in an invalid state.
///
/// # Safety
///
/// This function should be called when you are done using the context to ensure that all resources are properly freed.
pub fn context_dispose(&self) {
unsafe { core::LLVMContextDispose(self.get_ref()) }
}
/// Get Metadata `KindId` by name in current Context.
/// Useful for working with Metadata.
///
/// # Details
///
/// Retrieves the metadata kind ID by name within the current context.
///
/// This function simplifies the retrieval of a metadata kind ID by wrapping the `get_md_kind_id_in_context`
/// method from `MetadataKindId`. It returns the metadata kind ID corresponding to the provided name within
/// the context represented by `self`. This is useful for working with metadata in LLVM IR.
///
/// # Parameters
///
/// - `name`: A string slice (`&str`) representing the name of the metadata kind.
///
/// # Returns
///
/// Returns a `MetadataKindId` representing the ID associated with the provided metadata kind name in the current context.
#[must_use]
pub fn get_md_kind_id_in_context(&self, name: &str) -> MetadataKindId {
MetadataKindId::get_md_kind_id_in_context(self, name)
}
/// Create an enum attribute.
///
/// # Details
///
/// Creates an enum attribute within the current LLVM context or module.
///
/// This function simplifies the creation of an enum attribute by wrapping the `create_enum_attribute` method
/// from `AttributeRef`. It creates an enum attribute with the specified kind ID and value within the context or module
/// represented by `self`.
///
/// # Parameters
///
/// - `kind_id`: A `u32` representing the kind ID of the enum attribute. This ID specifies the kind of the attribute.
/// - `val`: A `u64` representing the value of the enum attribute.
///
/// # Returns
///
/// Returns an `AttributeRef` representing the created enum attribute.
#[must_use]
pub fn create_enum_attribute(&self, kind_id: u32, val: u64) -> AttributeRef {
AttributeRef::create_enum_attribute(self, kind_id, val)
}
/// Create a type attribute in context
///
/// # Details
///
/// Creates a string attribute within the current LLVM context or module.
///
/// This function simplifies the creation of a string attribute by wrapping the `create_string_attribute` method
/// from `AttributeRef`. It creates a string attribute with the specified key and value within the context or module
/// represented by `self`.
///
/// # Parameters
///
/// - `key`: A string slice (`&str`) representing the key (kind) of the attribute.
/// - `value`: A string slice (`&str`) representing the value of the attribute.
///
/// # Returns
///
/// Returns an `AttributeRef` representing the created string attribute.
#[must_use]
pub fn create_type_attribute(&self, kind_id: u32, type_ref: &TypeRef) -> AttributeRef {
AttributeRef::create_type_attribute(self, kind_id, type_ref)
}
/// Create a string attribute in context
#[must_use]
pub fn create_string_attribute(&self, key: &str, value: &str) -> AttributeRef {
AttributeRef::create_string_attribute(self, key, value)
}
/// Obtain a Type from a context by its registered name.
///
/// # Details
///
/// Retrieves a type by its name within the current LLVM module or context.
///
/// This function wraps the `LLVMGetTypeByName2` function from the LLVM core library. It searches for a type
/// with the specified name within the context or module represented by `self`. If a type with the given name
/// is found, it returns a `TypeRef` representing the type. Otherwise, it returns `None`.
///
/// # Parameters
///
/// - `name`: A string slice (`&str`) representing the name of the type to search for.
///
/// # Returns
///
/// Returns an `Option<TypeRef>`:
/// - `Some(TypeRef)` if the type with the specified name is found.
/// - `None` if the type is not found.
#[must_use]
pub fn get_type_by_name2(&self, name: &str) -> Option<TypeRef> {
let c_name = CString::from(name);
let type_ref = unsafe { core::LLVMGetTypeByName2(self.0, c_name.as_ptr()) };
if type_ref.is_null() {
None
} else {
Some(TypeRef::from(type_ref))
}
}
}
impl Drop for ContextRef {
/// Dispose context
fn drop(&mut self) {
self.context_dispose();
}
}
impl Deref for ContextRef {
type Target = LLVMContextRef;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl GetRef for ContextRef {
type RawRef = LLVMContextRef;
fn get_ref(&self) -> Self::RawRef {
self.0
}
}
/// Wrapper for `MetadataKindId`
pub struct MetadataKindId(pub u32);
impl MetadataKindId {
/// Get `MetadataKindId` by name in current `Context`.
/// Useful for working with Metadata.
///
/// # Details
///
/// Retrieves the metadata kind ID associated with a given name within a specific LLVM context.
///
/// This function wraps the `LLVMGetMDKindIDInContext` function from the LLVM core library. It returns the metadata kind ID
/// corresponding to the provided name within the specified LLVM context. Metadata kinds in LLVM IR are used to attach
/// additional information to various IR constructs, such as instructions or functions. Using this function allows for
/// context-specific retrieval of metadata kind IDs.
///
/// # Parameters
///
/// - `context`: A reference to the `ContextRef` in which the metadata kind ID will be retrieved.
/// - `name`: A string slice (`&str`) representing the name of the metadata kind.
///
/// # Returns
///
/// Returns a `MetadataKindId` representing the ID associated with the provided metadata kind name within the specified context.
#[must_use]
pub fn get_md_kind_id_in_context(context: &ContextRef, name: &str) -> Self {
let c_name = CString::from(name);
let id = unsafe {
core::LLVMGetMDKindIDInContext(
context.get_ref(),
c_name.as_ptr(),
*CUint::from(c_name.to_bytes().len()),
)
};
Self(id)
}
/// Get Metadata `KindId` by name.
/// Useful for working with Metadata.
///
/// # Details
///
/// Retrieves the metadata kind ID associated with a given name.
///
/// This function wraps the `LLVMGetMDKindID` function from the LLVM core library. It returns the metadata kind ID
/// corresponding to the provided name. Metadata kinds in LLVM IR are used to attach additional information to
/// various IR constructs, such as instructions or functions.
///
/// # Parameters
///
/// - `name`: A string slice (`&str`) representing the name of the metadata kind.
///
/// # Returns
///
/// Returns a `MetadataKindId` representing the ID associated with the provided metadata kind name.
#[must_use]
pub fn get_md_kind_id(name: &str) -> Self {
let c_name = CString::from(name);
let id = unsafe {
core::LLVMGetMDKindID(c_name.as_ptr(), *CUint::from(c_name.to_bytes().len()))
};
Self(id)
}
}
/// LLVM Attributes structure wrapper
pub struct AttributeRef(LLVMAttributeRef);
impl From<LLVMAttributeRef> for AttributeRef {
fn from(value: LLVMAttributeRef) -> Self {
Self(value)
}
}
impl GetRef for AttributeRef {
type RawRef = LLVMAttributeRef;
fn get_ref(&self) -> Self::RawRef {
self.0
}
}
impl AttributeRef {
/// Return the unique id given the name of the enum attribute,
/// or 0 if no attribute by that name exists.
///
/// See <http://llvm.org/docs/LangRef.html#parameter-attributes>
/// and <http://llvm.org/docs/LangRef.html#function-attributes>
/// for the list of available attributes.
///
/// # Note
///
/// Attribute names and/or id are subject to change without
/// going through the C API deprecation cycle.
///
/// # Details
///
/// Retrieves the enum attribute kind ID associated with a given name.
///
/// This function wraps the `LLVMGetEnumAttributeKindForName` function from the LLVM core library. It returns the
/// kind ID of the enum attribute that corresponds to the provided name. This is useful for looking up the kind ID
/// of an enum attribute by its name, allowing you to work with attributes in a more human-readable way.
///
/// # Parameters
///
/// - `name`: A string slice (`&str`) representing the name of the enum attribute.
///
/// # Returns
///
/// Returns a `u32` representing the kind ID associated with the provided attribute name.
#[must_use]
pub fn get_enum_attribute_kind_for_name(name: &str) -> u32 {
let c_name = CString::from(name);
unsafe {
core::LLVMGetEnumAttributeKindForName(c_name.as_ptr(), *SizeT(c_name.to_bytes().len()))
}
}
/// Get last enum attribute
///
/// # Details
///
/// Retrieves the highest (last) enum attribute kind ID used in LLVM.
///
/// This function wraps the `LLVMGetLastEnumAttributeKind` function from the LLVM core library. It returns the
/// highest (last) enum attribute kind ID that is currently defined in LLVM. This can be useful for determining
/// the range of valid enum attribute kinds or for iterating over all possible enum attributes.
///
/// # Returns
///
/// Returns a `u32` representing the highest (last) enum attribute kind ID.
#[must_use]
pub fn get_last_enum_attribute_kind() -> u32 {
unsafe { core::LLVMGetLastEnumAttributeKind() }
}
/// Create an enum attribute.
///
/// # Details
///
/// Creates an enum attribute in the specified LLVM context.
///
/// This function wraps the `LLVMCreateEnumAttribute` function from the LLVM core library. It creates and returns
/// an enum attribute with the specified kind ID and value within the given LLVM context. Enum attributes in LLVM IR
/// represent attributes that have a fixed set of possible values, and this function allows you to create such attributes
/// with a specific value.
///
/// # Parameters
///
/// - `context`: A reference to the `ContextRef` in which the enum attribute will be created.
/// - `kind_id`: A `u32` representing the kind ID of the enum attribute. This ID specifies the kind of the attribute.
/// - `val`: A `u64` representing the value of the enum attribute.
///
/// # Returns
///
/// Returns an instance of `AttributeRef` representing the created enum attribute.
#[must_use]
pub fn create_enum_attribute(context: &ContextRef, kind_id: u32, val: u64) -> Self {
let attr =
unsafe { core::LLVMCreateEnumAttribute(context.get_ref(), *CUint::from(kind_id), val) };
Self(attr)
}
/// Get the unique id corresponding to the enum attribute passed as argument.
///
/// # Details
///
/// Retrieves the kind (ID) of an enum attribute as a `u32`.
///
/// This function wraps the `LLVMGetEnumAttributeKind` function from the LLVM core library. It returns the
/// kind or ID associated with the enum attribute represented by `self`. The kind ID identifies the specific
/// attribute within the set of possible enum attributes in LLVM IR.
///
/// # Returns
///
/// Returns a `u32` representing the kind (ID) of the enum attribute.
#[must_use]
pub fn get_enum_attribute_kind(&self) -> u32 {
unsafe { core::LLVMGetEnumAttributeKind(self.0) }
}
/// Get the enum attribute's value. 0 is returned if none exists.
///
/// # Details
///
/// Retrieves the value of an enum attribute as a `u64`.
///
/// This function wraps the `LLVMGetEnumAttributeValue` function from the LLVM core library. It returns the
/// numeric value associated with the enum attribute represented by `self`. Enum attributes in LLVM IR typically
/// represent attributes that have a fixed set of possible values, and this function allows you to access the value
/// of such attributes.
///
/// # Returns
///
/// Returns a `u64` representing the value of the enum attribute.
#[must_use]
pub fn get_enum_attribute_value(&self) -> u64 {
unsafe { core::LLVMGetEnumAttributeValue(self.0) }
}
/// Create a type attribute
///
/// # Details
///
/// Creates a type attribute in the specified LLVM context.
///
/// This function wraps the `LLVMCreateTypeAttribute` function from the LLVM core library. It creates and returns
/// a type attribute with the specified kind ID and associated type within the given LLVM context. Type attributes
/// are used to annotate functions, instructions, or other entities with additional type information in LLVM IR.
///
/// # Parameters
///
/// - `context`: A reference to the `ContextRef` in which the type attribute will be created.
/// - `kind_id`: A `u32` representing the kind ID of the type attribute. This ID specifies the kind of the attribute.
/// - `type_ref`: A reference to the `TypeRef` representing the type associated with the attribute.
///
/// # Returns
///
/// Returns an instance of `AttributeRef` representing the created type attribute.
#[must_use]
pub fn create_type_attribute(context: &ContextRef, kind_id: u32, type_ref: &TypeRef) -> Self {
let attr = unsafe {
core::LLVMCreateTypeAttribute(context.get_ref(), kind_id, type_ref.get_ref())
};
Self(attr)
}
/// Get the type attribute's value.
///
/// # Details
///
/// Retrieves the type value of a type attribute.
///
/// This function wraps the `LLVMGetTypeAttributeValue` function from the LLVM core library. It returns the type
/// associated with the type attribute represented by `self`. This function is useful for accessing the type information
/// stored within a type attribute in LLVM IR.
///
/// # Returns
///
/// Returns a `TypeRef` representing the type value associated with the type attribute.
#[must_use]
pub fn get_type_attribute_value(&self) -> TypeRef {
let type_ref = unsafe { core::LLVMGetTypeAttributeValue(self.0) };
type_ref.into()
}
/// Create a string attribute.
///
/// # Details
///
/// Creates a string attribute in the specified LLVM context.
///
/// This function wraps the `LLVMCreateStringAttribute` function from the LLVM core library. It creates and returns
/// a string attribute with the specified key and value within the given LLVM context. String attributes in LLVM IR
/// are typically used to annotate functions, instructions, or other entities with additional metadata in the form of key-value pairs.
///
/// # Parameters
///
/// - `context`: A reference to the `ContextRef` in which the string attribute will be created.
/// - `key`: A string slice (`&str`) representing the key (kind) of the attribute.
/// - `value`: A string slice (`&str`) representing the value of the attribute.
///
/// # Returns
///
/// Returns an instance of `AttributeRef` representing the created string attribute.
#[must_use]
pub fn create_string_attribute(context: &ContextRef, key: &str, value: &str) -> Self {
let c_key = CString::from(key);
let c_value = CString::from(value);
let attr = unsafe {
core::LLVMCreateStringAttribute(
context.get_ref(),
c_key.as_ptr(),
*CUint::from(c_key.to_bytes().len()),
c_value.as_ptr(),
*CUint::from(c_value.to_bytes().len()),
)
};
Self(attr)
}
/// Get the string attribute's kind.
///
/// # Details
///
/// Retrieves the kind (key) of a string attribute as a `String`.
///
/// This function wraps the `LLVMGetStringAttributeKind` function from the LLVM core library. It returns the kind
/// or key associated with a string attribute represented by `self`. The kind is returned as a `String` if it exists;
/// otherwise, `None` is returned. This function is useful for extracting the key part of key-value pair attributes in LLVM IR.
///
/// # Returns
///
/// Returns an `Option<String>`:
/// - `Some(String)` containing the attribute kind (key) if it exists.
/// - `None` if the attribute has no kind or the kind could not be retrieved.
#[must_use]
pub fn get_string_attribute_kind(&self) -> Option<String> {
let mut length = *CUint::from(0_usize);
unsafe {
let c_str = core::LLVMGetStringAttributeKind(self.0, &mut length);
if c_str.is_null() {
return None;
}
Some(CStr::new(c_str).to_string())
}
}
/// Get the string attribute's value.
///
/// # Details
///
/// Retrieves the value of a string attribute as a `String`.
///
/// This function wraps the `LLVMGetStringAttributeValue` function from the LLVM core library. It returns the value
/// associated with a string attribute represented by `self`. The value is returned as a `String` if the attribute has
/// a value; otherwise, `None` is returned. This function is useful for extracting the value part of key-value pair
/// attributes in LLVM IR.
///
/// # Returns
///
/// Returns an `Option<String>`:
/// - `Some(String)` containing the attribute value if it exists.
/// - `None` if the attribute has no value or the value could not be retrieved.
#[must_use]
pub fn get_string_attribute_value(&self) -> Option<String> {
let mut length = *CUint::from(0_usize);
unsafe {
let c_str = core::LLVMGetStringAttributeValue(self.get_ref(), &mut length);
if c_str.is_null() {
return None;
}
Some(CStr::new(c_str).to_string())
}
}
/// Check for the types of attributes.
///
/// # Details
///
/// Checks whether the attribute is a string attribute.
///
/// This function wraps the `LLVMIsStringAttribute` function from the LLVM core library. It determines whether
/// the attribute represented by `self` is a string attribute. String attributes are typically key-value pairs
/// where the key is a string and the value may also be a string or other data.
///
/// # Returns
///
/// Returns `true` if the attribute is a string attribute, otherwise returns `false`.
#[must_use]
pub fn is_enum(&self) -> bool {
unsafe { core::LLVMIsEnumAttribute(self.get_ref()) != 0 }
}
/// Check for the types of attributes.
#[must_use]
pub fn is_string_attribute(&self) -> bool {
unsafe { core::LLVMIsStringAttribute(self.get_ref()) != 0 }
}
/// Check for the types of attributes.
///
/// # Details
///
/// Checks whether the attribute is a type attribute.
///
/// This function wraps the `LLVMIsTypeAttribute` function from the LLVM core library. It determines whether
/// the attribute represented by `self` is a type attribute. Type attributes are associated with types rather than
/// with functions or parameters.
///
/// # Returns
///
/// Returns `true` if the attribute is a type attribute, otherwise returns `false`.
#[must_use]
pub fn is_type_attribute(&self) -> bool {
unsafe { core::LLVMIsTypeAttribute(self.get_ref()) != 0 }
}
}
/// LLVM Diagnostic Info structure wrapper
pub struct DiagnosticInfoRef(LLVMDiagnosticInfoRef);
impl From<LLVMDiagnosticInfoRef> for DiagnosticInfoRef {
fn from(value: LLVMDiagnosticInfoRef) -> Self {
Self(value)
}
}
impl GetRef for DiagnosticInfoRef {
type RawRef = LLVMDiagnosticInfoRef;
fn get_ref(&self) -> Self::RawRef {
self.0
}
}
impl DiagnosticInfoRef {
/// Return a string representation of the `DiagnosticInfo`.
///
/// # Details
///
/// This function wraps the `LLVMGetDiagInfoDescription` function from the LLVM core library. It retrieves a description
/// of the diagnostic information represented by `self` as a `String`. The description provides a human-readable explanation
/// of the diagnostic. After obtaining the string, the memory is freed using `LLVMDisposeMessage`.
///
/// # Returns
///
/// Returns an `Option<String>`:
/// - `Some(String)` containing the description of the diagnostic if successful.
/// - `None` if the description could not be retrieved.
///
/// # Safety
///
/// This function allocates memory for the string, which is freed using `LLVMDisposeMessage`.
#[must_use]
pub fn get_description(&self) -> Option<String> {
unsafe {
let c_str = core::LLVMGetDiagInfoDescription(self.get_ref());
if c_str.is_null() {
return None;
}
let value = CStr::new(c_str).to_string();
// Dispose message
core::LLVMDisposeMessage(c_str);
Some(value)
}
}
/// Return an enum `DiagnosticSeverity` type
///
/// # Details
///
/// Retrieves the severity level of the diagnostic information.
///
/// This function wraps the `LLVMGetDiagInfoSeverity` function from the LLVM core library. It returns the severity
/// level of the diagnostic information represented by `self`. The severity level indicates the nature of the diagnostic,
/// such as whether it is an error, warning, remark, or note.
///
/// # Returns
///
/// Returns a `DiagnosticSeverity` enum variant representing the severity level of the diagnostic.
#[must_use]
pub fn get_severity(&self) -> DiagnosticSeverity {
unsafe {
let severity = core::LLVMGetDiagInfoSeverity(self.get_ref());
DiagnosticSeverity::from(severity)
}
}
}