]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/declare.rs
Generalized base.rs#call_memcpy and everything that it uses
[rust.git] / src / librustc_codegen_llvm / declare.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //! Declare various LLVM values.
11 //!
12 //! Prefer using functions and methods from this module rather than calling LLVM
13 //! functions directly. These functions do some additional work to ensure we do
14 //! the right thing given the preconceptions of codegen.
15 //!
16 //! Some useful guidelines:
17 //!
18 //! * Use declare_* family of methods if you are declaring, but are not
19 //!   interested in defining the Value they return.
20 //! * Use define_* family of methods when you might be defining the Value.
21 //! * When in doubt, define.
22
23 use llvm;
24 use llvm::AttributePlace::Function;
25 use rustc::ty::{self, PolyFnSig};
26 use rustc::ty::layout::LayoutOf;
27 use rustc::session::config::Sanitizer;
28 use rustc_data_structures::small_c_str::SmallCStr;
29 use rustc_target::spec::PanicStrategy;
30 use abi::{Abi, FnType, FnTypeExt};
31 use attributes;
32 use context::CodegenCx;
33 use type_::Type;
34 use value::{Value, ValueTrait};
35
36
37 /// Declare a global value.
38 ///
39 /// If there’s a value with the same name already declared, the function will
40 /// return its Value instead.
41 pub fn declare_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> &'ll Value {
42     debug!("declare_global(name={:?})", name);
43     let namebuf = SmallCStr::new(name);
44     unsafe {
45         llvm::LLVMRustGetOrInsertGlobal(cx.llmod, namebuf.as_ptr(), ty)
46     }
47 }
48
49
50 /// Declare a function.
51 ///
52 /// If there’s a value with the same name already declared, the function will
53 /// update the declaration and return existing Value instead.
54 fn declare_raw_fn<Value : ?Sized>(
55     cx: &CodegenCx<'ll, '_, &'ll Value>,
56     name: &str,
57     callconv: llvm::CallConv,
58     ty: &'ll Type,
59 ) -> &'ll Value where Value : ValueTrait {
60     debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
61     let namebuf = SmallCStr::new(name);
62     let llfn = unsafe {
63         llvm::LLVMRustGetOrInsertFunction(cx.llmod, namebuf.as_ptr(), ty)
64     };
65
66     llvm::SetFunctionCallConv(llfn, callconv);
67     // Function addresses in Rust are never significant, allowing functions to
68     // be merged.
69     llvm::SetUnnamedAddr(llfn, true);
70
71     if cx.tcx.sess.opts.cg.no_redzone
72         .unwrap_or(cx.tcx.sess.target.target.options.disable_redzone) {
73         llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
74     }
75
76     if let Some(ref sanitizer) = cx.tcx.sess.opts.debugging_opts.sanitizer {
77         match *sanitizer {
78             Sanitizer::Address => {
79                 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
80             },
81             Sanitizer::Memory => {
82                 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
83             },
84             Sanitizer::Thread => {
85                 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
86             },
87             _ => {}
88         }
89     }
90
91     match cx.tcx.sess.opts.cg.opt_level.as_ref().map(String::as_ref) {
92         Some("s") => {
93             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
94         },
95         Some("z") => {
96             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
97             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
98         },
99         _ => {},
100     }
101
102     if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
103         attributes::unwind(llfn, false);
104     }
105
106     attributes::non_lazy_bind(cx.sess(), llfn);
107
108     Value::of_llvm(llfn)
109 }
110
111
112 /// Declare a C ABI function.
113 ///
114 /// Only use this for foreign function ABIs and glue. For Rust functions use
115 /// `declare_fn` instead.
116 ///
117 /// If there’s a value with the same name already declared, the function will
118 /// update the declaration and return existing Value instead.
119 pub fn declare_cfn<Value : ?Sized>(
120     cx: &CodegenCx<'ll, '_, &'ll Value>,
121     name: &str,
122     fn_type: &'ll Type
123 ) -> &'ll Value where Value : ValueTrait {
124     declare_raw_fn(cx, name, llvm::CCallConv, fn_type)
125 }
126
127
128 /// Declare a Rust function.
129 ///
130 /// If there’s a value with the same name already declared, the function will
131 /// update the declaration and return existing Value instead.
132 pub fn declare_fn(
133     cx: &CodegenCx<'ll, 'tcx>,
134     name: &str,
135     sig: PolyFnSig<'tcx>,
136 ) -> &'ll Value {
137     debug!("declare_rust_fn(name={:?}, sig={:?})", name, sig);
138     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
139     debug!("declare_rust_fn (after region erasure) sig={:?}", sig);
140
141     let fty = FnType::new(cx, sig, &[]);
142     let llfn = declare_raw_fn(cx, name, fty.llvm_cconv(), fty.llvm_type(cx));
143
144     if cx.layout_of(sig.output()).abi.is_uninhabited() {
145         llvm::Attribute::NoReturn.apply_llfn(Function, llfn);
146     }
147
148     if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
149         attributes::unwind(llfn, false);
150     }
151
152     fty.apply_attrs_llfn(llfn);
153
154     llfn
155 }
156
157
158 /// Declare a global with an intention to define it.
159 ///
160 /// Use this function when you intend to define a global. This function will
161 /// return None if the name already has a definition associated with it. In that
162 /// case an error should be reported to the user, because it usually happens due
163 /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
164 pub fn define_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> Option<&'ll Value> {
165     if get_defined_value(cx, name).is_some() {
166         None
167     } else {
168         Some(declare_global(cx, name, ty))
169     }
170 }
171
172 /// Declare a private global
173 ///
174 /// Use this function when you intend to define a global without a name.
175 pub fn define_private_global(cx: &CodegenCx<'ll, '_, &'ll Value>, ty: &'ll Type) -> &'ll Value {
176     unsafe {
177         llvm::LLVMRustInsertPrivateGlobal(cx.llmod, ty)
178     }
179 }
180
181 /// Declare a Rust function with an intention to define it.
182 ///
183 /// Use this function when you intend to define a function. This function will
184 /// return panic if the name already has a definition associated with it. This
185 /// can happen with #[no_mangle] or #[export_name], for example.
186 pub fn define_fn(
187     cx: &CodegenCx<'ll, 'tcx>,
188     name: &str,
189     fn_sig: PolyFnSig<'tcx>,
190 ) -> &'ll Value {
191     if get_defined_value(cx, name).is_some() {
192         cx.sess().fatal(&format!("symbol `{}` already defined", name))
193     } else {
194         declare_fn(cx, name, fn_sig)
195     }
196 }
197
198 /// Declare a Rust function with an intention to define it.
199 ///
200 /// Use this function when you intend to define a function. This function will
201 /// return panic if the name already has a definition associated with it. This
202 /// can happen with #[no_mangle] or #[export_name], for example.
203 pub fn define_internal_fn(
204     cx: &CodegenCx<'ll, 'tcx>,
205     name: &str,
206     fn_sig: PolyFnSig<'tcx>,
207 ) -> &'ll Value {
208     let llfn = define_fn(cx, name, fn_sig);
209     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
210     llfn
211 }
212
213
214 /// Get declared value by name.
215 pub fn get_declared_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
216     debug!("get_declared_value(name={:?})", name);
217     let namebuf = SmallCStr::new(name);
218     unsafe { llvm::LLVMRustGetNamedValue(cx.llmod, namebuf.as_ptr()) }
219 }
220
221 /// Get defined or externally defined (AvailableExternally linkage) value by
222 /// name.
223 pub fn get_defined_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
224     get_declared_value(cx, name).and_then(|val|{
225         let declaration = unsafe {
226             llvm::LLVMIsDeclaration(val) != 0
227         };
228         if !declaration {
229             Some(val)
230         } else {
231             None
232         }
233     })
234 }