-
Notifications
You must be signed in to change notification settings - Fork 870
/
Copy pathcode.rs
12951 lines (12538 loc) · 547 KB
/
code.rs
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use super::{
intrinsics::{
tbaa_label, type_to_llvm, CtxType, FunctionCache, GlobalCache, Intrinsics, MemoryCache,
},
// stackmap::{StackmapEntry, StackmapEntryKind, StackmapRegistry, ValueSemantic},
state::{ControlFrame, ExtraInfo, IfElseState, State},
};
use inkwell::{
attributes::AttributeLoc,
builder::Builder,
context::Context,
module::{Linkage, Module},
passes::PassBuilderOptions,
targets::{FileType, TargetMachine},
types::{BasicType, BasicTypeEnum, FloatMathType, IntType, PointerType, VectorType},
values::{
AnyValue, BasicMetadataValueEnum, BasicValue, BasicValueEnum, CallSiteValue, FloatValue,
FunctionValue, InstructionOpcode, InstructionValue, IntValue, PhiValue, PointerValue,
VectorValue,
},
AddressSpace, AtomicOrdering, AtomicRMWBinOp, DLLStorageClass, FloatPredicate, IntPredicate,
};
use itertools::Itertools;
use smallvec::SmallVec;
use target_lexicon::BinaryFormat;
use crate::{
abi::{get_abi, Abi, G0M0FunctionKind, LocalFunctionG0M0params},
config::{CompiledKind, LLVM},
error::{err, err_nt},
object_file::{load_object_file, CompiledFunction},
};
use wasmer_compiler::{
from_binaryreadererror_wasmerror,
types::{
relocation::RelocationTarget,
symbols::{Symbol, SymbolRegistry},
},
wasmparser::{Catch, MemArg, Operator},
wpheaptype_to_type, wptype_to_type, FunctionBinaryReader, FunctionBodyData,
MiddlewareBinaryReader, ModuleMiddlewareChain, ModuleTranslationState,
};
use wasmer_types::{entity::PrimaryMap, TagIndex};
use wasmer_types::{
CompileError, FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex,
ModuleInfo, SignatureIndex, TableIndex, Type,
};
use wasmer_vm::{MemoryStyle, TableStyle, VMOffsets};
const FUNCTION_SECTION_ELF: &str = "__TEXT,wasmer_function";
const FUNCTION_SECTION_MACHO: &str = "__TEXT";
const FUNCTION_SEGMENT_MACHO: &str = "wasmer_function";
pub struct FuncTranslator {
ctx: Context,
target_machine: TargetMachine,
abi: Box<dyn Abi>,
binary_fmt: BinaryFormat,
func_section: String,
}
impl FuncTranslator {
pub fn new(
target_machine: TargetMachine,
binary_fmt: BinaryFormat,
) -> Result<Self, CompileError> {
let abi = get_abi(&target_machine);
Ok(Self {
ctx: Context::create(),
target_machine,
abi,
func_section: match binary_fmt {
BinaryFormat::Elf => FUNCTION_SECTION_ELF.to_string(),
BinaryFormat::Macho => FUNCTION_SEGMENT_MACHO.to_string(),
_ => {
return Err(CompileError::UnsupportedTarget(format!(
"Unsupported binary format: {binary_fmt:?}"
)))
}
},
binary_fmt,
})
}
#[allow(clippy::too_many_arguments)]
pub fn translate_to_module(
&self,
wasm_module: &ModuleInfo,
module_translation: &ModuleTranslationState,
local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData,
config: &LLVM,
memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &PrimaryMap<TableIndex, TableStyle>,
symbol_registry: &dyn SymbolRegistry,
) -> Result<Module, CompileError> {
// The function type, used for the callbacks.
let function = CompiledKind::Local(*local_func_index);
let func_index = wasm_module.func_index(*local_func_index);
let function_name =
symbol_registry.symbol_to_name(Symbol::LocalFunction(*local_func_index));
let g0m0_is_enabled = config.enable_g0m0_opt;
let func_kind = if g0m0_is_enabled {
Some(G0M0FunctionKind::Local)
} else {
None
};
let module_name = match wasm_module.name.as_ref() {
None => format!("<anonymous module> function {function_name}"),
Some(module_name) => format!("module {module_name} function {function_name}"),
};
let module = self.ctx.create_module(module_name.as_str());
let target_machine = &self.target_machine;
let target_triple = target_machine.get_triple();
let target_data = target_machine.get_target_data();
module.set_triple(&target_triple);
module.set_data_layout(&target_data.get_data_layout());
let wasm_fn_type = wasm_module
.signatures
.get(wasm_module.functions[func_index])
.unwrap();
// TODO: pointer width
let offsets = VMOffsets::new(8, wasm_module);
let intrinsics = Intrinsics::declare(&module, &self.ctx, &target_data, &self.binary_fmt);
let (func_type, func_attrs) = self.abi.func_type_to_llvm(
&self.ctx,
&intrinsics,
Some(&offsets),
wasm_fn_type,
func_kind,
)?;
let func = module.add_function(&function_name, func_type, Some(Linkage::External));
for (attr, attr_loc) in &func_attrs {
func.add_attribute(*attr_loc, *attr);
}
func.add_attribute(AttributeLoc::Function, intrinsics.stack_probe);
func.add_attribute(AttributeLoc::Function, intrinsics.uwtable);
func.add_attribute(AttributeLoc::Function, intrinsics.frame_pointer);
let section = match self.binary_fmt {
BinaryFormat::Elf => FUNCTION_SECTION_ELF.to_string(),
BinaryFormat::Macho => {
format!("{FUNCTION_SECTION_MACHO},{FUNCTION_SEGMENT_MACHO}")
}
_ => {
return Err(CompileError::UnsupportedTarget(format!(
"Unsupported binary format: {:?}",
self.binary_fmt
)))
}
};
func.set_personality_function(intrinsics.personality);
func.as_global_value().set_section(Some(§ion));
func.set_linkage(Linkage::DLLExport);
func.as_global_value()
.set_dll_storage_class(DLLStorageClass::Export);
let entry = self.ctx.append_basic_block(func, "entry");
let start_of_code = self.ctx.append_basic_block(func, "start_of_code");
let return_ = self.ctx.append_basic_block(func, "return");
let alloca_builder = self.ctx.create_builder();
let cache_builder = self.ctx.create_builder();
let builder = self.ctx.create_builder();
cache_builder.position_at_end(entry);
let br = err!(cache_builder.build_unconditional_branch(start_of_code));
alloca_builder.position_before(&br);
cache_builder.position_before(&br);
builder.position_at_end(start_of_code);
let mut state = State::new();
builder.position_at_end(return_);
let phis: SmallVec<[PhiValue; 1]> = wasm_fn_type
.results()
.iter()
.map(|&wasm_ty| {
type_to_llvm(&intrinsics, wasm_ty).map(|ty| builder.build_phi(ty, "").unwrap())
})
.collect::<Result<_, _>>()?;
state.push_block(return_, phis);
builder.position_at_end(start_of_code);
let mut reader = MiddlewareBinaryReader::new_with_offset(
function_body.data,
function_body.module_offset,
);
reader.set_middleware_chain(
config
.middlewares
.generate_function_middleware_chain(*local_func_index),
);
let mut params = vec![];
let first_param =
if func_type.get_return_type().is_none() && wasm_fn_type.results().len() > 1 {
if g0m0_is_enabled {
4
} else {
2
}
} else if g0m0_is_enabled {
3
} else {
1
};
let mut is_first_alloca = true;
let mut insert_alloca = |ty, name| -> Result<PointerValue, CompileError> {
let alloca = err!(alloca_builder.build_alloca(ty, name));
if is_first_alloca {
alloca_builder.position_at(entry, &alloca.as_instruction_value().unwrap());
is_first_alloca = false;
}
Ok(alloca)
};
for idx in 0..wasm_fn_type.params().len() {
let ty = wasm_fn_type.params()[idx];
let ty = type_to_llvm(&intrinsics, ty)?;
let value = func
.get_nth_param((idx as u32).checked_add(first_param).unwrap())
.unwrap();
let alloca = insert_alloca(ty, "param")?;
err!(cache_builder.build_store(alloca, value));
params.push((ty, alloca));
}
let mut locals = vec![];
let num_locals = reader.read_local_count()?;
for _ in 0..num_locals {
let (count, ty) = reader.read_local_decl()?;
let ty = err!(wptype_to_type(ty));
let ty = type_to_llvm(&intrinsics, ty)?;
for _ in 0..count {
let alloca = insert_alloca(ty, "local")?;
err!(cache_builder.build_store(alloca, ty.const_zero()));
locals.push((ty, alloca));
}
}
let mut params_locals = params.clone();
params_locals.extend(locals.iter().cloned());
let mut g0m0_params = None;
if g0m0_is_enabled {
let value = self.abi.get_g0_ptr_param(&func);
let g0 = insert_alloca(intrinsics.i32_ty.as_basic_type_enum(), "g0")?;
err!(cache_builder.build_store(g0, value));
g0.set_name("g0");
let m0 = self.abi.get_m0_ptr_param(&func);
m0.set_name("m0_base_ptr");
g0m0_params = Some((g0, m0));
}
let mut fcg = LLVMFunctionCodeGenerator {
g0m0: g0m0_params,
context: &self.ctx,
builder,
alloca_builder,
intrinsics: &intrinsics,
state,
function: func,
locals: params_locals,
ctx: CtxType::new(wasm_module, &func, &cache_builder, &*self.abi, config),
unreachable_depth: 0,
memory_styles,
_table_styles,
module: &module,
module_translation,
wasm_module,
symbol_registry,
abi: &*self.abi,
config,
exception_types_cache: HashMap::new(),
tags_cache: HashMap::new(),
ptr_size: self
.target_machine
.get_target_data()
.get_pointer_byte_size(None),
binary_fmt: self.binary_fmt,
};
fcg.ctx.add_func(
func_index,
func.as_global_value().as_pointer_value(),
func_type,
fcg.ctx.basic(),
&func_attrs,
);
while fcg.state.has_control_frames() {
let pos = reader.current_position() as u32;
let op = reader.read_operator()?;
fcg.translate_operator(op, pos)?;
}
fcg.finalize(wasm_fn_type)?;
if let Some(ref callbacks) = config.callbacks {
callbacks.preopt_ir(&function, &module);
}
let mut passes = vec![];
if config.enable_verifier {
passes.push("verify");
}
passes.push("sccp");
passes.push("early-cse");
//passes.push("deadargelim");
passes.push("adce");
passes.push("sroa");
passes.push("aggressive-instcombine");
passes.push("jump-threading");
//passes.push("ipsccp");
passes.push("simplifycfg");
passes.push("reassociate");
passes.push("loop-rotate");
passes.push("indvars");
//passes.push("lcssa");
//passes.push("licm");
//passes.push("instcombine");
passes.push("sccp");
passes.push("reassociate");
passes.push("simplifycfg");
passes.push("gvn");
passes.push("memcpyopt");
passes.push("dse");
passes.push("dce");
//passes.push("instcombine");
passes.push("reassociate");
passes.push("simplifycfg");
passes.push("mem2reg");
//let llvm_dump_path = std::env::var("WASMER_LLVM_DUMP_DIR");
//if let Ok(ref llvm_dump_path) = llvm_dump_path {
// let path = std::path::Path::new(llvm_dump_path);
// if !path.exists() {
// std::fs::create_dir_all(path).unwrap()
// }
// let path = path.join(format!("{function_name}.ll"));
// _ = module.print_to_file(path).unwrap();
//}
module
.run_passes(
passes.join(",").as_str(),
target_machine,
PassBuilderOptions::create(),
)
.unwrap();
//if let Ok(ref llvm_dump_path) = llvm_dump_path {
// if !passes.is_empty() {
// let path =
// std::path::Path::new(llvm_dump_path).join(format!("{function_name}_opt.ll"));
// _ = module.print_to_file(path).unwrap();
// }
//}
if let Some(ref callbacks) = config.callbacks {
callbacks.postopt_ir(&function, &module);
}
Ok(module)
}
#[allow(clippy::too_many_arguments)]
pub fn translate(
&self,
wasm_module: &ModuleInfo,
module_translation: &ModuleTranslationState,
local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData,
config: &LLVM,
memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
table_styles: &PrimaryMap<TableIndex, TableStyle>,
symbol_registry: &dyn SymbolRegistry,
) -> Result<CompiledFunction, CompileError> {
let module = self.translate_to_module(
wasm_module,
module_translation,
local_func_index,
function_body,
config,
memory_styles,
table_styles,
symbol_registry,
)?;
let function = CompiledKind::Local(*local_func_index);
let target_machine = &self.target_machine;
let memory_buffer = target_machine
.write_to_memory_buffer(&module, FileType::Object)
.unwrap();
if let Some(ref callbacks) = config.callbacks {
callbacks.obj_memory_buffer(&function, &memory_buffer);
}
let mem_buf_slice = memory_buffer.as_slice();
load_object_file(
mem_buf_slice,
&self.func_section,
RelocationTarget::LocalFunc(*local_func_index),
|name: &str| {
Ok({
let name = if matches!(self.binary_fmt, BinaryFormat::Macho) {
if name.starts_with("_") {
name.replacen("_", "", 1)
} else {
name.to_string()
}
} else {
name.to_string()
};
if let Some(Symbol::LocalFunction(local_func_index)) =
symbol_registry.name_to_symbol(&name)
{
Some(RelocationTarget::LocalFunc(local_func_index))
} else {
None
}
})
},
self.binary_fmt,
)
}
}
impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
// Create a vector where each lane contains the same value.
fn splat_vector(
&self,
value: BasicValueEnum<'ctx>,
vec_ty: VectorType<'ctx>,
) -> Result<VectorValue<'ctx>, CompileError> {
// Use insert_element to insert the element into an undef vector, then use
// shuffle vector to copy that lane to all lanes.
err_nt!(self.builder.build_shuffle_vector(
err!(self.builder.build_insert_element(
vec_ty.get_undef(),
value,
self.intrinsics.i32_zero,
"",
)),
vec_ty.get_undef(),
self.intrinsics
.i32_ty
.vec_type(vec_ty.get_size())
.const_zero(),
"",
))
}
// Convert floating point vector to integer and saturate when out of range.
// https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md
#[allow(clippy::too_many_arguments)]
fn trunc_sat<T: FloatMathType<'ctx>>(
&self,
fvec_ty: T,
ivec_ty: T::MathConvType,
lower_bound: u64, // Exclusive (least representable value)
upper_bound: u64, // Exclusive (greatest representable value)
int_min_value: u64,
int_max_value: u64,
value: IntValue<'ctx>,
) -> Result<VectorValue<'ctx>, CompileError> {
// a) Compare vector with itself to identify NaN lanes.
// b) Compare vector with splat of inttofp(upper_bound) to identify
// lanes that need to saturate to max.
// c) Compare vector with splat of inttofp(lower_bound) to identify
// lanes that need to saturate to min.
// d) Use vector select (not shuffle) to pick from either the
// splat vector or the input vector depending on whether the
// comparison indicates that we have an unrepresentable value. Replace
// unrepresentable values with zero.
// e) Now that the value is safe, fpto[su]i it.
// f) Use our previous comparison results to replace certain zeros with
// int_min or int_max.
let fvec_ty = fvec_ty.as_basic_type_enum().into_vector_type();
let ivec_ty = ivec_ty.as_basic_type_enum().into_vector_type();
let fvec_element_ty = fvec_ty.get_element_type().into_float_type();
let ivec_element_ty = ivec_ty.get_element_type().into_int_type();
let is_signed = int_min_value != 0;
let int_min_value = self.splat_vector(
ivec_element_ty
.const_int(int_min_value, is_signed)
.as_basic_value_enum(),
ivec_ty,
)?;
let int_max_value = self.splat_vector(
ivec_element_ty
.const_int(int_max_value, is_signed)
.as_basic_value_enum(),
ivec_ty,
)?;
let lower_bound = if is_signed {
err!(self.builder.build_signed_int_to_float(
ivec_element_ty.const_int(lower_bound, is_signed),
fvec_element_ty,
"",
))
} else {
err!(self.builder.build_unsigned_int_to_float(
ivec_element_ty.const_int(lower_bound, is_signed),
fvec_element_ty,
"",
))
};
let upper_bound = if is_signed {
err!(self.builder.build_signed_int_to_float(
ivec_element_ty.const_int(upper_bound, is_signed),
fvec_element_ty,
"",
))
} else {
err!(self.builder.build_unsigned_int_to_float(
ivec_element_ty.const_int(upper_bound, is_signed),
fvec_element_ty,
"",
))
};
let value = err!(self.builder.build_bit_cast(value, fvec_ty, "")).into_vector_value();
let zero = fvec_ty.const_zero();
let lower_bound = self.splat_vector(lower_bound.as_basic_value_enum(), fvec_ty)?;
let upper_bound = self.splat_vector(upper_bound.as_basic_value_enum(), fvec_ty)?;
let nan_cmp =
err!(self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan"));
let above_upper_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::OGT,
value,
upper_bound,
"above_upper_bound",
));
let below_lower_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::OLT,
value,
lower_bound,
"below_lower_bound",
));
let not_representable = err!(self.builder.build_or(
err!(self.builder.build_or(nan_cmp, above_upper_bound_cmp, "")),
below_lower_bound_cmp,
"not_representable_as_int",
));
let value =
err!(self
.builder
.build_select(not_representable, zero, value, "safe_to_convert"))
.into_vector_value();
let value = if is_signed {
self.builder
.build_float_to_signed_int(value, ivec_ty, "as_int")
} else {
self.builder
.build_float_to_unsigned_int(value, ivec_ty, "as_int")
};
let value = err!(value);
let value =
err!(self
.builder
.build_select(above_upper_bound_cmp, int_max_value, value, ""))
.into_vector_value();
err_nt!(self
.builder
.build_select(below_lower_bound_cmp, int_min_value, value, "")
.map(|v| v.into_vector_value()))
}
// Convert floating point vector to integer and saturate when out of range.
// https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md
#[allow(clippy::too_many_arguments)]
fn trunc_sat_into_int<T: FloatMathType<'ctx>>(
&self,
fvec_ty: T,
ivec_ty: T::MathConvType,
lower_bound: u64, // Exclusive (least representable value)
upper_bound: u64, // Exclusive (greatest representable value)
int_min_value: u64,
int_max_value: u64,
value: IntValue<'ctx>,
) -> Result<IntValue<'ctx>, CompileError> {
let res = self.trunc_sat(
fvec_ty,
ivec_ty,
lower_bound,
upper_bound,
int_min_value,
int_max_value,
value,
)?;
err_nt!(self
.builder
.build_bit_cast(res, self.intrinsics.i128_ty, "")
.map(|v| v.into_int_value()))
}
// Convert floating point vector to integer and saturate when out of range.
// https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md
fn trunc_sat_scalar(
&self,
int_ty: IntType<'ctx>,
lower_bound: u64, // Exclusive (least representable value)
upper_bound: u64, // Exclusive (greatest representable value)
int_min_value: u64,
int_max_value: u64,
value: FloatValue<'ctx>,
) -> Result<IntValue<'ctx>, CompileError> {
// TODO: this is a scalarized version of the process in trunc_sat. Either
// we should merge with trunc_sat, or we should simplify this function.
// a) Compare value with itself to identify NaN.
// b) Compare value inttofp(upper_bound) to identify values that need to
// saturate to max.
// c) Compare value with inttofp(lower_bound) to identify values that need
// to saturate to min.
// d) Use select to pick from either zero or the input vector depending on
// whether the comparison indicates that we have an unrepresentable
// value.
// e) Now that the value is safe, fpto[su]i it.
// f) Use our previous comparison results to replace certain zeros with
// int_min or int_max.
let is_signed = int_min_value != 0;
let int_min_value = int_ty.const_int(int_min_value, is_signed);
let int_max_value = int_ty.const_int(int_max_value, is_signed);
let lower_bound = if is_signed {
err!(self.builder.build_signed_int_to_float(
int_ty.const_int(lower_bound, is_signed),
value.get_type(),
"",
))
} else {
err!(self.builder.build_unsigned_int_to_float(
int_ty.const_int(lower_bound, is_signed),
value.get_type(),
"",
))
};
let upper_bound = if is_signed {
err!(self.builder.build_signed_int_to_float(
int_ty.const_int(upper_bound, is_signed),
value.get_type(),
"",
))
} else {
err!(self.builder.build_unsigned_int_to_float(
int_ty.const_int(upper_bound, is_signed),
value.get_type(),
"",
))
};
let zero = value.get_type().const_zero();
let nan_cmp =
err!(self
.builder
.build_float_compare(FloatPredicate::UNO, value, zero, "nan"));
let above_upper_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::OGT,
value,
upper_bound,
"above_upper_bound",
));
let below_lower_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::OLT,
value,
lower_bound,
"below_lower_bound",
));
let not_representable = err!(self.builder.build_or(
err!(self.builder.build_or(nan_cmp, above_upper_bound_cmp, "")),
below_lower_bound_cmp,
"not_representable_as_int",
));
let value =
err!(self
.builder
.build_select(not_representable, zero, value, "safe_to_convert"))
.into_float_value();
let value = if is_signed {
err!(self
.builder
.build_float_to_signed_int(value, int_ty, "as_int"))
} else {
err!(self
.builder
.build_float_to_unsigned_int(value, int_ty, "as_int"))
};
let value =
err!(self
.builder
.build_select(above_upper_bound_cmp, int_max_value, value, ""))
.into_int_value();
let value =
err!(self
.builder
.build_select(below_lower_bound_cmp, int_min_value, value, ""))
.into_int_value();
err_nt!(self
.builder
.build_bit_cast(value, int_ty, "")
.map(|v| v.into_int_value()))
}
fn trap_if_not_representable_as_int(
&self,
lower_bound: u64, // Inclusive (not a trapping value)
upper_bound: u64, // Inclusive (not a trapping value)
value: FloatValue,
) -> Result<(), CompileError> {
let float_ty = value.get_type();
let int_ty = if float_ty == self.intrinsics.f32_ty {
self.intrinsics.i32_ty
} else {
self.intrinsics.i64_ty
};
let lower_bound =
err!(self
.builder
.build_bit_cast(int_ty.const_int(lower_bound, false), float_ty, ""))
.into_float_value();
let upper_bound =
err!(self
.builder
.build_bit_cast(int_ty.const_int(upper_bound, false), float_ty, ""))
.into_float_value();
// The 'U' in the float predicate is short for "unordered" which means that
// the comparison will compare true if either operand is a NaN. Thus, NaNs
// are out of bounds.
let above_upper_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::UGT,
value,
upper_bound,
"above_upper_bound",
));
let below_lower_bound_cmp = err!(self.builder.build_float_compare(
FloatPredicate::ULT,
value,
lower_bound,
"below_lower_bound",
));
let out_of_bounds = err!(self.builder.build_or(
above_upper_bound_cmp,
below_lower_bound_cmp,
"out_of_bounds",
));
let failure_block = self
.context
.append_basic_block(self.function, "conversion_failure_block");
let continue_block = self
.context
.append_basic_block(self.function, "conversion_success_block");
err!(self
.builder
.build_conditional_branch(out_of_bounds, failure_block, continue_block));
self.builder.position_at_end(failure_block);
let is_nan =
err!(self
.builder
.build_float_compare(FloatPredicate::UNO, value, value, "is_nan"));
let trap_code = err!(self.builder.build_select(
is_nan,
self.intrinsics.trap_bad_conversion_to_integer,
self.intrinsics.trap_illegal_arithmetic,
"",
));
err!(self
.builder
.build_call(self.intrinsics.throw_trap, &[trap_code.into()], "throw"));
err!(self.builder.build_unreachable());
self.builder.position_at_end(continue_block);
Ok(())
}
fn trap_if_zero_or_overflow(
&self,
left: IntValue,
right: IntValue,
) -> Result<(), CompileError> {
let int_type = left.get_type();
let (min_value, neg_one_value) = if int_type == self.intrinsics.i32_ty {
let min_value = int_type.const_int(i32::MIN as u64, false);
let neg_one_value = int_type.const_int(-1i32 as u32 as u64, false);
(min_value, neg_one_value)
} else if int_type == self.intrinsics.i64_ty {
let min_value = int_type.const_int(i64::MIN as u64, false);
let neg_one_value = int_type.const_int(-1i64 as u64, false);
(min_value, neg_one_value)
} else {
unreachable!()
};
let divisor_is_zero = err!(self.builder.build_int_compare(
IntPredicate::EQ,
right,
int_type.const_zero(),
"divisor_is_zero",
));
let should_trap = err!(self.builder.build_or(
divisor_is_zero,
err!(self.builder.build_and(
err!(self.builder.build_int_compare(
IntPredicate::EQ,
left,
min_value,
"left_is_min"
)),
err!(self.builder.build_int_compare(
IntPredicate::EQ,
right,
neg_one_value,
"right_is_neg_one",
)),
"div_will_overflow",
)),
"div_should_trap",
));
let should_trap = err!(self.builder.build_call(
self.intrinsics.expect_i1,
&[
should_trap.into(),
self.intrinsics.i1_ty.const_zero().into(),
],
"should_trap_expect",
))
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let shouldnt_trap_block = self
.context
.append_basic_block(self.function, "shouldnt_trap_block");
let should_trap_block = self
.context
.append_basic_block(self.function, "should_trap_block");
err!(self.builder.build_conditional_branch(
should_trap,
should_trap_block,
shouldnt_trap_block
));
self.builder.position_at_end(should_trap_block);
let trap_code = err!(self.builder.build_select(
divisor_is_zero,
self.intrinsics.trap_integer_division_by_zero,
self.intrinsics.trap_illegal_arithmetic,
"",
));
err!(self
.builder
.build_call(self.intrinsics.throw_trap, &[trap_code.into()], "throw"));
err!(self.builder.build_unreachable());
self.builder.position_at_end(shouldnt_trap_block);
Ok(())
}
fn trap_if_zero(&self, value: IntValue) -> Result<(), CompileError> {
let int_type = value.get_type();
let should_trap = err!(self.builder.build_int_compare(
IntPredicate::EQ,
value,
int_type.const_zero(),
"divisor_is_zero",
));
let should_trap = err!(self.builder.build_call(
self.intrinsics.expect_i1,
&[
should_trap.into(),
self.intrinsics.i1_ty.const_zero().into(),
],
"should_trap_expect",
))
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let shouldnt_trap_block = self
.context
.append_basic_block(self.function, "shouldnt_trap_block");
let should_trap_block = self
.context
.append_basic_block(self.function, "should_trap_block");
err!(self.builder.build_conditional_branch(
should_trap,
should_trap_block,
shouldnt_trap_block
));
self.builder.position_at_end(should_trap_block);
err!(self.builder.build_call(
self.intrinsics.throw_trap,
&[self.intrinsics.trap_integer_division_by_zero.into()],
"throw",
));
err!(self.builder.build_unreachable());
self.builder.position_at_end(shouldnt_trap_block);
Ok(())
}
fn v128_into_int_vec(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
int_vec_ty: VectorType<'ctx>,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
let (value, info) = if info.has_pending_f32_nan() {
let value = err!(self
.builder
.build_bit_cast(value, self.intrinsics.f32x4_ty, ""));
(self.canonicalize_nans(value)?, info.strip_pending())
} else if info.has_pending_f64_nan() {
let value = err!(self
.builder
.build_bit_cast(value, self.intrinsics.f64x2_ty, ""));
(self.canonicalize_nans(value)?, info.strip_pending())
} else {
(value, info)
};
Ok((
err!(self.builder.build_bit_cast(value, int_vec_ty, "")).into_vector_value(),
info,
))
}
fn v128_into_i8x16(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
self.v128_into_int_vec(value, info, self.intrinsics.i8x16_ty)
}
fn v128_into_i16x8(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
self.v128_into_int_vec(value, info, self.intrinsics.i16x8_ty)
}
fn v128_into_i32x4(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
self.v128_into_int_vec(value, info, self.intrinsics.i32x4_ty)
}
fn v128_into_i64x2(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
self.v128_into_int_vec(value, info, self.intrinsics.i64x2_ty)
}
// If the value is pending a 64-bit canonicalization, do it now.
// Return a f32x4 vector.
fn v128_into_f32x4(
&self,
value: BasicValueEnum<'ctx>,
info: ExtraInfo,
) -> Result<(VectorValue<'ctx>, ExtraInfo), CompileError> {
let (value, info) = if info.has_pending_f64_nan() {
let value = err!(self
.builder
.build_bit_cast(value, self.intrinsics.f64x2_ty, ""));
(self.canonicalize_nans(value)?, info.strip_pending())